home · contact · privacy
Server, plugin: Refactor ai (plugin hooks).
[plomrogue] / libplomrogue.c
1 #include <math.h> /* pow() */
2 #include <stddef.h> /* NULL */
3 #include <stdint.h> /* ?(u)int(8|16|32)_t, ?(U)INT8_(MIN|MAX) */
4 #include <stdlib.h> /* free, malloc */
5 #include <string.h> /* memset */
6
7 /* Number of degrees a circle is divided into. The greater it is, the greater
8  * the angle precision. But make it one whole zero larger and bizarre FOV bugs
9  * appear on large maps, probably due to value overflows (TODO: more research!).
10  */
11 #define CIRCLE 3600000
12
13 /* Angle of a shadow. */
14 struct shadow_angle
15 {
16     struct shadow_angle * next;
17     uint32_t left_angle;
18     uint32_t right_angle;
19 };
20
21 /* To be used as temporary storage for world map array. */
22 static char * worldmap = NULL;
23
24 /* Coordinate for maps of max. 256x256 cells. */
25 struct yx_uint8
26 {
27     uint8_t y;
28     uint8_t x;
29 };
30
31 /* Storage for map_length, set by set_maplength(). */
32 static uint16_t maplength = 0;
33 extern void set_maplength(uint16_t maplength_input)
34 {
35     maplength = maplength_input;
36 }
37
38 /* Pseudo-randomness seed for rrand(), set by seed_rrand(). */
39 static uint32_t seed = 0;
40
41 /* Helper to mv_yx_in_dir_legal(). Move "yx" into hex direction "d". */
42 static void mv_yx_in_dir(char d, struct yx_uint8 * yx)
43 {
44     if      (d == 'e')
45     {
46         yx->x = yx->x + (yx->y % 2);
47         yx->y--;
48     }
49     else if (d == 'd')
50     {
51         yx->x++;
52     }
53     else if (d == 'c')
54     {
55         yx->x = yx->x + (yx->y % 2);
56         yx->y++;
57     }
58     else if (d == 'x')
59     {
60         yx->x = yx->x - !(yx->y % 2);
61         yx->y++;
62     }
63     else if (d == 's')
64     {
65         yx->x--;
66     }
67     else if (d == 'w')
68     {
69         yx->x = yx->x - !(yx->y % 2);
70         yx->y--;
71     }
72 }
73
74 /* Move "yx" into hex direction "dir". Available hex directions are: 'e'
75  * (north-east), 'd' (east), 'c' (south-east), 'x' (south-west), 's' (west), 'w'
76  * (north-west). Returns 1 if the move was legal, 0 if not, and -1 when internal
77  * wrapping limits were exceeded.
78  *
79  * A move is legal if "yx" ends up within the the map and the original wrap
80  * space. The latter is left to a neighbor wrap space if "yx" moves beyond the
81  * minimal (0) or maximal (UINT8_MAX) column or row of possible map space – in
82  * which case "yx".y or "yx".x will snap to the respective opposite side. The
83  * current wrapping state is kept between successive calls until a "yx" of NULL
84  * is passed, in which case the function does nothing but zero the wrap state.
85  * Successive wrapping may move "yx" several wrap spaces into either direction,
86  * or return it into the original wrap space.
87  */
88 static int8_t mv_yx_in_dir_legal(char dir, struct yx_uint8 * yx)
89 {
90     static int8_t wrap_west_east   = 0;
91     static int8_t wrap_north_south = 0;
92     if (!yx)
93     {
94         wrap_west_east = wrap_north_south = 0;
95         return 0;
96     }
97     if (   INT8_MIN == wrap_west_east || INT8_MIN == wrap_north_south
98         || INT8_MAX == wrap_west_east || INT8_MAX == wrap_north_south)
99     {
100         return -1;
101     }
102     struct yx_uint8 original = *yx;
103     mv_yx_in_dir(dir, yx);
104     if      (('e' == dir || 'd' == dir || 'c' == dir) && yx->x < original.x)
105     {
106         wrap_west_east++;
107     }
108     else if (('x' == dir || 's' == dir || 'w' == dir) && yx->x > original.x)
109     {
110         wrap_west_east--;
111     }
112     if      (('w' == dir || 'e' == dir)               && yx->y > original.y)
113     {
114         wrap_north_south--;
115     }
116     else if (('x' == dir || 'c' == dir)               && yx->y < original.y)
117     {
118         wrap_north_south++;
119     }
120     if (   !wrap_west_east && !wrap_north_south
121         && yx->x < maplength && yx->y < maplength)
122     {
123         return 1;
124     }
125     return 0;
126 }
127
128 /* Wrapper around mv_yx_in_dir_legal() that stores new coordinate in res_y/x,
129  * (return with result_y/x()), and immediately resets the wrapping.
130  */
131 static uint8_t res_y = 0;
132 static uint8_t res_x = 0;
133 extern uint8_t mv_yx_in_dir_legal_wrap(char dir, uint8_t y, uint8_t x)
134 {
135     struct yx_uint8 yx;
136     yx.y = y;
137     yx.x = x;
138     uint8_t result = mv_yx_in_dir_legal(dir, &yx);
139     mv_yx_in_dir_legal(0, NULL);
140     res_y = yx.y;
141     res_x = yx.x;
142     return result;
143 }
144 extern uint8_t result_y()
145 {
146     return res_y;
147 }
148 extern uint8_t result_x()
149 {
150     return res_x;
151 }
152
153 /* With set_seed set, set seed global to seed_input. In any case, return it. */
154 extern uint32_t seed_rrand(uint8_t set_seed, uint32_t seed_input)
155 {
156     if (set_seed)
157     {
158         seed = seed_input;
159     }
160     return seed;
161 }
162
163 /* Return 16-bit number pseudo-randomly generated via Linear Congruential
164  * Generator algorithm with some proven constants. Use instead of any rand() to
165   * ensure portability of the same pseudo-randomness across systems.
166  */
167 extern uint16_t rrand()
168 {   /* Constants as recommended by POSIX.1-2001 (see man page rand(3)). */
169     seed = ((seed * 1103515245) + 12345) % 4294967296;
170     return (seed >> 16); /* Ignore less random least significant bits. */
171 }
172
173 /* Free shadow angles list "angles". */
174 static void free_angles(struct shadow_angle * angles)
175 {
176     if (angles->next)
177     {
178         free_angles(angles->next);
179     }
180     free(angles);
181 }
182
183 /* Recalculate angle < 0 or > CIRCLE to a value between these two limits. */
184 static uint32_t correct_angle(int32_t angle)
185 {
186     while (angle < 0)
187     {
188         angle = angle + CIRCLE;
189     }
190     while (angle > CIRCLE)
191     {
192         angle = angle - CIRCLE;
193     }
194     return angle;
195 }
196
197 /* Try merging the angle between "left_angle" and "right_angle" to "shadow" if
198  * it meets the shadow from the right or the left. Returns 1 on success, else 0.
199  */
200 static uint8_t try_merge(struct shadow_angle * shadow,
201                          uint32_t left_angle, uint32_t right_angle)
202 {
203     if      (   shadow->right_angle <= left_angle + 1
204              && shadow->right_angle >= right_angle)
205     {
206         shadow->right_angle = right_angle;
207     }
208     else if (   shadow->left_angle + 1 >= right_angle
209              && shadow->left_angle     <= left_angle)
210     {
211         shadow->left_angle = left_angle;
212     }
213     else
214     {
215         return 0;
216     }
217     return 1;
218 }
219
220 /* Try merging the shadow angle between "left_angle" and "right_angle" into an
221  * existing shadow angle in "shadows". On success, see if this leads to any
222  * additional shadow angle overlaps and merge these accordingly. Return 1 on
223  * success, else 0.
224  */
225 static uint8_t try_merging_angles(uint32_t left_angle, uint32_t right_angle,
226                                   struct shadow_angle ** shadows)
227 {
228     uint8_t angle_merge = 0;
229     struct shadow_angle * shadow;
230     for (shadow = *shadows; shadow; shadow = shadow->next)
231     {
232         if (try_merge(shadow, left_angle, right_angle))
233         {
234             angle_merge = 1;
235         }
236     }
237     if (angle_merge)
238     {
239         struct shadow_angle * shadow1;
240         for (shadow1 = *shadows; shadow1; shadow1 = shadow1->next)
241         {
242             struct shadow_angle * last_shadow = NULL;
243             struct shadow_angle * shadow2;
244             for (shadow2 = *shadows; shadow2; shadow2 = shadow2->next)
245             {
246                 if (   shadow1 != shadow2
247                     && try_merge(shadow1, shadow2->left_angle,
248                                           shadow2->right_angle))
249                 {
250                     struct shadow_angle * to_free = shadow2;
251                     if (last_shadow)
252                     {
253                         last_shadow->next = shadow2->next;
254                         shadow2 = last_shadow;
255                     }
256                     else
257                     {
258                         *shadows = shadow2->next;
259                         shadow2 = *shadows;
260                     }
261                     free(to_free);
262                 }
263                 last_shadow = shadow2;
264             }
265         }
266     }
267     return angle_merge;
268 }
269
270 /* To "shadows", add shadow defined by "left_angle" and "right_angle", either as
271  * new entry or as part of an existing shadow (swallowed whole or extending it).
272  * Return 1 on malloc error, else 0.
273  */
274 static uint8_t set_shadow(uint32_t left_angle, uint32_t right_angle,
275                           struct shadow_angle ** shadows)
276 {
277     struct shadow_angle * shadow_i;
278     if (!try_merging_angles(left_angle, right_angle, shadows))
279     {
280         struct shadow_angle * shadow;
281         shadow = malloc(sizeof(struct shadow_angle));
282         if (!shadow)
283         {
284             return 1;
285         }
286         shadow->left_angle  = left_angle;
287         shadow->right_angle = right_angle;
288         shadow->next = NULL;
289         if (*shadows)
290         {
291             for (shadow_i = *shadows; shadow_i; shadow_i = shadow_i->next)
292             {
293                 if (!shadow_i->next)
294                 {
295                     shadow_i->next = shadow;
296                     return 0;
297                 }
298             }
299         }
300         *shadows = shadow;
301     }
302     return 0;
303 }
304
305 /* Test whether angle between "left_angle" and "right_angle", or at least
306  * "middle_angle", is captured inside one of the shadow angles in "shadows". If
307  * so, set hex in "fov_map" indexed by "pos_in_map" to 'H'. If the whole angle
308  * and not just "middle_angle" is captured, return 1. Any other case: 0.
309  */
310 static uint8_t shade_hex(uint32_t left_angle, uint32_t right_angle,
311                          uint32_t middle_angle, struct shadow_angle ** shadows,
312                          uint16_t pos_in_map, char * fov_map)
313 {
314     struct shadow_angle * shadow_i;
315     if (fov_map[pos_in_map] == 'v')
316     {
317         for (shadow_i = *shadows; shadow_i; shadow_i = shadow_i->next)
318         {
319             if (   left_angle <=  shadow_i->left_angle
320                 && right_angle >= shadow_i->right_angle)
321             {
322                 fov_map[pos_in_map] = 'H';
323                 return 1;
324             }
325             if (   middle_angle < shadow_i->left_angle
326                 && middle_angle > shadow_i->right_angle)
327             {
328                 fov_map[pos_in_map] = 'H';
329             }
330         }
331     }
332     return 0;
333 }
334
335 /* Evaluate map position "test_pos" in distance "dist" to the view origin, and
336  * on the circle of that distance to the origin on hex "hex_i" (as counted from
337  * the circle's rightmost point), for setting shaded hexes in "fov_map" and
338  * potentially adding a new shadow to linked shadow angle list "shadows".
339  * Return 1 on malloc error, else 0.
340  */
341 static uint8_t eval_position(uint16_t dist, uint16_t hex_i, char * fov_map,
342                              struct yx_uint8 * test_pos,
343                              struct shadow_angle ** shadows)
344 {
345     int32_t left_angle_uncorrected =   ((CIRCLE / 12) / dist)
346                                      - (hex_i * (CIRCLE / 6) / dist);
347     int32_t right_angle_uncorrected =   left_angle_uncorrected
348                                       - (CIRCLE / (6 * dist));
349     uint32_t left_angle  = correct_angle(left_angle_uncorrected);
350     uint32_t right_angle = correct_angle(right_angle_uncorrected);
351     uint32_t right_angle_1st = right_angle > left_angle ? 0 : right_angle;
352     uint32_t middle_angle = 0;
353     if (right_angle_1st)
354     {
355         middle_angle = right_angle + ((left_angle - right_angle) / 2);
356     }
357     uint16_t pos_in_map = test_pos->y * maplength + test_pos->x;
358     uint8_t all_shaded = shade_hex(left_angle, right_angle_1st, middle_angle,
359                                    shadows, pos_in_map, fov_map);
360     if (!all_shaded && 'X' == worldmap[pos_in_map])
361     {
362         if (set_shadow(left_angle, right_angle_1st, shadows))
363         {
364             return 1;
365         }
366         if (right_angle_1st != right_angle)
367         {
368             left_angle = CIRCLE;
369             if (set_shadow(left_angle, right_angle, shadows))
370             {
371                 return 1;
372             }
373         }
374     }
375     return 0;
376 }
377
378 /* Update field of view in "fovmap" of "worldmap_input" as seen from "y"/"x".
379  * Return 1 on malloc error, else 0.
380  */
381 extern uint8_t build_fov_map(uint8_t y, uint8_t x,
382                              char * fovmap, char * worldmap_input)
383 {
384     worldmap = worldmap_input;
385     struct shadow_angle * shadows = NULL;
386     struct yx_uint8 test_pos;
387     test_pos.y = y;
388     test_pos.x = x;
389     char * circledirs_string = "xswedc";
390     uint16_t circle_i;
391     uint8_t circle_is_on_map;
392     for (circle_i = 1, circle_is_on_map = 1; circle_is_on_map; circle_i++)
393     {
394         circle_is_on_map = 0;
395         if (1 < circle_i)                      /* All circles but the 1st are */
396         {                                      /* moved into starting from a  */
397             mv_yx_in_dir_legal('c', &test_pos);/* previous circle's last hex, */
398         }                                      /* i.e. from the upper left.   */
399         char dir_char = 'd'; /* Circle's 1st hex is entered by rightward move.*/
400         uint8_t dir_char_pos_in_circledirs_string = UINT8_MAX;
401         uint16_t dist_i, hex_i;
402         for (hex_i=0, dist_i=circle_i; hex_i < 6 * circle_i; dist_i++, hex_i++)
403         {
404             if (circle_i < dist_i)
405             {
406                 dist_i = 1;
407                 dir_char=circledirs_string[++dir_char_pos_in_circledirs_string];
408             }
409             if (mv_yx_in_dir_legal(dir_char, &test_pos))
410             {
411                 if (eval_position(circle_i, hex_i, fovmap, &test_pos, &shadows))
412                 {
413                     return 1;
414                 }
415                 circle_is_on_map = 1;
416             }
417         }
418     }
419     mv_yx_in_dir_legal(0, NULL);
420     free_angles(shadows);
421     return 0;
422 }
423
424 static uint16_t * score_map = NULL;
425 static uint16_t neighbor_scores[6];
426
427 /* Init AI score map. Return 1 on failure, else 0. */
428 extern uint8_t init_score_map()
429 {
430     uint32_t map_size = maplength * maplength;
431     score_map = malloc(map_size * sizeof(uint16_t));
432     if (!score_map)
433     {
434         return 1;
435     }
436     uint32_t i = 0;
437     for (; i < map_size; i++)
438     {
439         score_map[i] = UINT16_MAX;
440     }
441     return 0;
442 }
443
444 /* Set score_map[pos] to score. Return 1 on failure, else 0. */
445 extern uint8_t set_map_score(uint16_t pos, uint16_t score)
446 {
447     if (!score_map)
448     {
449         return 1;
450     }
451     score_map[pos] = score;
452     return 0;
453 }
454
455 /* Get score_map[pos]. Return uint16_t value on success, -1 on failure. */
456 extern int32_t get_map_score(uint16_t pos)
457 {
458     if (!score_map)
459     {
460         return -1;
461     }
462     return score_map[pos];
463 }
464
465 /* Free score_map. */
466 extern void free_score_map()
467 {
468     free(score_map);
469     score_map = NULL;
470 }
471
472 /* Write into "neighbors" scores of the immediate neighbors of the score_map
473  * cell at pos_i (array index), as found in the directions north-east, east,
474  * south-east etc. (clockwise order). Use kill_score for illegal neighborhoods
475  * (i.e. if direction would lead beyond the map's border).
476  */
477 static void get_neighbor_scores(uint16_t pos_i, uint16_t kill_score,
478                                 uint16_t * neighbors)
479 {
480     uint32_t map_size = maplength * maplength;
481     uint8_t open_north     = pos_i >= maplength;
482     uint8_t open_east      = pos_i + 1 % maplength;
483     uint8_t open_south     = pos_i + maplength < map_size;
484     uint8_t open_west      = pos_i % maplength;
485     uint8_t is_indented    = (pos_i / maplength) % 2;
486     uint8_t open_diag_west = is_indented || open_west;
487     uint8_t open_diag_east = !is_indented || open_east;
488     neighbors[0] = !(open_north && open_diag_east) ? kill_score :
489                    score_map[pos_i - maplength + is_indented];
490     neighbors[1] = !(open_east) ? kill_score : score_map[pos_i + 1];
491     neighbors[2] = !(open_south && open_diag_east) ? kill_score :
492                    score_map[pos_i + maplength + is_indented];
493     neighbors[3] = !(open_south && open_diag_west) ? kill_score :
494                    score_map[pos_i + maplength - !is_indented];
495     neighbors[4] = !(open_west) ? kill_score : score_map[pos_i - 1];
496     neighbors[5] = !(open_north && open_diag_west) ? kill_score :
497                    score_map[pos_i - maplength - !is_indented];
498 }
499
500 /* Call get_neighbor_scores() on neighbor_scores buffer. Return 1 on error. */
501 extern uint8_t ready_neighbor_scores(uint16_t pos)
502 {
503     if (!score_map)
504     {
505         return 1;
506     }
507     get_neighbor_scores(pos, UINT16_MAX, neighbor_scores);
508     return 0;
509 }
510
511 /* Return i-th position from neighbor_scores buffer.*/
512 extern uint16_t get_neighbor_score(uint8_t i)
513 {
514     return neighbor_scores[i];
515 }
516
517 /* Iterate over scored cells in score_map geometry. Compare each cell's score
518  * against the score of its immediate neighbors in 6 directions. If any
519  * neighbor's score is at least two points lower than the current cell's score,
520  * re-set it to 1 point higher than its lowest-scored neighbor. Repeat this
521  * whole process until all cells have settled on their final score. Ignore cells
522  * whose score is greater than UINT16_MAX - 1 (treat those as unreachable). Also
523  * ignore cells whose score is smaller or equal the number of past iterations.
524  * Return 1 on error, else 0.
525  */
526 extern uint8_t dijkstra_map()
527 {
528     if (!score_map)
529     {
530         return 1;
531     }
532     uint16_t max_score = UINT16_MAX - 1;
533     uint32_t map_size = maplength * maplength;
534     uint32_t pos;
535     uint16_t i_scans, neighbors[6], min_neighbor;
536     uint8_t scores_still_changing = 1;
537     uint8_t i_dirs;
538     for (i_scans = 0; scores_still_changing; i_scans++)
539     {
540         scores_still_changing = 0;
541         for (pos = 0; pos < map_size; pos++)
542         {
543             uint16_t score = score_map[pos];
544             if (score <= max_score && score > i_scans)
545             {
546                 get_neighbor_scores(pos, max_score, neighbors);
547                 min_neighbor = max_score;
548                 for (i_dirs = 0; i_dirs < 6; i_dirs++)
549                 {
550                     if (min_neighbor > neighbors[i_dirs])
551                     {
552                         min_neighbor = neighbors[i_dirs];
553                     }
554                 }
555                 if (score_map[pos] > min_neighbor + 1)
556                 {
557                     score_map[pos] = min_neighbor + 1;
558                     scores_still_changing = 1;
559                 }
560             }
561         }
562     }
563     return 0;
564 }
565
566 extern uint8_t zero_score_map_where_char_on_memdepthmap(char c,
567                                                         char * memdepthmap)
568 {
569     if (!score_map)
570     {
571         return 1;
572     }
573     uint32_t map_size = maplength * maplength;
574     uint16_t pos;
575     for (pos = 0; pos < map_size; pos++)
576     {
577         if (c == memdepthmap[pos])
578         {
579             score_map[pos] = 0;
580         }
581     }
582     return 0;
583 }
584
585 extern void age_some_memdepthmap_on_nonfov_cells(char * memdepthmap,
586                                                  char * fovmap)
587 {
588     uint32_t map_size = maplength * maplength;
589     uint16_t pos;
590     for (pos = 0; pos < map_size; pos++)
591     {
592         if ('v' != fovmap[pos])
593         {
594             char c = memdepthmap[pos];
595             if( '0' <= c && '9' > c && !(rrand() % (uint16_t) pow(2, c - 48)))
596             {
597                 memdepthmap[pos]++;
598             }
599         }
600     }
601 }
602
603 extern uint8_t set_cells_passable_on_memmap_to_65534_on_scoremap(char * mem_map,
604                                                   const char * symbols_passable)
605 {
606     if (!score_map)
607     {
608         return 1;
609     }
610     uint32_t map_size = maplength * maplength;
611     uint16_t pos;
612     for (pos = 0; pos < map_size; pos++)
613     {
614         if (NULL != strchr(symbols_passable, mem_map[pos]))
615         {
616             score_map[pos] = 65534;
617         }
618     }
619     return 0;
620 }
621
622
623 extern void update_mem_and_memdepthmap_via_fovmap(char * map, char * fovmap,
624                                                   char * memdepthmap,
625                                                   char * memmap)
626 {
627     uint32_t map_size = maplength * maplength;
628     uint16_t pos;
629     for (pos = 0; pos < map_size; pos++)
630     {
631         if ('v' == fovmap[pos])
632         {
633             memdepthmap[pos] = '0';
634             memmap[pos] = map[pos];
635         }
636     }
637 }