home · contact · privacy
Server: Add animate things in field of view to THINGS_HERE results.
[plomrogue] / src / server / run.c
1 /* src/server/run.c
2  *
3  * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4  * or any later version. For details on its copyright, license, and warranties,
5  * see the file NOTICE in the root directory of the PlomRogue source package.
6  */
7
8 #define _POSIX_C_SOURCE 200809L /* strdup() */
9 #include "run.h"
10 #include <stddef.h> /* NULL */
11 #include <stdint.h> /* uint8_t, uint16_t, uint32_t, int16_t */
12 #include <stdio.h> /* FILE, printf(), fflush() */
13 #include <stdlib.h> /* atoi(), free() */
14 #include <string.h> /* strlen(), strcmp(), strncmp(), strdup() */
15 #include <time.h> /* time_t, time() */
16 #include <unistd.h> /* access() */
17 #include "../common/parse_file.h" /* set_err_line_options(), token_from_line(),
18                                    * err_line(), err_line_inc(), parse_val(),
19                                    * parestest_int()
20                                    */
21 #include "../common/readwrite.h" /* try_fopen(), try_fcose(), try_fwrite(),
22                                   * try_fgets(), textfile_width(), try_fputc(),
23                                   * atomic_write_finish(), build_temp_path()
24                                   */
25 #include "../common/rexit.h" /* exit_trouble(), exit_err() */
26 #include "../common/try_malloc.h" /* try_malloc() */
27 #include "ai.h" /* ai() */
28 #include "cleanup.h" /* unset_cleanup_flag() */
29 #include "god_commands.h" /* parse_god_command_(1|2|3)arg() */
30 #include "hardcoded_strings.h" /* s */
31 #include "io.h" /* io_round(), save_world() */
32 #include "things.h" /* Thing, ThingType, ThingInMemory, get_player(),
33                      * get_thing_action_id_by_name(), try_thing_proliferation()
34                      */
35 #include "world.h" /* world */
36
37
38
39 /* If "string" and "comparand" match in string, set "c_to_set" to value."  */
40 static uint8_t set_char_by_string_comparison(char * string, char * comparand,
41                                              char * c_to_set, char value);
42
43 /* Return 1 on world.exists, else 0 and err_line() appropriate error message. */
44 static uint8_t player_commands_allowed();
45
46 /* Parse player commands "tok0" with optional argument "tok1" to player action.
47  * Return 1 on success, 0 on failure.
48  */
49 static uint8_t parse_player_command_0arg(char * tok0);
50 static uint8_t parse_player_command_1arg(char * tok0, char * tok1);
51
52 /* Parse/apply (non-)meta command "tok0" (read further tokens as necessary).
53  * Return 0 on failure, 1 on success, 2 on QUIT meta command.
54  */
55 static uint8_t parse_command_nonmeta(char * tok0);
56 static uint8_t parse_command_meta(char * tok0);
57
58 /* Compare 1st line of server out file to world.server_test, abort if they don't
59  * match, but not before unsetting flags deleting files in the server directory,
60  * for in that case those must be assumed to belong to another server process.
61  */
62 static void server_test();
63
64 /* Return array of IDs of non-owned things in game world, ended by non-ID -1. */
65 static int16_t * build_whitelist();
66
67 /* Return 1 if value of "id" appears in "whitelist", else 0. */
68 static uint8_t thing_in_whitelist(uint8_t id, int16_t * whitelist);
69
70 /* Run the game world and its inhabitants (and their actions) until the player
71  * avatar is free to receive new commands (or is dead). Only actions and
72  * proliferations for non-owned things are performed that exist at the start of
73  * the turn jumped into, or started anew by the cycle.
74  */
75 static void turn_over();
76
77
78
79 static uint8_t set_char_by_string_comparison(char * string, char * comparand,
80                                              char * c_to_set, char value)
81 {
82     if (!strcmp(string, comparand))
83     {
84         * c_to_set = value;
85         return 1;
86     }
87     return 0;
88 }
89
90
91
92 static uint8_t player_commands_allowed()
93 {
94     if (!world.exists)
95     {
96         return !err_line(1, "No world exists in which to run player commands.");
97     }
98     return 1;
99 }
100
101
102
103 static uint8_t parse_player_command_0arg(char * tok0)
104 {
105     struct Thing * player = get_player();
106     if (   !strcmp(tok0, s[S_CMD_WAIT]) || !strcmp(tok0, s[S_CMD_PICKUP])
107         || !strcmp(tok0, s[S_CMD_AI]))
108     {
109         if (player_commands_allowed())
110         {
111             if (!strcmp(tok0, s[S_CMD_AI]))
112             {
113                 ai(player);
114             }
115             else
116             {
117                 player->command = get_thing_action_id_by_name(tok0);
118                 player->arg = 0;
119             }
120             turn_over();
121         }
122         return 1;
123     }
124     return 0;
125 }
126
127
128
129 static uint8_t parse_player_command_1arg(char * tok0, char * tok1)
130 {
131     struct Thing * player = get_player();
132     if (   (   parse_val(tok0, tok1, s[S_CMD_DROP], '8', (char *) &player->arg)
133             || parse_val(tok0, tok1, s[S_CMD_USE], '8', (char *) &player->arg))
134         && player_commands_allowed())
135     {
136         player->command = get_thing_action_id_by_name(tok0);
137         turn_over();
138     }
139     else if (!strcmp(tok0, s[S_CMD_MOVE]) && player_commands_allowed())
140     {
141         char dir = '\0';
142         if (!(   set_char_by_string_comparison(tok1, "east",       &dir, 'd')
143               || set_char_by_string_comparison(tok1, "south-east", &dir, 'c')
144               || set_char_by_string_comparison(tok1, "south-west", &dir, 'x')
145               || set_char_by_string_comparison(tok1, "west",       &dir, 's')
146               || set_char_by_string_comparison(tok1, "north-west", &dir, 'w')
147               || set_char_by_string_comparison(tok1, "north-east", &dir, 'e')))
148         {
149             return 0;
150         }
151         player->arg = dir;
152         player->command = get_thing_action_id_by_name(tok0);
153         turn_over();
154     }
155     else
156     {
157         return 0;
158     }
159     return 1;
160 }
161
162
163
164 static uint8_t parse_command_nonmeta(char * tok0)
165 {
166     if (parse_player_command_0arg(tok0))
167     {
168         return 1;
169     }
170     else
171     {
172         char * tok1 = token_from_line(NULL);
173         if (tok1 && (   parse_player_command_1arg(tok0, tok1)
174                      || parse_god_command_1arg(tok0, tok1)))
175         {
176             return 1;
177         }
178         else
179         {
180             char * tok2 = token_from_line(NULL);
181             if (tok2 && parse_god_command_2arg(tok0, tok1, tok2))
182             {
183                 return 1;
184             }
185             else
186             {
187                 char * tok3 = token_from_line(NULL);
188                 if (tok2 && parse_god_command_3arg(tok0, tok1, tok2, tok3))
189                 {
190                     return 1;
191                 }
192             }
193         }
194     }
195     return 0;
196 }
197
198
199
200 static uint8_t parse_command_meta(char * tok0)
201 {
202     if (!strcmp("QUIT", tok0))
203     {
204         return 2;
205     }
206     if (!strcmp("PING", tok0))
207     {
208         send_to_outfile("PONG\n", 1);
209         return 1;
210     }
211     if (!strcmp("THINGS_HERE", tok0))
212     {
213         char * tok1 = token_from_line(NULL);
214         char * tok2 = token_from_line(NULL);
215         if (tok1&&tok2 && !parsetest_int(tok1, '8')&&!parsetest_int(tok2, '8'))
216         {
217             if (!world.exists)
218             {
219                 err_line(1, "Command only works on existing worlds.");
220                 return 0;
221             }
222             send_to_outfile("THINGS_HERE START\n", 1);
223             struct Thing * player = get_player();
224             if ('v' == player->fov_map[atoi(tok1)*world.map.length+atoi(tok2)])
225             {
226                 struct Thing * t;
227                 for (t = world.things; t; t = t->next)
228                 {
229                     if (t->pos.y == atoi(tok1) && t->pos.x == atoi(tok2))
230                     {
231                         struct ThingType * tt = get_thing_type(t->type);
232                         send_to_outfile(tt->name, 0);
233                         send_to_outfile("\n", 1);
234                     }
235                 }
236             }
237             struct ThingInMemory * t_mem;
238             for (t_mem = player->t_mem; t_mem; t_mem = t_mem->next)
239             {
240                 if (t_mem->pos.y == atoi(tok1) && t_mem->pos.x == atoi(tok2))
241                 {
242                     struct ThingType * tt = get_thing_type(t_mem->type);
243                     send_to_outfile(tt->name, 0);
244                     send_to_outfile("\n", 1);
245                 }
246             }
247             send_to_outfile("THINGS_HERE END\n", 1);
248             return 1;
249         }
250     }
251     return 0;
252 }
253
254
255
256 static void server_test()
257 {
258     char test[10 + 1 + 10 + 1 + 1];
259     FILE * file = try_fopen(s[S_PATH_OUT], "r", __func__);
260     try_fgets(test, 10 + 10 + 1 + 1, file, __func__);
261     try_fclose(file, __func__);
262     if (strcmp(test, world.server_test))
263     {
264         unset_cleanup_flag(CLEANUP_WORLDSTATE);
265         unset_cleanup_flag(CLEANUP_OUT);
266         unset_cleanup_flag(CLEANUP_IN);
267         char * msg = "Server test string in server output file does not match. "
268                      "This indicates that the current server process has been "
269                      "superseded by another one.";
270         exit_err(1, msg);
271     }
272 }
273
274
275
276 static int16_t * build_whitelist()
277 {
278     uint16_t i_things = NULL != world.things;
279     struct Thing * t = world.things;
280     for (; t; t = t->next, i_things++);
281     int16_t * whitelist = try_malloc(i_things * sizeof(int16_t), __func__);
282     for (i_things = 0, t = world.things; t;
283          whitelist[i_things] = t->id, t = t->next, i_things++);
284     whitelist[i_things] = -1;
285     return whitelist;
286 }
287
288
289
290 static uint8_t thing_in_whitelist(uint8_t id, int16_t * whitelist)
291 {
292     uint16_t i;
293     for (i = 0; -1 < whitelist[i]; i++)
294     {
295         if ((int16_t) id == whitelist[i])
296         {
297             return 1;
298         }
299     }
300     return 0;
301 }
302
303
304
305 static void turn_over()
306 {
307     struct Thing * player = get_player();
308     struct Thing * thing = player;
309     int16_t * whitelist = build_whitelist();
310     while (0 < player->lifepoints)
311     {
312         if (!thing)
313         {
314             world.turn++;
315             thing = world.things;
316             free(whitelist);
317             whitelist = build_whitelist();/* The whitelist excludes things    */
318         }                                 /* that appear only during the turn.*/
319         if (thing_in_whitelist(thing->id, whitelist))
320         {
321             if (0 < thing->lifepoints)
322             {
323                 if (0 == thing->command)
324                 {
325                     if (thing == player)
326                     {
327                         break;
328                     }
329                     ai(thing);
330                 }
331                 thing->progress++;
332                 struct ThingAction * ta = get_thing_action(thing->command);
333                 if (thing->progress == ta->effort)
334                 {
335                     ta->func(thing);
336                     thing->command = 0;
337                     thing->progress = 0;
338                 }
339             }
340             try_thing_proliferation(thing);
341         }
342         thing = thing->next;
343     }
344     free(whitelist);
345 }
346
347
348
349 extern void send_to_outfile(char * answer, uint8_t flush)
350 {
351     try_fwrite(answer, strlen(answer), 1, world.file_out, __func__);
352     if (flush)
353     {
354         fflush(world.file_out);
355     }
356 }
357
358
359
360 extern void record(char * msg, uint8_t force)
361 {
362     static FILE * file_tmp = NULL;
363     static time_t save_wait = 0;
364     static char * path_tmp;
365     if (!file_tmp)
366     {
367         path_tmp = build_temp_path(s[S_PATH_RECORD]);
368         file_tmp = try_fopen(path_tmp, "w", __func__);
369         if (!access(s[S_PATH_RECORD], F_OK))
370         {
371             FILE * file_read = try_fopen(s[S_PATH_RECORD], "r", __func__);
372             uint32_t linemax = textfile_width(file_read);
373             char * line = try_malloc(linemax + 1, __func__);
374             while (try_fgets(line, linemax + 1, file_read, __func__))
375             {
376                 try_fwrite(line, strlen(line), 1, file_tmp, __func__);
377             }
378             free(line);
379             try_fclose(file_read, __func__);
380         }
381     }
382     if (msg)
383     {
384         try_fwrite(msg, strlen(msg), 1, file_tmp, __func__);
385         try_fputc('\n', file_tmp, __func__);
386     }
387     if (force || time(NULL) > save_wait + 15)
388     {
389         save_wait = time(NULL);
390         save_world();
391         atomic_write_finish(file_tmp, s[S_PATH_RECORD], path_tmp);
392         file_tmp = NULL;
393     }
394 }
395
396
397
398 extern uint8_t obey_msg(char * msg, uint8_t obey_state)
399 {
400     if (world.is_verbose)
401     {
402         exit_trouble(-1 == printf("Input: %s\n", msg), __func__, "printf");
403     }
404     set_err_line_options("Trouble with message: ", msg, 0);
405     char * msg_copy = strdup(msg);
406     char * tok0 = token_from_line(msg_copy);
407     uint8_t ret = 0;
408     if (tok0)
409     {
410         ret = parse_command_meta(tok0);
411         if (ret || (obey_state < 2 && parse_command_nonmeta(tok0)))
412         {
413             if (!ret)
414             {
415                 if (world.exists)
416                 {
417                     world.do_update = 1;
418                 }
419                 if (1 == obey_state)
420                 {
421                    record(msg, 0);
422                 }
423             }
424             char * tokplus = token_from_line(NULL);
425             err_line(!(!tokplus), "Too many arguments, ignoring overflow.");
426         }
427         else if (world.replay)
428         {
429             ret = 3;
430         }
431         else if (!world.replay)
432         {
433             err_line(1, "Invalid command/argument or bad number of tokens.");
434         }
435     }
436     free(msg_copy);
437     return ret;
438 }
439
440
441
442 extern uint8_t io_loop(uint8_t obey_state)
443 {
444     while (1)
445     {
446         char * msg = io_round();
447         server_test();
448         if (msg)
449         {
450             uint8_t ret = obey_msg(msg, obey_state);
451             free(msg);
452             if (   (!world.replay && 2 == ret)
453                 || ( world.replay && 2 <= ret))
454             {
455                 return ret;
456             }
457         }
458     }
459 }