Crossfire Server, Trunk  R22047
map.c
Go to the documentation of this file.
1 /*
2  * Crossfire -- cooperative multi-player graphical RPG and adventure game
3  *
4  * Copyright (c) 1999-2014 Mark Wedel and the Crossfire Development Team
5  * Copyright (c) 1992 Frank Tore Johansen
6  *
7  * Crossfire is free software and comes with ABSOLUTELY NO WARRANTY. You are
8  * welcome to redistribute it under certain conditions. For details, please
9  * see COPYING and LICENSE.
10  *
11  * The authors can be reached via e-mail at <crossfire@metalforge.org>.
12  */
13 
19 #include "global.h"
20 
21 #include <ctype.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <math.h>
28 
29 #ifndef WIN32 /* ---win32 exclude header */
30 #include <unistd.h>
31 #endif /* win32 */
32 
33 #include "sproto.h"
34 #include "loader.h"
35 #include "output_file.h"
36 #include "path.h"
37 
38 #define PROFILE_BEGIN(expr) { \
39  struct timespec _begin, _end; \
40  clock_gettime(CLOCK_MONOTONIC, &_begin); \
41  expr;
42 
43 #define PROFILE_END(var, expr) \
44  clock_gettime(CLOCK_MONOTONIC, &_end); \
45  long var = timespec_diff(&_end, &_begin); \
46  expr; }
47 
48 static void free_all_objects(mapstruct *m);
49 
55 const char *const map_layer_name[MAP_LAYERS] = {
56  "floor", "no_pick", "no_pick", "item", "item",
57  "item", "living", "living", "fly", "fly"
58 };
59 
61 typedef struct Map_Layer_Info {
65 
73  { MAP_LAYER_FLOOR, 1 },
75  { MAP_LAYER_ITEM3, 1 }, { MAP_LAYER_ITEM3, 1 }, { MAP_LAYER_ITEM3, 1 },
76  { MAP_LAYER_LIVING2, 1 }, { MAP_LAYER_LIVING2, 1 },
77  { MAP_LAYER_FLY2, 1 }, { MAP_LAYER_FLY2, 1 }
78 };
79 
88 mapstruct *has_been_loaded(const char *name) {
89  mapstruct *map;
90 
91  if (!name || !*name)
92  return NULL;
93 
94  for (map = first_map; map; map = map->next)
95  if (!strcmp(name, map->path))
96  break;
97  return (map);
98 }
99 
113 char *create_pathname(const char *name, char *buf, size_t size) {
114  /* Why? having extra / doesn't confuse unix anyplace? Dependancies
115  * someplace else in the code? msw 2-17-97
116  */
117  if (*name == '/')
118  snprintf(buf, size, "%s/%s%s", settings.datadir, settings.mapdir, name);
119  else
120  snprintf(buf, size, "%s/%s/%s", settings.datadir, settings.mapdir, name);
121  return buf;
122 }
123 
134 void create_overlay_pathname(const char *name, char *buf, size_t size) {
135  /* Why? having extra / doesn't confuse unix anyplace? Dependancies
136  * someplace else in the code? msw 2-17-97
137  */
138  if (*name == '/')
139  snprintf(buf, size, "%s/%s%s", settings.localdir, settings.mapdir, name);
140  else
141  snprintf(buf, size, "%s/%s/%s", settings.localdir, settings.mapdir, name);
142 }
143 
154 void create_template_pathname(const char *name, char *buf, size_t size) {
155  /* Why? having extra / doesn't confuse unix anyplace? Dependancies
156  * someplace else in the code? msw 2-17-97
157  */
158  if (*name == '/')
159  snprintf(buf, size, "%s/%s%s", settings.localdir, settings.templatedir, name);
160  else
161  snprintf(buf, size, "%s/%s/%s", settings.localdir, settings.templatedir, name);
162 }
163 
177 static void create_items_path(const char *s, char *buf, size_t size) {
178  char *t;
179 
180  if (*s == '/')
181  s++;
182 
183  snprintf(buf, size, "%s/%s/", settings.localdir, settings.uniquedir);
184  t = buf+strlen(buf);
185  snprintf(t, buf+size-t, "%s", s);
186 
187  while (*t != '\0') {
188  if (*t == '/')
189  *t = '@';
190  t++;
191  }
192 }
193 
212 int check_path(const char *name, int prepend_dir) {
213  char buf[MAX_BUF];
214 #ifndef WIN32
215  struct stat statbuf;
216  int mode = 0;
217 #endif
218 
219  if (prepend_dir)
220  create_pathname(name, buf, MAX_BUF);
221  else
222  strlcpy(buf, name, sizeof(buf));
223 #ifdef WIN32 /* ***win32: check this sucker in windows style. */
224  return(_access(buf, 0));
225 #else
226 
227  if (stat(buf, &statbuf) != 0)
228  return -1;
229 
230  if (!S_ISREG(statbuf.st_mode))
231  return (-1);
232 
233  if (((statbuf.st_mode&S_IRGRP) && getegid() == statbuf.st_gid)
234  || ((statbuf.st_mode&S_IRUSR) && geteuid() == statbuf.st_uid)
235  || (statbuf.st_mode&S_IROTH))
236  mode |= 4;
237 
238  if ((statbuf.st_mode&S_IWGRP && getegid() == statbuf.st_gid)
239  || (statbuf.st_mode&S_IWUSR && geteuid() == statbuf.st_uid)
240  || (statbuf.st_mode&S_IWOTH))
241  mode |= 2;
242 
243  return (mode);
244 #endif
245 }
246 
256 void dump_map(const mapstruct *m) {
257  LOG(llevError, "Map %s status: %d.\n", m->path, m->in_memory);
258  LOG(llevError, "Size: %dx%d Start: %d,%d\n", MAP_WIDTH(m), MAP_HEIGHT(m), MAP_ENTER_X(m), MAP_ENTER_Y(m));
259 
260  if (m->msg != NULL)
261  LOG(llevError, "Message:\n%s", m->msg);
262 
263  if (m->maplore != NULL)
264  LOG(llevError, "Lore:\n%s", m->maplore);
265 
266  if (m->tmpname != NULL)
267  LOG(llevError, "Tmpname: %s\n", m->tmpname);
268 
269  LOG(llevError, "Difficulty: %d\n", m->difficulty);
270  LOG(llevError, "Darkness: %d\n", m->darkness);
271 }
272 
279 void dump_all_maps(void) {
280  mapstruct *m;
281 
282  for (m = first_map; m != NULL; m = m->next) {
283  dump_map(m);
284  }
285 }
286 
311 int get_map_flags(mapstruct *oldmap, mapstruct **newmap, int16_t x, int16_t y, int16_t *nx, int16_t *ny) {
312  int retval = 0;
313  mapstruct *mp;
314 
315  /*
316  * Since x and y are copies of the original values, we can directly
317  * mess with them here.
318  */
319  mp = get_map_from_coord(oldmap, &x, &y);
320  if (!mp)
321  return P_OUT_OF_MAP;
322  if (mp != oldmap)
323  retval |= P_NEW_MAP;
324  if (newmap)
325  *newmap = mp;
326  if (nx)
327  *nx = x;
328  if (ny)
329  *ny = y;
330  retval |= mp->spaces[x+mp->width*y].flags;
331  return retval;
332 }
333 
355 int blocked_link(object *ob, mapstruct *m, int16_t sx, int16_t sy) {
356  object *tmp_head;
357  int mflags, blocked;
358 
359  /* Make sure the coordinates are valid - they should be, as caller should
360  * have already checked this.
361  */
362  if (OUT_OF_REAL_MAP(m, sx, sy)) {
363  LOG(llevError, "blocked_link: Passed map, x, y coordinates outside of map\n");
364  return 1;
365  }
366 
367  /* special hack for transports: if it's a transport with a move_type of 0, it can do on the space anyway */
368  if (ob->type == TRANSPORT && ob->move_type == 0)
369  return 0;
370 
371  /* Save some cycles - instead of calling get_map_flags(), just get the value
372  * directly.
373  */
374  mflags = m->spaces[sx+m->width*sy].flags;
375 
376  blocked = GET_MAP_MOVE_BLOCK(m, sx, sy);
377 
378  /* If space is currently not blocked by anything, no need to
379  * go further. Not true for players - all sorts of special
380  * things we need to do for players.
381  */
382  if (ob->type != PLAYER && !(mflags&P_IS_ALIVE) && (blocked == 0))
383  return 0;
384 
385  /* if there isn't anytyhing alive on this space, and this space isn't
386  * otherwise blocked, we can return now. Only if there is a living
387  * creature do we need to investigate if it is part of this creature
388  * or another. Likewise, only if something is blocking us do we
389  * need to investigate if there is a special circumstance that would
390  * let the player through (inventory checkers for example)
391  */
392  if (!(mflags&P_IS_ALIVE) && !OB_TYPE_MOVE_BLOCK(ob, blocked))
393  return 0;
394 
395  ob = HEAD(ob);
396 
397  /* We basically go through the stack of objects, and if there is
398  * some other object that has NO_PASS or FLAG_ALIVE set, return
399  * true. If we get through the entire stack, that must mean
400  * ob is blocking it, so return 0.
401  */
402  FOR_MAP_PREPARE(m, sx, sy, tmp) {
403  /* Never block part of self. */
404  tmp_head = HEAD(tmp);
405  if (tmp_head == ob)
406  continue;
407  /* This must be before the checks below. Code for inventory checkers. */
408  if (tmp->type == CHECK_INV && OB_MOVE_BLOCK(ob, tmp)) {
409  /* If last_sp is set, the player/monster needs an object,
410  * so we check for it. If they don't have it, they can't
411  * pass through this space.
412  */
413  if (tmp->last_sp) {
414  if (check_inv_recursive(ob, tmp) == NULL) {
415  if (tmp->msg) {
416  /* Optionally display the reason why one cannot move
417  * there. Note: emitting a message from this function
418  * is not very elegant. Ideally, this should be done
419  * somewhere in server/player.c, but this is difficult
420  * for objects of type CHECK_INV that are not alive.
421  */
424  tmp->msg);
425  }
426  return 1;
427  }
428  } else {
429  /* In this case, the player must not have the object -
430  * if they do, they can't pass through.
431  */
432  if (check_inv_recursive(ob, tmp) != NULL) {
433  if (tmp->msg) {
436  tmp->msg);
437  }
438  return 1;
439  }
440  }
441  } /* if check_inv */
442  else {
443  /* Broke apart a big nasty if into several here to make
444  * this more readable. first check - if the space blocks
445  * movement, can't move here.
446  * second - if a monster, can't move there, unless it is a
447  * hidden dm
448  */
449  if (OB_MOVE_BLOCK(ob, tmp))
450  return 1;
451  if (QUERY_FLAG(tmp, FLAG_ALIVE)
452  && tmp->head != ob
453  && tmp != ob
454  && tmp->type != DOOR
455  && !(QUERY_FLAG(tmp, FLAG_WIZ) && tmp->contr->hidden))
456  return 1;
457  }
458  } FOR_MAP_FINISH();
459  return 0;
460 }
461 
498 int ob_blocked(const object *ob, mapstruct *m, int16_t x, int16_t y) {
499  archetype *tmp;
500  int flag;
501  mapstruct *m1;
502  int16_t sx, sy;
503  const object *part;
504 
505  if (ob == NULL) {
506  flag = get_map_flags(m, &m1, x, y, &sx, &sy);
507  if (flag&P_OUT_OF_MAP)
508  return P_OUT_OF_MAP;
509 
510  /* don't have object, so don't know what types would block */
511  return(GET_MAP_MOVE_BLOCK(m1, sx, sy));
512  }
513 
514  for (tmp = ob->arch, part = ob; tmp != NULL; tmp = tmp->more, part = part->more) {
515  flag = get_map_flags(m, &m1, x+tmp->clone.x, y+tmp->clone.y, &sx, &sy);
516 
517  if (flag&P_OUT_OF_MAP)
518  return P_OUT_OF_MAP;
519  if (flag&P_IS_ALIVE)
520  return P_IS_ALIVE;
521 
522  /* object_find_first_free_spot() calls this function. However, often
523  * ob doesn't have any move type (when used to place exits)
524  * so the AND operation in OB_TYPE_MOVE_BLOCK doesn't work.
525  */
526 
527  if (ob->move_type == 0 && GET_MAP_MOVE_BLOCK(m1, sx, sy) != MOVE_ALL)
528  continue;
529 
530  /* A transport without move_type for a part should go through everything for that part. */
531  if (ob->type == TRANSPORT && part->move_type == 0)
532  continue;
533 
534  /* Note it is intentional that we check ob - the movement type of the
535  * head of the object should correspond for the entire object.
536  */
537  if (OB_TYPE_MOVE_BLOCK(ob, GET_MAP_MOVE_BLOCK(m1, sx, sy)))
538  return AB_NO_PASS;
539  }
540  return 0;
541 }
542 
553 static void fix_container_multipart(object *container) {
554  FOR_INV_PREPARE(container, tmp) {
555  archetype *at;
556  object *op, *last;
557 
558  if (tmp->inv)
560  /* already multipart, or non-multipart arch - don't do anything more */
561  for (at = tmp->arch->more, last = tmp; at != NULL; at = at->more, last = op) {
562  /* FIXME: We can't reuse object_fix_multipart() since that only
563  * works for items directly on maps. Maybe factor out common code?
564  */
565  op = arch_to_object(at);
566  op->head = tmp;
567  op->env = tmp->env;
568  last->more = op;
569  if (tmp->name != op->name) {
570  if (op->name)
571  free_string(op->name);
572  op->name = add_string(tmp->name);
573  }
574  if (tmp->title != op->title) {
575  if (op->title)
576  free_string(op->title);
577  op->title = add_string(tmp->title);
578  }
580  }
581  } FOR_INV_FINISH();
582 }
583 
595  int x, y;
596 
597  for (x = 0; x < MAP_WIDTH(m); x++)
598  for (y = 0; y < MAP_HEIGHT(m); y++)
599  FOR_MAP_PREPARE(m, x, y, tmp) {
600  if (tmp->inv)
602 
603  /* already multipart - don't do anything more */
604  if (tmp->head || tmp->more)
605  continue;
606 
608  } FOR_MAP_FINISH(); /* for objects on this space */
609 }
610 
622 static void load_objects(mapstruct *m, FILE *fp, int mapflags) {
623  int i, j, bufstate = LO_NEWFILE;
624  int unique;
625  object *op, *prev = NULL, *last_more = NULL;
626 
627  op = object_new();
628  op->map = m; /* To handle buttons correctly */
629 
630  PROFILE_BEGIN(long cum_body_time = 0;);
631  while ((i = load_object(fp, op, bufstate, mapflags))) {
632  /* Since the loading of the map header does not load an object
633  * anymore, we need to pass LO_NEWFILE for the first object loaded,
634  * and then switch to LO_REPEAT for faster loading.
635  */
636  bufstate = LO_REPEAT;
637 
638  /* if the archetype for the object is null, means that we
639  * got an invalid object. Don't do anything with it - the game
640  * or editor will not be able to do anything with it either.
641  */
642  if (op->arch == NULL) {
643  LOG(llevDebug, "Discarding object without arch: %s\n", op->name ? op->name : "(null)");
644  continue;
645  }
646 
647  /*
648  * You can NOT have players on a map being loaded.
649  * Trying to use such a type leads to crashes everywhere as op->contr is NULL.
650  */
651  if (op->type == PLAYER) {
652  LOG(llevError, "Discarding invalid item with type PLAYER in map %s\n", m->path);
653  continue;
654  }
655 
656  /* don't use out_of_map because we don't want to consider tiling properties, we're loading a single map */
657  if (op->x < 0 || op->y < 0 || op->x >= MAP_WIDTH(m) || op->y >= MAP_HEIGHT(m)) {
658  LOG(llevError, " object %s not on valid map position %s:%d:%d\n", op->name ? op->name : "(null)", m->path, op->x, op->y);
659  if (op->x < 0) {
660  op->x = 0;
661  } else if (op->x >= MAP_WIDTH(m)) {
662  op->x = MAP_WIDTH(m) - 1;
663  }
664  if (op->y < 0) {
665  op->y = 0;
666  } else if (op->y >= MAP_HEIGHT(m)) {
667  op->y = MAP_HEIGHT(m) - 1;
668  }
669  }
670 
671  PROFILE_BEGIN();
672  switch (i) {
673  case LL_NORMAL:
674  /* if we are loading an overlay, put the floors on the bottom */
676  && mapflags&MAP_OVERLAY)
677  object_insert_in_map_at(op, m, op, INS_NO_MERGE|INS_NO_WALK_ON|INS_ABOVE_FLOOR_ONLY|INS_MAP_LOAD, op->x, op->y);
678  else
679  object_insert_in_map_at(op, m, op, INS_NO_MERGE|INS_NO_WALK_ON|INS_ON_TOP|INS_MAP_LOAD, op->x, op->y);
680 
681  if (op->inv)
682  object_sum_weight(op);
683 
684  prev = op,
685  last_more = op;
686  break;
687 
688  case LL_MORE:
689  object_insert_in_map_at(op, m, op, INS_NO_MERGE|INS_NO_WALK_ON|INS_ABOVE_FLOOR_ONLY, op->x, op->y);
690  op->head = prev,
691  last_more->more = op,
692  last_more = op;
693  break;
694  }
695  if (mapflags&MAP_STYLE) {
697  }
698  PROFILE_END(diff, cum_body_time += diff);
699  op = object_new();
700  op->map = m;
701  }
702  PROFILE_END(diff, LOG(llevDebug,
703  "load_objects: while loop took %ld, body took %ld\n",
704  diff, cum_body_time));
705  for (i = 0; i < m->width; i++) {
706  for (j = 0; j < m->height; j++) {
707  unique = 0;
708  /* check for unique items, or unique squares */
709  FOR_MAP_PREPARE(m, i, j, otmp) {
710  if (QUERY_FLAG(otmp, FLAG_UNIQUE))
711  unique = 1;
712  if (!(mapflags&(MAP_OVERLAY|MAP_PLAYER_UNIQUE) || unique))
714  } FOR_MAP_FINISH();
715  }
716  }
719 }
720 
738 static int save_objects(mapstruct *m, FILE *fp, FILE *fp2, int flag) {
739  int i, j = 0, unique = 0, res = 0;
740  unsigned int count = 0;
741 
742  PROFILE_BEGIN();
743  /* first pass - save one-part objects */
744  for (i = 0; i < MAP_WIDTH(m); i++)
745  for (j = 0; j < MAP_HEIGHT(m); j++) {
746  unique = 0;
747  FOR_MAP_PREPARE(m, i, j, op) {
749  unique = 1;
750 
751  if (op->type == PLAYER) {
752  LOG(llevDebug, "Player on map that is being saved\n");
753  continue;
754  }
755 
756  if (op->head || object_get_owner(op) != NULL)
757  continue;
758 
759  if (unique || QUERY_FLAG(op, FLAG_UNIQUE)) {
761  count++ ;
762  } else if (flag == 0
763  || (flag == SAVE_FLAG_NO_REMOVE && (!QUERY_FLAG(op, FLAG_OBJ_ORIGINAL) && !QUERY_FLAG(op, FLAG_UNPAID)))) {
765  count++;
766  }
767 
768  if (res != 0)
769  return res;
770  } FOR_MAP_FINISH(); /* for this space */
771  } /* for this j */
772 
773  PROFILE_END(diff,
774  LOG(llevDebug, "save_objects on %s took %ld us (%u objects = %f us each)\n", m->path, diff, count, (double)diff/count));
775  return 0;
776 }
777 
790  mapstruct *map = (mapstruct *)calloc(1, sizeof(mapstruct));
791  /* mapstruct *mp;*/
792 
793  if (map == NULL)
795  /*
796  * Nothing in the code appears to require we add new maps to the end of the list.
797  * Why not just add them to the front instead? Its faster.
798  *
799  * SilverNexus 2016-05-18
800  *
801  for (mp = first_map; mp != NULL && mp->next != NULL; mp = mp->next)
802  ;
803  if (mp == NULL)
804  first_map = map;
805  else
806  mp->next = map;
807  */
808  map->next = first_map;
809  first_map = map;
810 
811  map->in_memory = MAP_SWAPPED;
812  /* The maps used to pick up default x and y values from the
813  * map archetype. Mimic that behaviour.
814  */
815  MAP_WIDTH(map) = 16;
816  MAP_HEIGHT(map) = 16;
817  MAP_RESET_TIMEOUT(map) = 0;
818  MAP_TIMEOUT(map) = 300;
819  MAP_ENTER_X(map) = 0;
820  MAP_ENTER_Y(map) = 0;
821  map->last_reset_time = 0;
822  return map;
823 }
824 
827  return (uint32_t)m->width * (uint32_t)m->height;
828 }
829 
840 static void allocate_map(mapstruct *m) {
842  /* Log this condition and free the storage. We could I suppose
843  * realloc, but if the caller is presuming the data will be intact,
844  * that is their poor assumption.
845  */
846  if (m->spaces) {
847  LOG(llevError, "allocate_map called with already allocated map (%s)\n", m->path);
848  free(m->spaces);
849  }
850 
851  m->spaces = calloc(map_size(m), sizeof(MapSpace));
852 
853  if (m->spaces == NULL)
855 }
856 
870 mapstruct *get_empty_map(int sizex, int sizey) {
871  mapstruct *m = get_linked_map();
872  m->width = sizex;
873  m->height = sizey;
874  m->in_memory = MAP_SWAPPED;
875  allocate_map(m);
876  return m;
877 }
878 
892 static shopitems *parse_shop_string(const char *input_string, const mapstruct *map) {
893  char *shop_string, *p, *q, *next_semicolon, *next_colon;
894  shopitems *items = NULL;
895  int i = 0, number_of_entries = 0;
896  const typedata *current_type;
897 
898  shop_string = strdup_local(input_string);
899  p = shop_string;
900  LOG(llevDebug, "parsing %s\n", input_string);
901  /* first we'll count the entries, we'll need that for allocating the array shortly */
902  while (p) {
903  p = strchr(p, ';');
904  number_of_entries++;
905  if (p)
906  p++;
907  }
908  p = shop_string;
909  strip_endline(p);
910  items = CALLOC(number_of_entries+1, sizeof(shopitems));
911  /*
912  * The memset would always set at least one byte to zero,
913  * so a failed calloc would have segfaulted the program.
914  * Instead, check for a null and fail more gracefully.
915  */
916  if (!items)
918  /*
919  * calloc() already sets each byte to zero already
920  *
921  memset(items, 0, (sizeof(shopitems)*number_of_entries+1));
922  */
923  for (i = 0; i < number_of_entries; i++) {
924  if (!p) {
925  LOG(llevError, "parse_shop_string: I seem to have run out of string, that shouldn't happen.\n");
926  break;
927  }
928  next_semicolon = strchr(p, ';');
929  next_colon = strchr(p, ':');
930  /* if there is a stregth specified, figure out what it is, we'll need it soon. */
931  if (next_colon && (!next_semicolon || next_colon < next_semicolon))
932  items[i].strength = atoi(strchr(p, ':')+1);
933 
934  if (isdigit(*p) || *p == '*') {
935  items[i].typenum = *p == '*' ? -1 : atoi(p);
936  current_type = get_typedata(items[i].typenum);
937  if (current_type) {
938  items[i].name = current_type->name;
939  items[i].name_pl = current_type->name_pl;
940  }
941  } else { /*we have a named type, let's figure out what it is */
942  q = strpbrk(p, ";:");
943  if (q)
944  *q = '\0';
945 
946  current_type = get_typedata_by_name(p);
947  if (current_type) {
948  items[i].name = current_type->name;
949  items[i].typenum = current_type->number;
950  items[i].name_pl = current_type->name_pl;
951  } else {
952  /* oh uh, something's wrong, let's free up this one, and try
953  * the next entry while we're at it, better print a warning */
954  LOG(llevError, "invalid type %s defined in shopitems for %s in string %s\n", p, map->name, input_string);
955  }
956  }
957  items[i].index = number_of_entries;
958  if (next_semicolon)
959  p = ++next_semicolon;
960  else
961  p = NULL;
962  }
963  free(shop_string);
964  return items;
965 }
966 
978 static void print_shop_string(mapstruct *m, char *output_string, int size) {
979  int i;
980  char tmp[MAX_BUF];
981 
982  output_string[0] = '\0';
983  for (i = 0; i < m->shopitems[0].index; i++) {
984  if (m->shopitems[i].typenum != -1) {
985  if (m->shopitems[i].strength) {
986  snprintf(tmp, sizeof(tmp), "%s:%d;", m->shopitems[i].name, m->shopitems[i].strength);
987  } else
988  snprintf(tmp, sizeof(tmp), "%s;", m->shopitems[i].name);
989  } else {
990  if (m->shopitems[i].strength) {
991  snprintf(tmp, sizeof(tmp), "*:%d;", m->shopitems[i].strength);
992  } else
993  snprintf(tmp, sizeof(tmp), "*;");
994  }
995  snprintf(output_string+strlen(output_string), size-strlen(output_string), "%s", tmp);
996  }
997 
998  /* erase final ; else parsing back will lead to issues */
999  if (strlen(output_string) > 0) {
1000  output_string[strlen(output_string) - 1] = '\0';
1001  }
1002 }
1003 
1023 static int load_map_header(FILE *fp, mapstruct *m) {
1024  char buf[HUGE_BUF], *key = NULL, *value;
1025 
1026  m->width = m->height = 0;
1027  while (fgets(buf, sizeof(buf), fp) != NULL) {
1028  char *p;
1029 
1030  p = strchr(buf, '\n');
1031  if (p == NULL) {
1032  LOG(llevError, "Error loading map header - did not find a newline - perhaps file is truncated? Buf=%s\n", buf);
1033  return 1;
1034  }
1035  *p = '\0';
1036 
1037  key = buf;
1038  while (isspace(*key))
1039  key++;
1040  if (*key == 0)
1041  continue; /* empty line */
1042  value = strchr(key, ' ');
1043  if (value) {
1044  *value = 0;
1045  value++;
1046  while (isspace(*value)) {
1047  value++;
1048  if (*value == '\0') {
1049  /* Nothing but spaces. */
1050  value = NULL;
1051  break;
1052  }
1053  }
1054  }
1055 
1056  /* key is the field name, value is what it should be set
1057  * to. We've already done the work to null terminate key,
1058  * and strip off any leading spaces for both of these.
1059  * We have not touched the newline at the end of the line -
1060  * these are needed for some values. the end pointer
1061  * points to the first of the newlines.
1062  * value could be NULL! It would be easy enough to just point
1063  * this to "" to prevent cores, but that would let more errors slide
1064  * through.
1065  *
1066  * First check for entries that do not use the value parameter, then
1067  * validate that value is given and check for the remaining entries
1068  * that use the parameter.
1069  */
1070 
1071  if (!strcmp(key, "msg")) {
1072  char msgbuf[HUGE_BUF];
1073  int msgpos = 0;
1074 
1075  while (fgets(buf, sizeof(buf), fp) != NULL) {
1076  if (!strcmp(buf, "endmsg\n"))
1077  break;
1078  else {
1079  snprintf(msgbuf+msgpos, sizeof(msgbuf)-msgpos, "%s", buf);
1080  msgpos += strlen(buf);
1081  }
1082  }
1083  /* There are lots of maps that have empty messages (eg, msg/endmsg
1084  * with nothing between). There is no reason in those cases to
1085  * keep the empty message. Also, msgbuf contains garbage data
1086  * when msgpos is zero, so copying it results in crashes
1087  */
1088  if (msgpos != 0) {
1089  /* When loading eg an overlay, message is already set, so free() current one. */
1090  free(m->msg);
1091  m->msg = strdup_local(msgbuf);
1092  }
1093  } else if (!strcmp(key, "maplore")) {
1094  char maplorebuf[HUGE_BUF];
1095  size_t maplorepos = 0;
1096 
1097  while (fgets(buf, HUGE_BUF-1, fp) != NULL) {
1098  if (!strcmp(buf, "endmaplore\n"))
1099  break;
1100  else {
1101  if (maplorepos >= sizeof(maplorebuf)) {
1102  LOG(llevError, "Map lore exceeds buffer length\n");
1103  return 1;
1104  }
1105  snprintf(maplorebuf+maplorepos, sizeof(maplorebuf)-maplorepos, "%s", buf);
1106  maplorepos += strlen(buf);
1107  }
1108  }
1109  if (maplorepos != 0)
1110  m->maplore = strdup_local(maplorebuf);
1111  } else if (!strcmp(key, "end")) {
1112  break;
1113  } else if (value == NULL) {
1114  LOG(llevError, "Got '%s' line without parameter in map header\n", key);
1115  } else if (!strcmp(key, "arch")) {
1116  /* This is an oddity, but not something we care about much. */
1117  if (strcmp(value, "map")) {
1118  LOG(llevError, "load_map_header: expected 'arch map': check line endings?\n");
1119  return 1;
1120  }
1121  } else if (!strcmp(key, "name")) {
1122  /* When loading eg an overlay, the name is already set, so free() current one. */
1123  free(m->name);
1124  m->name = strdup_local(value);
1125  /* first strcmp value on these are old names supported
1126  * for compatibility reasons. The new values (second) are
1127  * what really should be used.
1128  */
1129  } else if (!strcmp(key, "enter_x")) {
1130  m->enter_x = atoi(value);
1131  } else if (!strcmp(key, "enter_y")) {
1132  m->enter_y = atoi(value);
1133  } else if (!strcmp(key, "width")) {
1134  m->width = atoi(value);
1135  } else if (!strcmp(key, "height")) {
1136  m->height = atoi(value);
1137  } else if (!strcmp(key, "reset_timeout")) {
1138  m->reset_timeout = atoi(value);
1139  } else if (!strcmp(key, "swap_time")) {
1140  m->timeout = atoi(value);
1141  } else if (!strcmp(key, "difficulty")) {
1142  m->difficulty = atoi(value);
1143  } else if (!strcmp(key, "darkness")) {
1144  m->darkness = atoi(value);
1145  } else if (!strcmp(key, "fixed_resettime")) {
1146  m->fixed_resettime = atoi(value);
1147  } else if (!strcmp(key, "unique")) {
1148  m->unique = atoi(value);
1149  } else if (!strcmp(key, "template")) {
1150  m->is_template = atoi(value);
1151  } else if (!strcmp(key, "region")) {
1152  m->region = get_region_by_name(value);
1153  } else if (!strcmp(key, "shopitems")) {
1154  m->shopitems = parse_shop_string(value, m);
1155  } else if (!strcmp(key, "shopgreed")) {
1156  m->shopgreed = atof(value);
1157  } else if (!strcmp(key, "shopmin")) {
1158  m->shopmin = atol(value);
1159  } else if (!strcmp(key, "shopmax")) {
1160  m->shopmax = atol(value);
1161  } else if (!strcmp(key, "shoprace")) {
1162  m->shoprace = strdup_local(value);
1163  } else if (!strcmp(key, "outdoor")) {
1164  m->outdoor = atoi(value);
1165  } else if (!strcmp(key, "nosmooth")) {
1166  m->nosmooth = atoi(value);
1167  } else if (!strcmp(key, "first_load")) {
1168  m->last_reset_time = atoi(value);
1169  } else if (!strncmp(key, "tile_path_", 10)) {
1170  int tile = atoi(key+10);
1171 
1172  if (tile < 1 || tile > 4) {
1173  LOG(llevError, "load_map_header: tile location %d out of bounds (%s)\n", tile, m->path);
1174  } else {
1175  if (m->tile_path[tile-1]) {
1176  LOG(llevError, "load_map_header: tile location %d duplicated (%s)\n", tile, m->path);
1177  free(m->tile_path[tile-1]);
1178  }
1179  m->tile_path[tile-1] = strdup_local(value);
1180  } /* end if tile direction (in)valid */
1181  } else if (!strcmp(key, "background_music")) {
1182  m->background_music = strdup_local(value);
1183  } else {
1184  LOG(llevError, "Got unknown value in map header: %s %s\n", key, value);
1185  }
1186  }
1187  if ((m->width == 0) || (m->height == 0)) {
1188  LOG(llevError, "Map width or height not specified\n");
1189  return 1;
1190  }
1191  if (!key || strcmp(key, "end")) {
1192  LOG(llevError, "Got premature eof on map header!\n");
1193  return 1;
1194  }
1195  return 0;
1196 }
1197 
1213 mapstruct *mapfile_load(const char *map, int flags) {
1214  FILE *fp;
1215  mapstruct *m;
1216  char pathname[MAX_BUF];
1217 
1218  PROFILE_BEGIN();
1219 
1220  if (flags&MAP_PLAYER_UNIQUE) {
1221  snprintf(pathname, sizeof(pathname), "%s/%s/%s", settings.localdir, settings.playerdir, map+1);
1222  }
1223  else if (flags&MAP_OVERLAY)
1224  create_overlay_pathname(map, pathname, MAX_BUF);
1225  else
1226  create_pathname(map, pathname, MAX_BUF);
1227 
1228  if ((fp = fopen(pathname, "r")) == NULL) {
1229  LOG((flags&MAP_PLAYER_UNIQUE) ? llevDebug : llevError,
1230  "Can't open %s: %s\n", pathname, strerror(errno));
1231  return (NULL);
1232  }
1233 
1234  m = get_linked_map();
1235 
1236  safe_strncpy(m->path, map, HUGE_BUF);
1237  if (load_map_header(fp, m)) {
1238  LOG(llevError, "Error loading map header for %s, flags=%d\n", map, flags);
1239  delete_map(m);
1240  fclose(fp);
1241  return NULL;
1242  }
1243 
1244  allocate_map(m);
1245 
1246  m->in_memory = MAP_LOADING;
1247  load_objects(m, fp, flags & MAP_STYLE);
1248  fclose(fp);
1249  m->in_memory = MAP_IN_MEMORY;
1250  if (!MAP_DIFFICULTY(m) && (!(flags & MAP_NO_DIFFICULTY)))
1252  set_map_reset_time(m);
1253 
1254  /* In case other objects press some buttons down */
1255  update_buttons(m);
1256 
1258 
1259  if (!(flags & MAP_STYLE))
1260  apply_auto_fix(m); /* Chests which open as default */
1261 
1262  PROFILE_END(diff,
1263  LOG(llevDebug, "mapfile_load on %s" " took %ld us\n", map, diff));
1264 
1265  return (m);
1266 }
1267 
1277  FILE *fp;
1278 
1279  if (!m->tmpname) {
1280  LOG(llevError, "No temporary filename for map %s\n", m->path);
1281  return 1;
1282  }
1283 
1284  if ((fp = fopen(m->tmpname, "r")) == NULL) {
1285  LOG(llevError, "Cannot open %s: %s\n", m->tmpname, strerror(errno));
1286  return 2;
1287  }
1288 
1289  if (load_map_header(fp, m)) {
1290  LOG(llevError, "Error loading map header for %s (%s)\n", m->path, m->tmpname);
1291  fclose(fp);
1292  return 3;
1293  }
1294  allocate_map(m);
1295 
1296  m->in_memory = MAP_LOADING;
1297  load_objects(m, fp, 0);
1298  fclose(fp);
1299  m->in_memory = MAP_IN_MEMORY;
1300  return 0;
1301 }
1302 
1312 static int load_overlay_map(const char *filename, mapstruct *m) {
1313  FILE *fp;
1314  char pathname[MAX_BUF];
1315 
1316  create_overlay_pathname(filename, pathname, MAX_BUF);
1317 
1318  if ((fp = fopen(pathname, "r")) == NULL) {
1319  /* nothing bad to not having an overlay */
1320  return 0;
1321  }
1322 
1323  if (load_map_header(fp, m)) {
1324  LOG(llevError, "Error loading map header for overlay %s (%s)\n", m->path, pathname);
1325  fclose(fp);
1326  return 1;
1327  }
1328  /*allocate_map(m);*/
1329 
1330  m->in_memory = MAP_LOADING;
1331  load_objects(m, fp, MAP_OVERLAY);
1332  fclose(fp);
1333  m->in_memory = MAP_IN_MEMORY;
1334  return 0;
1335 }
1336 
1337 /******************************************************************************
1338  * This is the start of unique map handling code
1339  *****************************************************************************/
1340 
1348  int i, j, unique = 0;
1349 
1350  for (i = 0; i < MAP_WIDTH(m); i++)
1351  for (j = 0; j < MAP_HEIGHT(m); j++) {
1352  unique = 0;
1353  FOR_MAP_PREPARE(m, i, j, op) {
1355  unique = 1;
1356  if (op->head == NULL && (QUERY_FLAG(op, FLAG_UNIQUE) || unique)) {
1357  clean_object(op);
1358  if (QUERY_FLAG(op, FLAG_IS_LINKED))
1359  remove_button_link(op);
1360  object_remove(op);
1362  }
1363  } FOR_MAP_FINISH();
1364  }
1365 }
1366 
1373  FILE *fp;
1374  int count;
1375  char firstname[MAX_BUF], name[MAX_BUF];
1376 
1377  create_items_path(m->path, name, MAX_BUF);
1378  for (count = 0; count < 10; count++) {
1379  snprintf(firstname, sizeof(firstname), "%s.v%02d", name, count);
1380  if (!access(firstname, R_OK))
1381  break;
1382  }
1383  /* If we get here, we did not find any map */
1384  if (count == 10)
1385  return;
1386 
1387  if ((fp = fopen(firstname, "r")) == NULL) {
1388  /* There is no expectation that every map will have unique items, but this
1389  * is debug output, so leave it in.
1390  */
1391  LOG(llevDebug, "Can't open unique items file for %s\n", name);
1392  return;
1393  }
1394 
1395  m->in_memory = MAP_LOADING;
1396  if (m->tmpname == NULL) /* if we have loaded unique items from */
1397  delete_unique_items(m); /* original map before, don't duplicate them */
1398  load_object(fp, NULL, LO_NOREAD, 0);
1399  load_objects(m, fp, 0);
1400  fclose(fp);
1401  m->in_memory = MAP_IN_MEMORY;
1402 }
1403 
1419 int save_map(mapstruct *m, int flag) {
1420 #define TEMP_EXT ".savefile"
1421  FILE *fp, *fp2;
1422  OutputFile of, of2;
1423  char filename[MAX_BUF], buf[MAX_BUF], shop[MAX_BUF], final[MAX_BUF];
1424  int i, res;
1425 
1426  if (flag && !*m->path) {
1427  LOG(llevError, "Tried to save map without path.\n");
1428  return SAVE_ERROR_NO_PATH;
1429  }
1430 
1431  PROFILE_BEGIN();
1432 
1433  if (flag != SAVE_MODE_NORMAL || (m->unique) || (m->is_template)) {
1434  if (!m->unique && !m->is_template) { /* flag is set */
1435  if (flag == SAVE_MODE_OVERLAY)
1436  create_overlay_pathname(m->path, filename, MAX_BUF);
1437  else
1438  create_pathname(m->path, filename, MAX_BUF);
1439  } else {
1440  if (m->path[0] != '~') {
1441  LOG(llevError,
1442  "Cannot save unique map '%s' outside of LOCALDIR. Check "
1443  "that all exits to '%s' have FLAG_UNIQUE set correctly.\n",
1444  m->path, m->path);
1445  return SAVE_ERROR_UCREATION;
1446  }
1447  snprintf(filename, sizeof(filename), "%s/%s/%s", settings.localdir, settings.playerdir, m->path+1);
1448  }
1449 
1450  make_path_to_file(filename);
1451  } else {
1452  if (!m->tmpname)
1453  m->tmpname = tempnam(settings.tmpdir, NULL);
1454  strlcpy(filename, m->tmpname, sizeof(filename));
1455  }
1456  m->in_memory = MAP_SAVING;
1457 
1458  strlcpy(final, filename, sizeof(final));
1459  snprintf(filename, sizeof(filename), "%s%s", final, TEMP_EXT);
1460  fp = of_open(&of, filename);
1461  if (fp == NULL)
1462  return SAVE_ERROR_RCREATION;
1463 
1464  /* legacy */
1465  fprintf(fp, "arch map\n");
1466  if (m->name)
1467  fprintf(fp, "name %s\n", m->name);
1468  if (!flag)
1469  fprintf(fp, "swap_time %d\n", m->swap_time);
1470  if (m->reset_timeout)
1471  fprintf(fp, "reset_timeout %u\n", m->reset_timeout);
1472  if (m->fixed_resettime)
1473  fprintf(fp, "fixed_resettime %d\n", m->fixed_resettime);
1474  /* we unfortunately have no idea if this is a value the creator set
1475  * or a difficulty value we generated when the map was first loaded
1476  */
1477  if (m->difficulty)
1478  fprintf(fp, "difficulty %d\n", m->difficulty);
1479  if (m->region)
1480  fprintf(fp, "region %s\n", m->region->name);
1481  if (m->shopitems) {
1482  print_shop_string(m, shop, sizeof(shop));
1483  fprintf(fp, "shopitems %s\n", shop);
1484  }
1485  if (m->shopgreed)
1486  fprintf(fp, "shopgreed %f\n", m->shopgreed);
1487  if (m->shopmin)
1488  fprintf(fp, "shopmin %"FMT64U"\n", m->shopmin);
1489  if (m->shopmax)
1490  fprintf(fp, "shopmax %"FMT64U"\n", m->shopmax);
1491  if (m->shoprace)
1492  fprintf(fp, "shoprace %s\n", m->shoprace);
1493  if (m->darkness)
1494  fprintf(fp, "darkness %d\n", m->darkness);
1495  if (m->width)
1496  fprintf(fp, "width %d\n", m->width);
1497  if (m->height)
1498  fprintf(fp, "height %d\n", m->height);
1499  if (m->enter_x)
1500  fprintf(fp, "enter_x %d\n", m->enter_x);
1501  if (m->enter_y)
1502  fprintf(fp, "enter_y %d\n", m->enter_y);
1503  if (m->msg)
1504  fprintf(fp, "msg\n%sendmsg\n", m->msg);
1505  if (m->maplore)
1506  fprintf(fp, "maplore\n%sendmaplore\n", m->maplore);
1507  if (m->unique)
1508  fprintf(fp, "unique %d\n", m->unique);
1509  if (m->is_template)
1510  fprintf(fp, "template %d\n", m->is_template);
1511  if (m->outdoor)
1512  fprintf(fp, "outdoor %d\n", m->outdoor);
1513  if (m->nosmooth)
1514  fprintf(fp, "nosmooth %d\n", m->nosmooth);
1515  if (m->last_reset_time)
1516  fprintf(fp, "first_load %ld\n", m->last_reset_time);
1517  if (m->background_music)
1518  fprintf(fp, "background_music %s\n", m->background_music);
1519 
1520  /* Save any tiling information, except on overlays */
1521  if (flag != SAVE_MODE_OVERLAY)
1522  for (i = 0; i < 4; i++)
1523  if (m->tile_path[i])
1524  fprintf(fp, "tile_path_%d %s\n", i+1, m->tile_path[i]);
1525 
1526  fprintf(fp, "end\n");
1527 
1528  /* In the game save unique items in the different file, but
1529  * in the editor save them to the normal map file.
1530  * If unique map, save files in the proper destination (set by
1531  * player)
1532  */
1533  if ((flag == SAVE_MODE_NORMAL || flag == SAVE_MODE_OVERLAY) && !m->unique && !m->is_template) {
1534  char name[MAX_BUF], final_unique[MAX_BUF];
1535 
1536  create_items_path(m->path, name, MAX_BUF);
1537  snprintf(final_unique, sizeof(final_unique), "%s.v00", name);
1538  snprintf(buf, sizeof(buf), "%s%s", final_unique, TEMP_EXT);
1539  fp2 = of_open(&of2, buf);
1540  if (fp2 == NULL) {
1541  of_cancel(&of);
1542  return SAVE_ERROR_UCREATION;
1543  }
1544  if (flag == SAVE_MODE_OVERLAY) {
1545  /* SO_FLAG_NO_REMOVE is non destructive save, so map is still valid. */
1546  res = save_objects(m, fp, fp2, SAVE_FLAG_NO_REMOVE);
1547  if (res < 0) {
1548  LOG(llevError, "Save error during object save: %d\n", res);
1549  of_cancel(&of);
1550  of_cancel(&of2);
1551  return res;
1552  }
1553  m->in_memory = MAP_IN_MEMORY;
1554  } else {
1555  res = save_objects(m, fp, fp2, 0);
1556  if (res < 0) {
1557  LOG(llevError, "Save error during object save: %d\n", res);
1558  of_cancel(&of);
1559  of_cancel(&of2);
1560  return res;
1561  }
1562  free_all_objects(m);
1563  }
1564  if (ftell(fp2) == 0) {
1565  of_cancel(&of2);
1566  unlink(buf);
1567  /* If there are no unique items left on the map, we need to
1568  * unlink the original unique map so that the unique
1569  * items don't show up again.
1570  */
1571  unlink(final_unique);
1572  } else {
1573  if (!of_close(&of2)) {
1574  of_cancel(&of);
1575  return SAVE_ERROR_WRITE;
1576  }
1577  unlink(final_unique); /* failure isn't too bad, maybe the file doesn't exist. */
1578  if (rename(buf, final_unique) == -1) {
1579  LOG(llevError, "Couldn't rename unique file %s to %s\n", buf, final_unique);
1580  of_cancel(&of);
1581  return SAVE_ERROR_URENAME;
1582  }
1583 
1584  if (chmod(final_unique, SAVE_MODE) != 0) {
1585  LOG(llevError, "Could not set permissions on '%s'\n",
1586  final_unique);
1587  }
1588  }
1589  } else { /* save same file when not playing, like in editor */
1590  res = save_objects(m, fp, fp, 0);
1591  if (res < 0) {
1592  LOG(llevError, "Save error during object save: %d\n", res);
1593  of_cancel(&of);
1594  return res;
1595  }
1596  free_all_objects(m);
1597  }
1598 
1599  if (!of_close(&of))
1600  return SAVE_ERROR_CLOSE;
1601  unlink(final); /* failure isn't too bad, maybe the file doesn't exist. */
1602  if (rename(filename, final) == -1) {
1603  LOG(llevError, "Couldn't rename regular file %s to %s\n", filename, final);
1604  return SAVE_ERROR_RRENAME;
1605  }
1606 
1607  if (chmod(final, SAVE_MODE) != 0) {
1608  LOG(llevError, "Could not set permissions on '%s'\n", final);
1609  }
1610 
1611  PROFILE_END(diff,
1612  LOG(llevDebug, "save_map on %s" " took %ld us\n", m->path, diff));
1613 
1614  return SAVE_ERROR_OK;
1615 }
1616 
1626 void clean_object(object *op) {
1627  FOR_INV_PREPARE(op, tmp) {
1628  clean_object(tmp);
1629  if (QUERY_FLAG(tmp, FLAG_IS_LINKED))
1630  remove_button_link(tmp);
1631  object_remove(tmp);
1633  } FOR_INV_FINISH();
1634 }
1635 
1642 static void free_all_objects(mapstruct *m) {
1643  int i, j;
1644  object *op;
1645 
1646  for (i = 0; i < MAP_WIDTH(m); i++)
1647  for (j = 0; j < MAP_HEIGHT(m); j++) {
1648  object *previous_obj = NULL;
1649 
1650  while ((op = GET_MAP_OB(m, i, j)) != NULL) {
1651  if (op == previous_obj) {
1652  LOG(llevDebug, "free_all_objects: Link error, bailing out.\n");
1653  break;
1654  }
1655  previous_obj = op;
1656  op = HEAD(op);
1657 
1658  /* If the map isn't in memory, object_free_drop_inventory() will remove and
1659  * free objects in op's inventory. So let it do the job.
1660  */
1661  if (m->in_memory == MAP_IN_MEMORY)
1662  clean_object(op);
1663  object_remove(op);
1665  }
1666  }
1667 #ifdef MANY_CORES
1668  /* I see periodic cores on metalforge where a map has been swapped out, but apparantly
1669  * an item on that map was not saved - look for that condition and die as appropriate -
1670  * this leaves more of the map data intact for better debugging.
1671  */
1672  for (op = objects; op != NULL; op = op->next) {
1673  if (!QUERY_FLAG(op, FLAG_REMOVED) && op->map == m) {
1674  LOG(llevError, "free_all_objects: object %s still on map after it should have been freed\n", op->name);
1675  abort();
1676  }
1677  }
1678 #endif
1679 }
1680 
1690  int i;
1691 
1692  if (!m->in_memory) {
1693  LOG(llevError, "Trying to free freed map.\n");
1694  return;
1695  }
1696 
1698 
1699  if (m->spaces)
1700  free_all_objects(m);
1701  if (m->name)
1702  FREE_AND_CLEAR(m->name);
1703  if (m->spaces)
1704  FREE_AND_CLEAR(m->spaces);
1705  if (m->msg)
1706  FREE_AND_CLEAR(m->msg);
1707  if (m->maplore)
1708  FREE_AND_CLEAR(m->maplore);
1709  if (m->shopitems)
1711  if (m->shoprace)
1713  if (m->background_music)
1715  if (m->buttons)
1717  m->buttons = NULL;
1718  for (i = 0; i < 4; i++) {
1719  if (m->tile_path[i])
1720  FREE_AND_CLEAR(m->tile_path[i]);
1721  m->tile_map[i] = NULL;
1722  }
1723  m->in_memory = MAP_SWAPPED;
1724 }
1725 
1736  mapstruct *tmp, *last;
1737  int i;
1738 
1739  if (!m)
1740  return;
1741  if (m->in_memory == MAP_IN_MEMORY) {
1742  /* change to MAP_SAVING, even though we are not,
1743  * so that object_remove() doesn't do as much work.
1744  */
1745  m->in_memory = MAP_SAVING;
1746  free_map(m);
1747  }
1748  /* move this out of free_map, since tmpname can still be needed if
1749  * the map is swapped out.
1750  */
1751  free(m->tmpname);
1752  m->tmpname = NULL;
1753  last = NULL;
1754  /* We need to look through all the maps and see if any maps
1755  * are pointing at this one for tiling information. Since
1756  * tiling can be assymetric, we just can not look to see which
1757  * maps this map tiles with and clears those.
1758  */
1759  for (tmp = first_map; tmp != NULL; tmp = tmp->next) {
1760  if (tmp->next == m)
1761  last = tmp;
1762 
1763  /* This should hopefully get unrolled on a decent compiler */
1764  for (i = 0; i < 4; i++)
1765  if (tmp->tile_map[i] == m)
1766  tmp->tile_map[i] = NULL;
1767  }
1768 
1769  /* If last is null, then this should be the first map in the list */
1770  if (!last) {
1771  if (m == first_map)
1772  first_map = m->next;
1773  else
1774  /* m->path is a static char, so should hopefully still have
1775  * some useful data in it.
1776  */
1777  LOG(llevError, "delete_map: Unable to find map %s in list\n", m->path);
1778  } else
1779  last->next = m->next;
1780 
1781  free(m);
1782 }
1783 
1797 mapstruct *ready_map_name(const char *name, int flags) {
1798  mapstruct *m;
1799 
1800  if (!name)
1801  return (NULL);
1802 
1803  /* Have we been at this level before? */
1804  m = has_been_loaded(name);
1805 
1806  /* Map is good to go, so just return it */
1807  if (m && (m->in_memory == MAP_LOADING || m->in_memory == MAP_IN_MEMORY)) {
1808  return m;
1809  }
1810 
1811  /* Rewrite old paths starting with LOCALDIR/PLAYERDIR to new '~' paths. */
1812  char buf[MAX_BUF], buf2[MAX_BUF];
1813  snprintf(buf, sizeof(buf), "%s/%s", settings.localdir, settings.playerdir);
1814  if (strncmp(name, buf, strlen(buf)) == 0) {
1815  snprintf(buf2, sizeof(buf2), "~%s", name+strlen(buf)+1);
1816  name = buf2;
1817  }
1818 
1819  /* Paths starting with '~' are unique. */
1820  if (name[0] == '~') {
1821  flags |= MAP_PLAYER_UNIQUE;
1822  }
1823 
1824  /* unique maps always get loaded from their original location, and never
1825  * a temp location. Likewise, if map_flush is set, or we have never loaded
1826  * this map, load it now. I removed the reset checking from here -
1827  * it seems the probability of a player trying to enter a map that should
1828  * reset but hasn't yet is quite low, and removing that makes this function
1829  * a bit cleaner (and players probably shouldn't rely on exact timing for
1830  * resets in any case - if they really care, they should use the 'maps command.
1831  */
1832  if ((flags&(MAP_FLUSH|MAP_PLAYER_UNIQUE)) || !m) {
1833  /* first visit or time to reset */
1834  if (m) {
1835  clean_tmp_map(m); /* Doesn't make much difference */
1836  delete_map(m);
1837  }
1838 
1839  m = mapfile_load(name, (flags&MAP_PLAYER_UNIQUE));
1840  if (m == NULL) return NULL;
1841 
1842  /* If a player unique map, no extra unique object file to load.
1843  * if from the editor, likewise.
1844  */
1845  if (!(flags&(MAP_FLUSH|MAP_PLAYER_UNIQUE)))
1847 
1848  if (!(flags&(MAP_FLUSH|MAP_PLAYER_UNIQUE|MAP_OVERLAY))) {
1849  if (load_overlay_map(name, m) != 0) {
1850  delete_map(m);
1851  m = mapfile_load(name, 0);
1852  if (m == NULL) {
1853  /* Really, this map is bad :( */
1854  return NULL;
1855  }
1856  }
1857  }
1858  } else {
1859  /* If in this loop, we found a temporary map, so load it up. */
1860 
1861  if (load_temporary_map(m) != 0) {
1862  /*
1863  * There was a failure loading the temporary map, fall back to original one.
1864  * load_temporary_map() already logged the error.
1865  */
1866  delete_map(m);
1867  m = mapfile_load(name, 0);
1868  if (m == NULL) {
1869  /* Really, this map is bad :( */
1870  return NULL;
1871  }
1872  }
1874 
1875  clean_tmp_map(m);
1876  m->in_memory = MAP_IN_MEMORY;
1877  /* tempnam() on sun systems (probably others) uses malloc
1878  * to allocated space for the string. Free it here.
1879  * In some cases, load_temporary_map above won't find the
1880  * temporary map, and so has reloaded a new map. If that
1881  * is the case, tmpname is now null
1882  */
1883  free(m->tmpname);
1884  m->tmpname = NULL;
1885  /* It's going to be saved anew anyway */
1886  }
1887 
1888  /* Below here is stuff common to both first time loaded maps and
1889  * temp maps.
1890  */
1891 
1892  decay_objects(m); /* start the decay */
1893 
1894  if (m->outdoor)
1895  set_darkness_map(m);
1896 
1897  if (!(flags&(MAP_FLUSH))) {
1898  if (m->last_reset_time == 0) {
1899  m->last_reset_time = seconds();
1900  }
1901  }
1902  return m;
1903 }
1904 
1921  archetype *at;
1922  int x, y;
1923  int diff = 0;
1924  int i;
1925  int64_t exp_pr_sq, total_exp = 0;
1926 
1927  if (MAP_DIFFICULTY(m)) {
1928  return MAP_DIFFICULTY(m);
1929  }
1930 
1931  for (x = 0; x < MAP_WIDTH(m); x++)
1932  for (y = 0; y < MAP_HEIGHT(m); y++)
1933  FOR_MAP_PREPARE(m, x, y, op) {
1934  if (QUERY_FLAG(op, FLAG_MONSTER))
1935  total_exp += op->stats.exp;
1936  if (QUERY_FLAG(op, FLAG_GENERATOR)) {
1937  total_exp += op->stats.exp;
1938  // If we have an other_arch on our generator, just use that.
1939  // FIXME: Figure out what to do if we are doing template generation from inventory.
1940  at = op->other_arch ? op->other_arch : NULL;
1941  if (at != NULL) {
1942  // Make sure we can't set off a null pointer dereference in atoi().
1943  const char *val = object_get_value(op, "generator_limit");
1944  int lim = atoi(val ? val : "0");
1945  // We assume, on average, the generator will generate half its contents.
1946  if (!lim || lim >= 16)
1947  total_exp += at->clone.stats.exp*8;
1948  else
1949  total_exp += at->clone.stats.exp*(lim/2);
1950  }
1951  }
1952  } FOR_MAP_FINISH();
1953  // Used to be multiplied by 1000, but this undershot horribly
1954  // once I fixed the calculation for generators.
1955  // I'm trying out some exponentiation, since linear scaling
1956  // seems to overshoot low-level maps and undershoot high-level maps.
1957  // I also feel comfortable, knowing that generators return
1958  // sensible values, to up the max diff this calculates from 20 to 25.
1959  // - Daniel Hawkins 2021-03-04
1960  exp_pr_sq = (pow(total_exp, 1.75))/(MAP_WIDTH(m)*MAP_HEIGHT(m)+1);
1961  diff = 25;
1962  for (i = 1; i < 25; i++)
1963  if (exp_pr_sq <= level_exp(i, 1.0)) {
1964  diff = i;
1965  break;
1966  }
1967 
1968  return diff;
1969 }
1970 
1978  if (m->tmpname == NULL)
1979  return;
1980  (void)unlink(m->tmpname);
1981 }
1982 
1986 void free_all_maps(void) {
1987  int real_maps = 0;
1988 
1989  while (first_map) {
1990  /* I think some of the callers above before it gets here set this to be
1991  * saving, but we still want to free this data
1992  */
1993  if (first_map->in_memory == MAP_SAVING)
1996  real_maps++;
1997  }
1998  LOG(llevDebug, "free_all_maps: Freed %d maps\n", real_maps);
1999 }
2000 
2018 int change_map_light(mapstruct *m, int change) {
2019  int new_level = m->darkness+change;
2020 
2021  /* Nothing to do */
2022  if (!change
2023  || (new_level <= 0 && m->darkness == 0)
2024  || (new_level >= MAX_DARKNESS && m->darkness >= MAX_DARKNESS)) {
2025  return 0;
2026  }
2027 
2028  /* inform all players on the map */
2029  if (change > 0)
2030  ext_info_map(NDI_BLACK, m, MSG_TYPE_MISC, MSG_SUBTYPE_NONE, "It becomes darker.");
2031  else
2032  ext_info_map(NDI_BLACK, m, MSG_TYPE_MISC, MSG_SUBTYPE_NONE, "It becomes brighter.");
2033 
2034  /* Do extra checking. since m->darkness is a unsigned value,
2035  * we need to be extra careful about negative values.
2036  * In general, the checks below are only needed if change
2037  * is not +/-1
2038  */
2039  if (new_level < 0)
2040  m->darkness = 0;
2041  else if (new_level >= MAX_DARKNESS)
2042  m->darkness = MAX_DARKNESS;
2043  else
2044  m->darkness = new_level;
2045 
2046  /* All clients need to get re-updated for the change */
2047  update_all_map_los(m);
2048  return 1;
2049 }
2050 
2073 static inline void add_face_layer(int low_layer, int high_layer, object *ob, object *layers[], int honor_visibility) {
2074  int l, l1;
2075  object *tmp;
2076 
2077  for (l = low_layer; l <= high_layer; l++) {
2078  if (!layers[l]) {
2079  /* found an empty spot. now, we want to make sure
2080  * highest visibility at top, etc.
2081  */
2082  layers[l] = ob;
2083  if (!honor_visibility)
2084  return;
2085 
2086  /* This is basically a mini bubble sort. Only swap
2087  * position if the lower face has greater (not equal)
2088  * visibility - map stacking is secondary consideration here.
2089  */
2090  for (l1 = (l-1); l1 >= low_layer; l1--) {
2091  if (layers[l1]->face->visibility > layers[l1+1]->face->visibility) {
2092  tmp = layers[l1+1];
2093  layers[l1+1] = layers[l1];
2094  layers[l1] = tmp;
2095  }
2096  }
2097  /* Nothing more to do - face inserted */
2098  return;
2099  }
2100  }
2101  /* If we get here, all the layers have an object..
2102  */
2103  if (!honor_visibility) {
2104  /* Basically, in this case, it is pure stacking logic, so
2105  * new object goes on the top.
2106  */
2107  for (l = low_layer; l < high_layer; l++)
2108  layers[l] = layers[l+1];
2109  layers[high_layer] = ob;
2110  /* If this object doesn't have higher visibility than
2111  * the lowest object, no reason to go further.
2112  */
2113  } else if (ob->face->visibility >= layers[low_layer]->face->visibility) {
2114  /*
2115  * Start at the top (highest visibility) layer and work down.
2116  * once this face exceed that of the layer, push down those
2117  * other layers, and then replace the layer with our object.
2118  */
2119  for (l = high_layer; l >= low_layer; l--) {
2120  if (ob->face->visibility >= layers[l]->face->visibility) {
2121  for (l1 = low_layer; l1 < l; l1++)
2122  layers[l1] = layers[l1+1];
2123  layers[l] = ob;
2124  break;
2125  }
2126  }
2127  }
2128 }
2129 
2142 void update_position(mapstruct *m, int x, int y) {
2143  object *player = NULL;
2144  uint8_t flags = 0, oldflags, light = 0;
2145  object *layers[MAP_LAYERS];
2146 
2147  MoveType move_block = 0, move_slow = 0, move_on = 0, move_off = 0, move_allow = 0;
2148 
2149  oldflags = GET_MAP_FLAGS(m, x, y);
2150  if (!(oldflags&P_NEED_UPDATE)) {
2151  LOG(llevDebug, "update_position called with P_NEED_UPDATE not set: %s (%d, %d)\n", m->path, x, y);
2152  return;
2153  }
2154 
2155  memset(layers, 0, MAP_LAYERS*sizeof(object *));
2156 
2157  FOR_MAP_PREPARE(m, x, y, tmp) {
2158  /* DMs just don't do anything when hidden, including no light. */
2159  if (QUERY_FLAG(tmp, FLAG_WIZ) && tmp->contr->hidden)
2160  continue;
2161 
2162  if (tmp->type == PLAYER)
2163  player = tmp;
2164 
2165  /* This could be made additive I guess (two lights better than
2166  * one). But if so, it shouldn't be a simple additive - 2
2167  * light bulbs do not illuminate twice as far as once since
2168  * it is a dissipation factor that is squared (or is it cubed?)
2169  */
2170  if (tmp->glow_radius > light)
2171  light = tmp->glow_radius;
2172 
2173  /* if this object is visible and not a blank face,
2174  * update the objects that show how this space
2175  * looks.
2176  */
2177  if (!tmp->invisible && tmp->face != blank_face) {
2178  if (tmp->map_layer) {
2179  add_face_layer(tmp->map_layer, map_layer_info[tmp->map_layer].high_layer,
2180  tmp, layers, map_layer_info[tmp->map_layer].honor_visibility);
2181  } else if (tmp->move_type&MOVE_FLYING) {
2182  add_face_layer(MAP_LAYER_FLY1, MAP_LAYER_FLY2, tmp, layers, 1);
2183  } else if ((tmp->type == PLAYER || QUERY_FLAG(tmp, FLAG_MONSTER))) {
2185  } else if (QUERY_FLAG(tmp, FLAG_IS_FLOOR)) {
2186  layers[MAP_LAYER_FLOOR] = tmp;
2187  /* floors hide everything else */
2188  memset(layers+1, 0, (MAP_LAYERS-1)*sizeof(object *));
2189  /* Check for FLAG_SEE_ANYWHERE is removed - objects
2190  * with that flag should just have a high visibility
2191  * set - we shouldn't need special code here.
2192  */
2193  } else if (QUERY_FLAG(tmp, FLAG_NO_PICK)) {
2195  } else {
2197  }
2198  }
2199  if (tmp == tmp->above) {
2200  LOG(llevError, "Error in structure of map\n");
2201  exit(-1);
2202  }
2203 
2204  move_slow |= tmp->move_slow;
2205  move_block |= tmp->move_block;
2206  move_on |= tmp->move_on;
2207  move_off |= tmp->move_off;
2208  move_allow |= tmp->move_allow;
2209 
2210  if (QUERY_FLAG(tmp, FLAG_ALIVE))
2211  flags |= P_IS_ALIVE;
2212  if (QUERY_FLAG(tmp, FLAG_NO_MAGIC))
2213  flags |= P_NO_MAGIC;
2214  if (QUERY_FLAG(tmp, FLAG_DAMNED))
2215  flags |= P_NO_CLERIC;
2216 
2217  if (QUERY_FLAG(tmp, FLAG_BLOCKSVIEW))
2218  flags |= P_BLOCKSVIEW;
2219  } FOR_MAP_FINISH(); /* for stack of objects */
2220 
2221  if (player)
2222  flags |= P_PLAYER;
2223 
2224  /* we don't want to rely on this function to have accurate flags, but
2225  * since we're already doing the work, we calculate them here.
2226  * if they don't match, logic is broken someplace.
2227  */
2228  if (((oldflags&~(P_NEED_UPDATE|P_NO_ERROR)) != flags)
2229  && (!(oldflags&P_NO_ERROR))) {
2230  LOG(llevDebug, "update_position: updated flags do not match old flags: %s (x=%d,y=%d) %x != %x\n",
2231  m->path, x, y, (oldflags&~P_NEED_UPDATE), flags);
2232  }
2233 
2234  SET_MAP_FLAGS(m, x, y, flags);
2235  SET_MAP_MOVE_BLOCK(m, x, y, move_block&~move_allow);
2236  SET_MAP_MOVE_ON(m, x, y, move_on);
2237  SET_MAP_MOVE_OFF(m, x, y, move_off);
2238  SET_MAP_MOVE_SLOW(m, x, y, move_slow);
2239  SET_MAP_LIGHT(m, x, y, light);
2240 
2241  /* Note that player may be NULL here, which is fine - if no player, need
2242  * to clear any value that may be set.
2243  */
2244  SET_MAP_PLAYER(m, x, y, player);
2245 
2246  /* Note it is intentional we copy everything, including NULL values. */
2247  memcpy(GET_MAP_FACE_OBJS(m, x, y), layers, sizeof(object *)*MAP_LAYERS);
2248 }
2249 
2257  int timeout;
2258 
2259  timeout = MAP_RESET_TIMEOUT(map);
2260  if (timeout <= 0)
2261  timeout = MAP_DEFAULTRESET;
2262  if (timeout >= MAP_MAXRESET)
2263  timeout = MAP_MAXRESET;
2264  MAP_RESET_TIMEOUT(map) = timeout;
2265  MAP_WHEN_RESET(map) = seconds()+timeout;
2266 }
2267 
2282 static mapstruct *load_and_link_tiled_map(mapstruct *orig_map, int tile_num) {
2283  int dest_tile = (tile_num+2)%4;
2284  char path[HUGE_BUF];
2285 
2286  path_combine_and_normalize(orig_map->path, orig_map->tile_path[tile_num], path, sizeof(path));
2287 
2288  orig_map->tile_map[tile_num] = ready_map_name(path, 0);
2289  if (orig_map->tile_map[tile_num] == NULL) {
2290  LOG(llevError, "%s has invalid tiled map %s\n", orig_map->path, path);
2291  free(orig_map->tile_path[tile_num]);
2292  orig_map->tile_path[tile_num] = NULL;
2293  return NULL;
2294  }
2295 
2296  /* need to do a strcmp here as the orig_map->path is not a shared string */
2297  if (orig_map->tile_map[tile_num]->tile_path[dest_tile]
2298  && !strcmp(orig_map->tile_map[tile_num]->tile_path[dest_tile], orig_map->path))
2299  orig_map->tile_map[tile_num]->tile_map[dest_tile] = orig_map;
2300 
2301  return orig_map->tile_map[tile_num];
2302 }
2303 
2321 int out_of_map(mapstruct *m, int x, int y) {
2322 
2323  /* Simple case - coordinates are within this local
2324  * map.
2325  */
2326  if (x >= 0 && x < MAP_WIDTH(m) && y >= 0 && y < MAP_HEIGHT(m))
2327  return 0;
2328 
2329  if (x < 0) {
2330  if (!m->tile_path[3])
2331  return 1;
2332  if (!m->tile_map[3] || m->tile_map[3]->in_memory != MAP_IN_MEMORY) {
2334  /* Verify the tile map loaded correctly */
2335  if (!m->tile_map[3])
2336  return 0;
2337  }
2338  return (out_of_map(m->tile_map[3], x+MAP_WIDTH(m->tile_map[3]), y));
2339  } else if (x >= MAP_WIDTH(m)) {
2340  if (!m->tile_path[1])
2341  return 1;
2342  if (!m->tile_map[1] || m->tile_map[1]->in_memory != MAP_IN_MEMORY) {
2344  /* Verify the tile map loaded correctly */
2345  if (!m->tile_map[1])
2346  return 0;
2347  }
2348  return (out_of_map(m->tile_map[1], x-MAP_WIDTH(m), y));
2349  }
2350 
2351  if (y < 0) {
2352  if (!m->tile_path[0])
2353  return 1;
2354  if (!m->tile_map[0] || m->tile_map[0]->in_memory != MAP_IN_MEMORY) {
2356  /* Verify the tile map loaded correctly */
2357  if (!m->tile_map[0])
2358  return 0;
2359  }
2360  return (out_of_map(m->tile_map[0], x, y+MAP_HEIGHT(m->tile_map[0])));
2361  } else if (y >= MAP_HEIGHT(m)) {
2362  if (!m->tile_path[2])
2363  return 1;
2364  if (!m->tile_map[2] || m->tile_map[2]->in_memory != MAP_IN_MEMORY) {
2366  /* Verify the tile map loaded correctly */
2367  if (!m->tile_map[2])
2368  return 0;
2369  }
2370  return (out_of_map(m->tile_map[2], x, y-MAP_HEIGHT(m)));
2371  }
2372  return 1;
2373 }
2374 
2395 
2396  /* Simple case - coordinates are within this local
2397  * map.
2398  */
2399 
2400  if ( !m ) return NULL;
2401  if (*x >= 0 && *x < MAP_WIDTH(m) && *y >= 0 && *y < MAP_HEIGHT(m))
2402  return m;
2403 
2404  do /* With the first case there, we can assume we are out of the map if we get here */
2405  {
2406  // Figure out what map should be in the direction we are off the map, and then
2407  // load that map and look again.
2408  if (*x < 0) {
2409  if (!m->tile_path[3])
2410  return NULL;
2411  if (!m->tile_map[3] || m->tile_map[3]->in_memory != MAP_IN_MEMORY){
2413  /* Make sure we loaded properly. */
2414  if (!m->tile_map[3])
2415  return NULL;
2416  }
2417  *x += MAP_WIDTH(m->tile_map[3]);
2418  m = m->tile_map[3];
2419  }
2420  else if (*x >= MAP_WIDTH(m)) {
2421  if (!m->tile_path[1])
2422  return NULL;
2423  if (!m->tile_map[1] || m->tile_map[1]->in_memory != MAP_IN_MEMORY){
2425  /* Make sure we loaded properly. */
2426  if (!m->tile_map[1])
2427  return NULL;
2428  }
2429  *x -= MAP_WIDTH(m);
2430  m = m->tile_map[1];
2431  }
2432  // It is possible that x and y be considered separate compare groups,
2433  // But using an else-if here retains the old behavior that recursion produced.
2434  else if (*y < 0) {
2435  if (!m->tile_path[0])
2436  return NULL;
2437  if (!m->tile_map[0] || m->tile_map[0]->in_memory != MAP_IN_MEMORY){
2439  /* Make sure we loaded properly. */
2440  if (!m->tile_map[0])
2441  return NULL;
2442  }
2443  *y += MAP_HEIGHT(m->tile_map[0]);
2444  m = m->tile_map[0];
2445  }
2446  else if (*y >= MAP_HEIGHT(m)) {
2447  if (!m->tile_path[2])
2448  return NULL;
2449  if (!m->tile_map[2] || m->tile_map[2]->in_memory != MAP_IN_MEMORY){
2451  /* Make sure we loaded properly. */
2452  if (!m->tile_map[2])
2453  return NULL;
2454  }
2455  *y -= MAP_HEIGHT(m);
2456  m = m->tile_map[2];
2457  }
2458  // The check here is if our single tile is in the map.
2459  // That is exactly what the OUT_OF_MAP macro does.
2460  } while (OUT_OF_REAL_MAP(m, *x, *y));
2461  return m; /* We have found our map */
2462 }
2463 
2477 static int adjacent_map(const mapstruct *map1, const mapstruct *map2, int *dx, int *dy) {
2478  if (!map1 || !map2)
2479  return 0;
2480 
2481  if (map1 == map2) {
2482  *dx = 0;
2483  *dy = 0;
2484  } else if (map1->tile_map[0] == map2) { /* up */
2485  *dx = 0;
2486  *dy = -MAP_HEIGHT(map2);
2487  } else if (map1->tile_map[1] == map2) { /* right */
2488  *dx = MAP_WIDTH(map1);
2489  *dy = 0;
2490  } else if (map1->tile_map[2] == map2) { /* down */
2491  *dx = 0;
2492  *dy = MAP_HEIGHT(map1);
2493  } else if (map1->tile_map[3] == map2) { /* left */
2494  *dx = -MAP_WIDTH(map2);
2495  *dy = 0;
2496  } else if (map1->tile_map[0] && map1->tile_map[0]->tile_map[1] == map2) { /* up right */
2497  *dx = MAP_WIDTH(map1->tile_map[0]);
2498  *dy = -MAP_HEIGHT(map1->tile_map[0]);
2499  } else if (map1->tile_map[0] && map1->tile_map[0]->tile_map[3] == map2) { /* up left */
2500  *dx = -MAP_WIDTH(map2);
2501  *dy = -MAP_HEIGHT(map1->tile_map[0]);
2502  } else if (map1->tile_map[1] && map1->tile_map[1]->tile_map[0] == map2) { /* right up */
2503  *dx = MAP_WIDTH(map1);
2504  *dy = -MAP_HEIGHT(map2);
2505  } else if (map1->tile_map[1] && map1->tile_map[1]->tile_map[2] == map2) { /* right down */
2506  *dx = MAP_WIDTH(map1);
2507  *dy = MAP_HEIGHT(map1->tile_map[1]);
2508  } else if (map1->tile_map[2] && map1->tile_map[2]->tile_map[1] == map2) { /* down right */
2509  *dx = MAP_WIDTH(map1->tile_map[2]);
2510  *dy = MAP_HEIGHT(map1);
2511  } else if (map1->tile_map[2] && map1->tile_map[2]->tile_map[3] == map2) { /* down left */
2512  *dx = -MAP_WIDTH(map2);
2513  *dy = MAP_HEIGHT(map1);
2514  } else if (map1->tile_map[3] && map1->tile_map[3]->tile_map[0] == map2) { /* left up */
2515  *dx = -MAP_WIDTH(map1->tile_map[3]);
2516  *dy = -MAP_HEIGHT(map2);
2517  } else if (map1->tile_map[3] && map1->tile_map[3]->tile_map[2] == map2) { /* left down */
2518  *dx = -MAP_WIDTH(map1->tile_map[3]);
2519  *dy = MAP_HEIGHT(map1->tile_map[3]);
2520  } else { /* not "adjacent" enough */
2521  return 0;
2522  }
2523 
2524  return 1;
2525 }
2526 
2554 int get_rangevector(object *op1, const object *op2, rv_vector *retval, int flags) {
2555  if (!adjacent_map(op1->map, op2->map, &retval->distance_x, &retval->distance_y)) {
2556  /* be conservative and fill in _some_ data */
2557  retval->distance = 100000;
2558  retval->distance_x = 32767;
2559  retval->distance_y = 32767;
2560  retval->direction = 0;
2561  retval->part = NULL;
2562  return 0;
2563  } else {
2564  object *best;
2565 
2566  retval->distance_x += op2->x-op1->x;
2567  retval->distance_y += op2->y-op1->y;
2568 
2569  best = op1;
2570  /* If this is multipart, find the closest part now */
2571  if (!(flags&0x1) && op1->more) {
2572  object *tmp;
2573  int best_distance = retval->distance_x*retval->distance_x+
2574  retval->distance_y*retval->distance_y, tmpi;
2575 
2576  /* we just take the offset of the piece to head to figure
2577  * distance instead of doing all that work above again
2578  * since the distance fields we set above are positive in the
2579  * same axis as is used for multipart objects, the simply arithmetic
2580  * below works.
2581  */
2582  for (tmp = op1->more; tmp != NULL; tmp = tmp->more) {
2583  tmpi = (op1->x-tmp->x+retval->distance_x)*(op1->x-tmp->x+retval->distance_x)+
2584  (op1->y-tmp->y+retval->distance_y)*(op1->y-tmp->y+retval->distance_y);
2585  if (tmpi < best_distance) {
2586  best_distance = tmpi;
2587  best = tmp;
2588  }
2589  }
2590  if (best != op1) {
2591  retval->distance_x += op1->x-best->x;
2592  retval->distance_y += op1->y-best->y;
2593  }
2594  }
2595  retval->part = best;
2596  retval->distance = isqrt(retval->distance_x*retval->distance_x+retval->distance_y*retval->distance_y);
2597  retval->direction = find_dir_2(-retval->distance_x, -retval->distance_y);
2598  return 1;
2599  }
2600 }
2601 
2627 int get_rangevector_from_mapcoord(const mapstruct *m, int x, int y, const object *op2, rv_vector *retval, int flags) {
2628  (void)flags; // unused [avoid compiler warning]
2629  if (!adjacent_map(m, op2->map, &retval->distance_x, &retval->distance_y)) {
2630  /* be conservative and fill in _some_ data */
2631  retval->distance = 100000;
2632  retval->distance_x = 32767;
2633  retval->distance_y = 32767;
2634  retval->direction = 0;
2635  retval->part = NULL;
2636  return 0;
2637  } else {
2638  retval->distance_x += op2->x-x;
2639  retval->distance_y += op2->y-y;
2640 
2641  retval->part = NULL;
2642  retval->distance = isqrt(retval->distance_x*retval->distance_x+retval->distance_y*retval->distance_y);
2643  retval->direction = find_dir_2(-retval->distance_x, -retval->distance_y);
2644  return 1;
2645  }
2646 }
2647 
2666 int on_same_map(const object *op1, const object *op2) {
2667  int dx, dy;
2668 
2669  return adjacent_map(op1->map, op2->map, &dx, &dy);
2670 }
2671 
2689 object *map_find_by_flag(mapstruct *map, int x, int y, int flag) {
2690  object *tmp;
2691 
2692  for (tmp = GET_MAP_OB(map, x, y); tmp != NULL; tmp = tmp->above) {
2693  object *head;
2694 
2695  head = HEAD(tmp);
2696  if (QUERY_FLAG(head, flag))
2697  return head;
2698  }
2699  return NULL;
2700 }
2701 
2707  char base[HUGE_BUF], path[HUGE_BUF];
2708  int count;
2709 
2710  if (map->unique) {
2711  snprintf(path, sizeof(path), "%s/%s/%s", settings.localdir, settings.playerdir, map->path+1);
2712  if (unlink(path) != 0) {
2713  LOG(llevError, "Could not delete %s: %s\n", path, strerror(errno));
2714  }
2715  return;
2716  }
2717 
2718  create_items_path(map->path, base, sizeof(base));
2719 
2720  for (count = 0; count < 10; count++) {
2721  snprintf(path, sizeof(path), "%s.v%02d", base, count);
2722  unlink(path);
2723  }
2724 }
2725 
2731 const char *map_get_path(const object *item) {
2732  if (item->map != NULL) {
2733  if (strlen(item->map->path) > 0) {
2734  return item->map->path;
2735  }
2736 
2737  return item->map->name ? item->map->name : "(empty path and name)";
2738  }
2739 
2740  if (item->env != NULL)
2741  return map_get_path(item->env);
2742 
2743  return "(no map and no env!)";
2744 }
#define FLAG_NO_MAGIC
Definition: define.h:276
char path[HUGE_BUF]
Definition: map.h:366
int find_dir_2(int x, int y)
Definition: object.c:3467
void free_all_maps(void)
Definition: map.c:1986
#define MSG_TYPE_MISC
Definition: newclient.h:389
Definition: player.h:92
double shopgreed
Definition: map.h:359
#define FLAG_DAMNED
Definition: define.h:318
mapstruct * mapfile_load(const char *map, int flags)
Definition: map.c:1213
#define FLAG_IS_FLOOR
Definition: define.h:303
#define FLAG_UNPAID
Definition: define.h:236
MapSpace * spaces
Definition: map.h:356
static void allocate_map(mapstruct *m)
Definition: map.c:840
#define MAP_STYLE
Definition: map.h:99
#define FLAG_IS_LINKED
Definition: define.h:316
#define S_IRGRP
Definition: win32.h:88
mapstruct * get_linked_map(void)
Definition: map.c:789
Definition: map.h:381
int64_t level_exp(int level, double expmul)
Definition: living.c:1872
#define P_PLAYER
Definition: map.h:237
#define SAVE_ERROR_OK
Definition: map.h:144
static mapstruct * load_and_link_tiled_map(mapstruct *orig_map, int tile_num)
Definition: map.c:2282
void of_cancel(OutputFile *of)
Definition: output_file.c:89
#define P_NEED_UPDATE
Definition: map.h:240
#define MAP_FLUSH
Definition: map.h:96
mapstruct * get_empty_map(int sizex, int sizey)
Definition: map.c:870
#define SET_FLAG(xyz, p)
Definition: define.h:223
int32_t swap_time
Definition: map.h:343
region * get_region_by_name(const char *region_name)
Definition: region.c:46
unsigned char uint8_t
Definition: win32.h:161
StringBuffer * buf
Definition: readable.c:1591
int get_rangevector_from_mapcoord(const mapstruct *m, int x, int y, const object *op2, rv_vector *retval, int flags)
Definition: map.c:2627
void make_path_to_file(const char *filename)
Definition: porting.c:316
object * part
Definition: map.h:386
const char * name_pl
Definition: define.h:92
#define strdup_local
Definition: compat.h:25
static int save_objects(mapstruct *m, FILE *fp, FILE *fp2, int flag)
Definition: map.c:738
uint32_t map_size(mapstruct *m)
Definition: map.c:826
#define MAP_LAYER_ITEM1
Definition: map.h:43
const Face * blank_face
Definition: image.c:35
#define P_NO_MAGIC
Definition: map.h:228
uint32_t nosmooth
Definition: map.h:340
static const Map_Layer_Info map_layer_info[MAP_LAYERS]
Definition: map.c:72
void fatal(enum fatal_error err)
Definition: utils.c:597
struct mapdef * tile_map[4]
Definition: map.h:365
char * create_pathname(const char *name, char *buf, size_t size)
Definition: map.c:113
uint32_t in_memory
Definition: map.h:346
mapstruct * ready_map_name(const char *name, int flags)
Definition: map.c:1797
const char * playerdir
Definition: global.h:247
unsigned char MoveType
Definition: define.h:432
#define LO_REPEAT
Definition: loader.h:15
#define MAP_ENTER_X(m)
Definition: map.h:85
void free_string(sstring str)
Definition: shstr.c:280
#define MAP_DEFAULTRESET
Definition: config.h:426
signed long object_sum_weight(object *op)
Definition: object.c:338
static shopitems * parse_shop_string(const char *input_string, const mapstruct *map)
Definition: map.c:892
#define FMT64U
Definition: compat.h:13
#define HUGE_BUF
Definition: define.h:37
void object_fix_multipart(object *tmp)
Definition: object.c:4442
#define MAP_MAXRESET
Definition: config.h:424
mapstruct * get_map_from_coord(mapstruct *m, int16_t *x, int16_t *y)
Definition: map.c:2394
#define S_IWOTH
Definition: win32.h:76
const char * object_get_value(const object *op, const char *const key)
Definition: object.c:4136
#define SET_MAP_LIGHT(M, X, Y, L)
Definition: map.h:168
uint32_t is_template
Definition: map.h:339
#define MAP_HEIGHT(m)
Definition: map.h:80
int calculate_difficulty(mapstruct *m)
Definition: map.c:1920
#define MAX_DARKNESS
Definition: define.h:469
int isqrt(int n)
Definition: utils.c:586
struct Map_Layer_Info Map_Layer_Info
void decay_objects(mapstruct *m)
Definition: utils.c:175
#define MAP_LAYER_FLOOR
Definition: map.h:40
const char * name
Definition: map.h:307
char * maplore
Definition: map.h:363
#define OUT_OF_REAL_MAP(M, X, Y)
Definition: map.h:218
int blocked_link(object *ob, mapstruct *m, int16_t sx, int16_t sy)
Definition: map.c:355
#define SAVE_MODE_NORMAL
Definition: map.h:121
const typedata * get_typedata_by_name(const char *name)
Definition: item.c:338
#define NDI_BLACK
Definition: newclient.h:221
void strip_endline(char *buf)
Definition: utils.c:341
void free_map(mapstruct *m)
Definition: map.c:1689
#define safe_strncpy
Definition: compat.h:23
static int load_temporary_map(mapstruct *m)
Definition: map.c:1276
int distance_y
Definition: map.h:384
void draw_ext_info(int flags, int pri, const object *pl, uint8_t type, uint8_t subtype, const char *message)
Definition: main.c:308
const char * map_get_path(const object *item)
Definition: map.c:2731
int change_map_light(mapstruct *m, int change)
Definition: map.c:2018
#define FLAG_REMOVED
Definition: define.h:232
#define MAP_WHEN_RESET(m)
Definition: map.h:62
int typenum
Definition: map.h:309
void events_execute_global_event(int eventcode,...)
Definition: events.cpp:27
#define CALLOC(x, y)
Definition: compat.h:27
#define PROFILE_BEGIN(expr)
Definition: map.c:38
#define MAP_LAYER_LIVING2
Definition: map.h:47
#define SAVE_ERROR_WRITE
Definition: map.h:147
#define NDI_NAVY
Definition: newclient.h:223
const typedata * get_typedata(int itemtype)
Definition: item.c:318
uint16_t height
Definition: map.h:348
#define MOVE_ALL
Definition: define.h:413
char * name
Definition: map.h:329
#define SAVE_FLAG_SAVE_UNPAID
Definition: map.h:111
#define MAP_IN_MEMORY
Definition: map.h:131
void object_free_drop_inventory(object *ob)
Definition: object.c:1316
#define MAP_LAYER_NO_PICK1
Definition: map.h:41
object * object_insert_in_map_at(object *op, mapstruct *m, object *originator, int flag, int x, int y)
Definition: object.c:1849
static int load_map_header(FILE *fp, mapstruct *m)
Definition: map.c:1023
char * name
Definition: map.h:279
#define FLAG_ALIVE
Definition: define.h:230
#define S_IROTH
Definition: win32.h:85
#define LL_NORMAL
Definition: loader.h:12
object * object_new(void)
Definition: object.c:1011
#define MAP_OVERLAY
Definition: map.h:100
#define FLAG_OBJ_ORIGINAL
Definition: define.h:365
#define MAP_SWAPPED
Definition: map.h:132
int index
Definition: map.h:312
signed short int16_t
Definition: win32.h:160
#define LO_NEWFILE
Definition: loader.h:17
int16_t enter_x
Definition: map.h:349
uint32_t unique
Definition: map.h:338
object * arch_to_object(archetype *at)
Definition: arch.cpp:232
const char * tmpdir
Definition: global.h:254
#define LL_MORE
Definition: loader.h:11
uint8_t honor_visibility
Definition: map.c:63
int8_t strength
Definition: map.h:310
#define SET_MAP_MOVE_SLOW(M, X, Y, C)
Definition: map.h:200
#define snprintf
Definition: win32.h:46
uint64_t shopmin
Definition: map.h:360
int ob_blocked(const object *ob, mapstruct *m, int16_t x, int16_t y)
Definition: map.c:498
static void link_multipart_objects(mapstruct *m)
Definition: map.c:594
#define MAP_TIMEOUT(m)
Definition: map.h:66
#define PROFILE_END(var, expr)
Definition: map.c:43
void dump_all_maps(void)
Definition: map.c:279
char * path_combine_and_normalize(const char *src, const char *dst, char *path, size_t size)
Definition: path.c:172
#define MOVE_FLYING
Definition: define.h:410
#define FOR_INV_FINISH()
Definition: define.h:714
char * msg
Definition: map.h:362
void object_remove_from_active_list(object *op)
Definition: object.c:1148
void update_position(mapstruct *m, int x, int y)
Definition: map.c:2142
#define S_IWGRP
Definition: win32.h:79
#define MAP_LAYERS
Definition: map.h:32
#define R_OK
Definition: win32.h:64
#define SET_MAP_PLAYER(M, X, Y, C)
Definition: map.h:170
int of_close(OutputFile *of)
Definition: output_file.c:61
object * objects
Definition: object.c:60
void remove_button_link(object *op)
Definition: button.c:693
#define FLAG_BLOCKSVIEW
Definition: define.h:269
long seconds(void)
Definition: time.c:344
int distance_x
Definition: map.h:383
int save_object(FILE *fp, object *op, int flag)
Definition: object.c:5114
char * tile_path[4]
Definition: map.h:364
#define MAP_LAYER_ITEM3
Definition: map.h:45
uint32_t fixed_resettime
Definition: map.h:336
#define MAP_ENTER_Y(m)
Definition: map.h:87
#define OB_TYPE_MOVE_BLOCK(ob1, type)
Definition: define.h:447
#define FLAG_OVERLAY_FLOOR
Definition: define.h:255
#define P_OUT_OF_MAP
Definition: map.h:252
#define SAVE_ERROR_NO_PATH
Definition: map.h:148
#define GET_MAP_MOVE_BLOCK(M, X, Y)
Definition: map.h:193
uint8_t darkness
Definition: map.h:347
const char * templatedir
Definition: global.h:253
#define MAP_DIFFICULTY(m)
Definition: map.h:65
#define SAVE_ERROR_URENAME
Definition: map.h:149
static void delete_unique_items(mapstruct *m)
Definition: map.c:1347
#define MAP_SAVING
Definition: map.h:134
void update_buttons(mapstruct *m)
Definition: button.c:227
#define SET_MAP_MOVE_OFF(M, X, Y, C)
Definition: map.h:210
long last_reset_time
Definition: map.h:367
int on_same_map(const object *op1, const object *op2)
Definition: map.c:2666
#define QUERY_FLAG(xyz, p)
Definition: define.h:225
#define CLEAR_FLAG(xyz, p)
Definition: define.h:224
#define FLAG_WIZ
Definition: define.h:231
#define SAVE_ERROR_CLOSE
Definition: map.h:150
#define MAP_NO_DIFFICULTY
Definition: map.h:98
void dump_map(const mapstruct *m)
Definition: map.c:256
#define MAX_BUF
Definition: define.h:35
#define MSG_TYPE_ATTACK
Definition: newclient.h:385
oblinkpt * buttons
Definition: map.h:355
int16_t enter_y
Definition: map.h:349
const char *const map_layer_name[MAP_LAYERS]
Definition: map.c:55
#define MAP_LAYER_FLY1
Definition: map.h:48
uint16_t difficulty
Definition: map.h:344
signed __int64 int64_t
Definition: win32.h:168
static const flag_definition flags[]
#define EVENT_MAPUNLOAD
Definition: events.h:49
#define FOR_MAP_FINISH()
Definition: define.h:767
const char * uniquedir
Definition: global.h:252
#define MAP_LAYER_NO_PICK2
Definition: map.h:42
static int adjacent_map(const mapstruct *map1, const mapstruct *map2, int *dx, int *dy)
Definition: map.c:2477
char * tmpname
Definition: map.h:328
#define SAVE_FLAG_NO_REMOVE
Definition: map.h:112
int save_map(mapstruct *m, int flag)
Definition: map.c:1419
uint8_t high_layer
Definition: map.c:62
#define SAVE_ERROR_UCREATION
Definition: map.h:146
int32_t timeout
Definition: map.h:342
#define GET_MAP_FLAGS(M, X, Y)
Definition: map.h:162
unsigned int uint32_t
Definition: win32.h:162
const char * datadir
Definition: global.h:245
object * check_inv_recursive(object *op, const object *trig)
Definition: button.c:782
static void free_all_objects(mapstruct *m)
Definition: map.c:1642
#define SET_MAP_MOVE_ON(M, X, Y, C)
Definition: map.h:205
void set_map_reset_time(mapstruct *map)
Definition: map.c:2256
#define SET_MAP_FLAGS(M, X, Y, C)
Definition: map.h:164
#define P_NEW_MAP
Definition: map.h:253
#define FLAG_GENERATOR
Definition: define.h:248
#define MAP_LAYER_LIVING1
Definition: map.h:46
uint32_t outdoor
Definition: map.h:341
static void load_unique_objects(mapstruct *m)
Definition: map.c:1372
Definition: map.h:259
const char * name
Definition: define.h:91
void update_all_map_los(mapstruct *map)
Definition: los.c:508
object * map_find_by_flag(mapstruct *map, int x, int y, int flag)
Definition: map.c:2689
#define MAP_PLAYER_UNIQUE
Definition: map.h:97
const char * localdir
Definition: global.h:246
const char * name_pl
Definition: map.h:308
int load_object(FILE *fp, object *op, int bufstate, int map_flags)
mapstruct * has_been_loaded(const char *name)
Definition: map.c:88
#define AB_NO_PASS
Definition: map.h:236
#define MAP_WIDTH(m)
Definition: map.h:78
#define unlink(__a)
Definition: win32.h:56
const char * mapdir
Definition: global.h:248
uint32_t reset_timeout
Definition: map.h:334
static void print_shop_string(mapstruct *m, char *output_string, int size)
Definition: map.c:978
uint64_t shopmax
Definition: map.h:361
uint16_t width
Definition: map.h:348
unsigned int distance
Definition: map.h:382
struct Settings settings
Definition: init.c:39
static void load_objects(mapstruct *m, FILE *fp, int mapflags)
Definition: map.c:622
FILE * of_open(OutputFile *of, const char *fname)
Definition: output_file.c:30
int direction
Definition: map.h:385
#define SAVE_MODE
Definition: config.h:566
Definition: map.h:306
#define TEMP_EXT
#define EVENT_MAPLOAD
Definition: events.h:47
int out_of_map(mapstruct *m, int x, int y)
Definition: map.c:2321
void delete_map(mapstruct *m)
Definition: map.c:1735
void apply_auto_fix(mapstruct *m)
Definition: main.c:259
#define MAP_RESET_TIMEOUT(m)
Definition: map.h:64
#define MAP_LOADING
Definition: map.h:133
#define GET_MAP_FACE_OBJS(M, X, Y)
Definition: map.h:190
static void create_items_path(const char *s, char *buf, size_t size)
Definition: map.c:177
sstring add_string(const char *str)
Definition: shstr.c:124
#define GET_MAP_OB(M, X, Y)
Definition: map.h:173
int check_path(const char *name, int prepend_dir)
Definition: map.c:212
#define FLAG_MONSTER
Definition: define.h:245
static void fix_container_multipart(object *container)
Definition: map.c:553
int get_map_flags(mapstruct *oldmap, mapstruct **newmap, int16_t x, int16_t y, int16_t *nx, int16_t *ny)
Definition: map.c:311
#define NDI_UNIQUE
Definition: newclient.h:245
#define OB_MOVE_BLOCK(ob1, ob2)
Definition: define.h:438
#define SAVE_ERROR_RRENAME
Definition: map.h:151
#define MSG_SUBTYPE_NONE
Definition: newclient.h:398
void LOG(LogLevel logLevel, const char *format,...)
Definition: logger.c:51
uint8_t flags
Definition: map.h:263
#define SAVE_ERROR_RCREATION
Definition: map.h:145
#define LO_NOREAD
Definition: loader.h:18
#define FOR_MAP_PREPARE(map_, mx_, my_, it_)
Definition: define.h:760
struct shopitem * shopitems
Definition: map.h:357
#define S_IRUSR
Definition: win32.h:91
#define S_IWUSR
Definition: win32.h:82
#define MSG_TYPE_ATTACK_NOKEY
Definition: newclient.h:612
struct mapdef * next
Definition: map.h:327
#define P_BLOCKSVIEW
Definition: map.h:227
#define P_NO_ERROR
Definition: map.h:241
void set_darkness_map(mapstruct *m)
Definition: main.c:346
int number
Definition: define.h:90
char * shoprace
Definition: map.h:358
#define MAP_LAYER_FLY2
Definition: map.h:49
void create_overlay_pathname(const char *name, char *buf, size_t size)
Definition: map.c:134
Definition: map.h:326
char * background_music
Definition: map.h:368
#define P_IS_ALIVE
Definition: map.h:238
#define FREE_AND_CLEAR(xyz)
Definition: global.h:193
#define FLAG_UNIQUE
Definition: define.h:288
#define FLAG_NO_PICK
Definition: define.h:239
#define SET_MAP_MOVE_BLOCK(M, X, Y, C)
Definition: map.h:195
static int load_overlay_map(const char *filename, mapstruct *m)
Definition: map.c:1312
int get_rangevector(object *op1, const object *op2, rv_vector *retval, int flags)
Definition: map.c:2554
void ext_info_map(int color, const mapstruct *map, uint8_t type, uint8_t subtype, const char *str1)
Definition: main.c:323
#define S_ISREG(x)
Definition: win32.h:70
void create_template_pathname(const char *name, char *buf, size_t size)
Definition: map.c:154
void map_remove_unique_files(const mapstruct *map)
Definition: map.c:2706
struct regiondef * region
Definition: map.h:330
void clean_tmp_map(mapstruct *m)
Definition: map.c:1977
EXTERN mapstruct * first_map
Definition: global.h:116
void clean_object(object *op)
Definition: map.c:1626
object * object_get_owner(object *op)
Definition: object.c:568
#define SAVE_MODE_OVERLAY
Definition: map.h:123
#define P_NO_CLERIC
Definition: map.h:239
size_t strlcpy(char *dst, const char *src, size_t size)
Definition: porting.c:370
#define FOR_INV_PREPARE(op_, it_)
Definition: define.h:707
void object_remove(object *op)
Definition: object.c:1588
static void add_face_layer(int low_layer, int high_layer, object *ob, object *layers[], int honor_visibility)
Definition: map.c:2073