Debian Codegraph @

common/map.c

raw symbols SCIP
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 <[email protected]>.
12 */
13
14 /**
15 * @file map.c
16 * Map-related functions.
17 */
18
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
28 #ifndef WIN32 /* ---win32 exclude header */
29 #include <unistd.h>
30 #endif /* win32 */
31
32 #include "sproto.h"
33 #include "loader.h"
34 #include "output_file.h"
35 #include "path.h"
36
37 #define PROFILE_BEGIN(expr) { \
38 struct timespec _begin, _end; \
39 clock_gettime(CLOCK_MONOTONIC, &_begin); \
40 expr;
41
42 #define PROFILE_END(var, expr) \
43 clock_gettime(CLOCK_MONOTONIC, &_end); \
44 long var = timespec_diff(&_end, &_begin); \
45 expr; }
46
47 static void free_all_objects(mapstruct *m);
48
49 /**
50 * These correspond to the layer names in map.h -
51 * since some of the types can be on multiple layers,
52 * names are duplicated to correspond to that layer.
53 */
54 const char *const map_layer_name[MAP_LAYERS] = {
55 "floor", "no_pick", "no_pick", "item", "item",
56 "item", "living", "living", "fly", "fly"
57 };
58
59 /** Information about a layer. */
60 typedef struct Map_Layer_Info {
61 uint8_t high_layer; /**< Highest layer for this group. */
62 uint8_t honor_visibility; /**< If 0 then don't reorder items, else allow. */
63 } Map_Layer_Info;
64
65 /**
66 * the ob->map_layer holds the low layer. For the update_position()
67 * logic, we also need to know the higher layer and whether
68 * visibility should be honored. This table has that information,
69 * so that it doesn't need to be hardcoded.
70 */
71 static const Map_Layer_Info map_layer_info[MAP_LAYERS] = {
72 { MAP_LAYER_FLOOR, 1 },
73 { MAP_LAYER_NO_PICK2, 0 }, { MAP_LAYER_NO_PICK2, 0 },
74 { MAP_LAYER_ITEM3, 1 }, { MAP_LAYER_ITEM3, 1 }, { MAP_LAYER_ITEM3, 1 },
75 { MAP_LAYER_LIVING2, 1 }, { MAP_LAYER_LIVING2, 1 },
76 { MAP_LAYER_FLY2, 1 }, { MAP_LAYER_FLY2, 1 }
77 };
78
79 /**
80 * Checks whether map has been loaded.
81 * @param name
82 * path of the map to search. Can be NULL.
83 * @return
84 * the mapstruct which has a name matching the given argument.
85 * return NULL if no match is found.
86 */
87 mapstruct *has_been_loaded(const char *name) {
88 mapstruct *map;
89
90 if (!name || !*name)
91 return NULL;
92
93 for (map = first_map; map; map = map->next)
94 if (!strcmp(name, map->path))
95 break;
96 return (map);
97 }
98
99 /**
100 * Get the full path to a map file. This simply means prepending the correct
101 * map directory to the given path.
102 *
103 * @param name
104 * path of the map.
105 * @param buf
106 * buffer that will contain the full path.
107 * @param size
108 * buffer's length.
109 * @return
110 * buf.
111 */
112 char *create_pathname(const char *name, char *buf, size_t size) {
113 /* Why? having extra / doesn't confuse unix anyplace? Dependancies
114 * someplace else in the code? msw 2-17-97
115 */
116 if (*name == '/')
117 snprintf(buf, size, "%s/%s%s", settings.datadir, settings.mapdir, name);
118 else
119 snprintf(buf, size, "%s/%s/%s", settings.datadir, settings.mapdir, name);
120 return buf;
121 }
122
123 /**
124 * Same as create_pathname(), but for the overlay maps.
125 /
126 * @param name
127 * path of the overlay map.
128 * @param buf
129 * buffer that will contain the full path.
130 * @param size
131 * buffer's length.
132 */
133 void create_overlay_pathname(const char *name, char *buf, size_t size) {
134 /* Why? having extra / doesn't confuse unix anyplace? Dependancies
135 * someplace else in the code? msw 2-17-97
136 */
137 if (*name == '/')
138 snprintf(buf, size, "%s/%s%s", settings.localdir, settings.mapdir, name);
139 else
140 snprintf(buf, size, "%s/%s/%s", settings.localdir, settings.mapdir, name);
141 }
142
143 /**
144 * same as create_pathname(), but for the template maps.
145 *
146 * @param name
147 * path of the template map.
148 * @param buf
149 * buffer that will contain the full path.
150 * @param size
151 * buf's length
152 */
153 void create_template_pathname(const char *name, char *buf, size_t size) {
154 /* Why? having extra / doesn't confuse unix anyplace? Dependancies
155 * someplace else in the code? msw 2-17-97
156 */
157 if (*name == '/')
158 snprintf(buf, size, "%s/%s%s", settings.localdir, settings.templatedir, name);
159 else
160 snprintf(buf, size, "%s/%s/%s", settings.localdir, settings.templatedir, name);
161 }
162
163 /**
164 * This makes absolute path to the itemfile where unique objects
165 * will be saved. Converts '/' to '@'. I think it's essier maintain
166 * files than full directory structure, but if this is problem it can
167 * be changed.
168 *
169 * @param s
170 * path of the map for the item.
171 * @param buf
172 * buffer that will contain path. Must not be NULL.
173 * @param size
174 * buffer's length.
175 */
176 static void create_items_path(const char *s, char *buf, size_t size) {
177 char *t;
178
179 if (*s == '/')
180 s++;
181
182 snprintf(buf, size, "%s/%s/", settings.localdir, settings.uniquedir);
183 t = buf+strlen(buf);
184 snprintf(t, buf+size-t, "%s", s);
185
186 while (*t != '\0') {
187 if (*t == '/')
188 *t = '@';
189 t++;
190 }
191 }
192
193 /**
194 * This function checks if a file with the given path exists.
195 *
196 * @param name
197 * map path to check.
198 * @param prepend_dir
199 * If set, then we call create_pathname (which prepends libdir & mapdir).
200 * Otherwise, we assume the name given is fully complete.
201 * @return
202 * -1 if it fails, otherwise the mode of the file is returned.
203 *
204 * @note
205 * Only the editor actually cares about the writablity of this -
206 * the rest of the code only cares that the file is readable.
207 * when the editor goes away, the call to stat should probably be
208 * replaced by an access instead (similar to the windows one, but
209 * that seems to be missing the prepend_dir processing
210 */
211 int check_path(const char *name, int prepend_dir) {
212 char buf[MAX_BUF];
213 #ifndef WIN32
214 struct stat statbuf;
215 int mode = 0;
216 #endif
217
218 if (prepend_dir)
219 create_pathname(name, buf, MAX_BUF);
220 else
221 strlcpy(buf, name, sizeof(buf));
222 #ifdef WIN32 /* ***win32: check this sucker in windows style. */
223 return(_access(buf, 0));
224 #else
225
226 if (stat(buf, &statbuf) != 0)
227 return -1;
228
229 if (!S_ISREG(statbuf.st_mode))
230 return (-1);
231
232 if (((statbuf.st_mode&S_IRGRP) && getegid() == statbuf.st_gid)
233 || ((statbuf.st_mode&S_IRUSR) && geteuid() == statbuf.st_uid)
234 || (statbuf.st_mode&S_IROTH))
235 mode |= 4;
236
237 if ((statbuf.st_mode&S_IWGRP && getegid() == statbuf.st_gid)
238 || (statbuf.st_mode&S_IWUSR && geteuid() == statbuf.st_uid)
239 || (statbuf.st_mode&S_IWOTH))
240 mode |= 2;
241
242 return (mode);
243 #endif
244 }
245
246 /**
247 * Prints out debug-information about a map.
248 * Dumping these at llevError doesn't seem right, but is
249 * necessary to make sure the information is in fact logged.
250 * Can be used by a DM with the dumpmap command.
251 *
252 * @param m
253 * map to dump.
254 */
255 void dump_map(const mapstruct *m) {
256 LOG(llevError, "Map %s status: %d.\n", m->path, m->in_memory);
257 LOG(llevError, "Size: %dx%d Start: %d,%d\n", MAP_WIDTH(m), MAP_HEIGHT(m), MAP_ENTER_X(m), MAP_ENTER_Y(m));
258
259 if (m->msg != NULL)
260 LOG(llevError, "Message:\n%s", m->msg);
261
262 if (m->maplore != NULL)
263 LOG(llevError, "Lore:\n%s", m->maplore);
264
265 if (m->tmpname != NULL)
266 LOG(llevError, "Tmpname: %s\n", m->tmpname);
267
268 LOG(llevError, "Difficulty: %d\n", m->difficulty);
269 LOG(llevError, "Darkness: %d\n", m->darkness);
270 }
271
272 /**
273 * Prints out debug-information about all maps.
274 * This basically just goes through all the maps and calls
275 * dump_map() on each one.
276 * Can be used by a DM with the dumpallmaps command.
277 */
278 void dump_all_maps(void) {
279 mapstruct *m;
280
281 for (m = first_map; m != NULL; m = m->next) {
282 dump_map(m);
283 }
284 }
285
286 /**
287 * This rolls up wall, blocks_magic, blocks_view, etc, all into
288 * one function that just returns a P_.. value (see map.h)
289 * it will also do map translation for tiled maps, returning
290 * new values into newmap, nx, and ny. Any and all of those
291 * values can be null, in which case if a new map is needed (returned
292 * by a P_NEW_MAP value, another call to get_map_from_coord
293 * is needed. The case of not passing values is if we're just
294 * checking for the existence of something on those spaces, but
295 * don't expect to insert/remove anything from those spaces.
296 *
297 * @param oldmap
298 * map for which we want information.
299 * @param newmap
300 * if not NULL, will contain the actual map checked if not oldmap.
301 * @param x
302 * @param y
303 * coordinates to check
304 * @param nx
305 * @param ny
306 * if not NULL, will contain the actual coordinates checked.
307 * @return
308 * flags for specified position, with maybe ::P_OUT_OF_MAP or ::P_NEW_MAP set.
309 */
310 int get_map_flags(mapstruct *oldmap, mapstruct **newmap, int16_t x, int16_t y, int16_t *nx, int16_t *ny) {
311 int retval = 0;
312 mapstruct *mp;
313
314 /*
315 * Since x and y are copies of the original values, we can directly
316 * mess with them here.
317 */
318 mp = get_map_from_coord(oldmap, &x, &y);
319 if (!mp)
320 return P_OUT_OF_MAP;
321 if (mp != oldmap)
322 retval |= P_NEW_MAP;
323 if (newmap)
324 *newmap = mp;
325 if (nx)
326 *nx = x;
327 if (ny)
328 *ny = y;
329 retval |= mp->spaces[x+mp->width*y].flags;
330 return retval;
331 }
332
333 /**
334 * Returns true if the given coordinate is blocked except by the
335 * object passed is not blocking. This is used with
336 * multipart monsters - if we want to see if a 2x2 monster
337 * can move 1 space to the left, we don't want its own area
338 * to block it from moving there.
339 *
340 * @param ob
341 * object we ignore. Must not be NULL.
342 * @param m
343 * map we're considering.
344 * @param sx
345 * @param sy
346 * target coordinates
347 * @return
348 * TRUE if the space is blocked by something other than ob.
349 *
350 * @note
351 * the coordinates & map passed in should have been updated for tiling
352 * by the caller.
353 */
354 int blocked_link(object *ob, mapstruct *m, int16_t sx, int16_t sy) {
355 object *tmp_head;
356 int mflags, blocked;
357
358 /* Make sure the coordinates are valid - they should be, as caller should
359 * have already checked this.
360 */
361 if (OUT_OF_REAL_MAP(m, sx, sy)) {
362 LOG(llevError, "blocked_link: Passed map, x, y coordinates outside of map\n");
363 return 1;
364 }
365
366 /* special hack for transports: if it's a transport with a move_type of 0, it can do on the space anyway */
367 if (ob->type == TRANSPORT && ob->move_type == 0)
368 return 0;
369
370 /* Save some cycles - instead of calling get_map_flags(), just get the value
371 * directly.
372 */
373 mflags = m->spaces[sx+m->width*sy].flags;
374
375 blocked = GET_MAP_MOVE_BLOCK(m, sx, sy);
376
377 /* If space is currently not blocked by anything, no need to
378 * go further. Not true for players - all sorts of special
379 * things we need to do for players.
380 */
381 if (ob->type != PLAYER && !(mflags&P_IS_ALIVE) && (blocked == 0))
382 return 0;
383
384 /* if there isn't anytyhing alive on this space, and this space isn't
385 * otherwise blocked, we can return now. Only if there is a living
386 * creature do we need to investigate if it is part of this creature
387 * or another. Likewise, only if something is blocking us do we
388 * need to investigate if there is a special circumstance that would
389 * let the player through (inventory checkers for example)
390 */
391 if (!(mflags&P_IS_ALIVE) && !OB_TYPE_MOVE_BLOCK(ob, blocked))
392 return 0;
393
394 ob = HEAD(ob);
395
396 /* We basically go through the stack of objects, and if there is
397 * some other object that has NO_PASS or FLAG_ALIVE set, return
398 * true. If we get through the entire stack, that must mean
399 * ob is blocking it, so return 0.
400 */
401 FOR_MAP_PREPARE(m, sx, sy, tmp) {
402 /* Never block part of self. */
403 tmp_head = HEAD(tmp);
404 if (tmp_head == ob)
405 continue;
406 /* This must be before the checks below. Code for inventory checkers. */
407 if (tmp->type == CHECK_INV && OB_MOVE_BLOCK(ob, tmp)) {
408 /* If last_sp is set, the player/monster needs an object,
409 * so we check for it. If they don't have it, they can't
410 * pass through this space.
411 */
412 if (tmp->last_sp) {
413 if (check_inv_recursive(ob, tmp) == NULL) {
414 if (tmp->msg) {
415 /* Optionally display the reason why one cannot move
416 * there. Note: emitting a message from this function
417 * is not very elegant. Ideally, this should be done
418 * somewhere in server/player.c, but this is difficult
419 * for objects of type CHECK_INV that are not alive.
420 */
421 draw_ext_info(NDI_UNIQUE|NDI_NAVY, 0, ob,
422 MSG_TYPE_ATTACK, MSG_TYPE_ATTACK_NOKEY,
423 tmp->msg);
424 }
425 return 1;
426 }
427 } else {
428 /* In this case, the player must not have the object -
429 * if they do, they can't pass through.
430 */
431 if (check_inv_recursive(ob, tmp) != NULL) {
432 if (tmp->msg) {
433 draw_ext_info(NDI_UNIQUE|NDI_NAVY, 0, ob,
434 MSG_TYPE_ATTACK, MSG_TYPE_ATTACK_NOKEY,
435 tmp->msg);
436 }
437 return 1;
438 }
439 }
440 } /* if check_inv */
441 else {
442 /* Broke apart a big nasty if into several here to make
443 * this more readable. first check - if the space blocks
444 * movement, can't move here.
445 * second - if a monster, can't move there, unless it is a
446 * hidden dm
447 */
448 if (OB_MOVE_BLOCK(ob, tmp))
449 return 1;
450 if (QUERY_FLAG(tmp, FLAG_ALIVE)
451 && tmp->head != ob
452 && tmp != ob
453 && tmp->type != DOOR
454 && !(QUERY_FLAG(tmp, FLAG_WIZ) && tmp->contr->hidden))
455 return 1;
456 }
457 } FOR_MAP_FINISH();
458 return 0;
459 }
460
461 /**
462 * Returns true if the given object can't fit in the given spot.
463 * This is meant for multi space objects - for single space objecs,
464 * just calling get_map_blocked and checking that against movement type
465 * of object. This function goes through all the parts of the
466 * multipart object and makes sure they can be inserted.
467 *
468 * While this doesn't call out of map, the get_map_flags does.
469 *
470 * This function has been used to deprecate arch_out_of_map -
471 * this function also does that check, and since in most cases,
472 * a call to one would follow the other, doesn't make a lot of sense to
473 * have two seperate functions for this.
474 *
475 * This returns nonzero if this arch can not go on the space provided,
476 * 0 otherwise. the return value will contain the P_.. value
477 * so the caller can know why this object can't go on the map.
478 * Note that callers should not expect ::P_NEW_MAP to be set
479 * in return codes - since the object is multispace - if
480 * we did return values, what do you return if half the object
481 * is one map, half on another.
482 *
483 * @param ob
484 * object to test.
485 * @param m
486 * @param x
487 * @param y
488 * map and coordinates to check.
489 * @return
490 * 0 if the object can fit on specified space, non-zero else.
491 *
492 * @note
493 * This used to be arch_blocked, but with new movement
494 * code, we need to have actual object to check its move_type
495 * against the move_block values.
496 */
497 int ob_blocked(const object *ob, mapstruct *m, int16_t x, int16_t y) {
498 archetype *tmp;
499 int flag;
500 mapstruct *m1;
501 int16_t sx, sy;
502 const object *part;
503
504 if (ob == NULL) {
505 flag = get_map_flags(m, &m1, x, y, &sx, &sy);
506 if (flag&P_OUT_OF_MAP)
507 return P_OUT_OF_MAP;
508
509 /* don't have object, so don't know what types would block */
510 return(GET_MAP_MOVE_BLOCK(m1, sx, sy));
511 }
512
513 for (tmp = ob->arch, part = ob; tmp != NULL; tmp = tmp->more, part = part->more) {
514 flag = get_map_flags(m, &m1, x+tmp->clone.x, y+tmp->clone.y, &sx, &sy);
515
516 if (flag&P_OUT_OF_MAP)
517 return P_OUT_OF_MAP;
518 if (flag&P_IS_ALIVE)
519 return P_IS_ALIVE;
520
521 /* object_find_first_free_spot() calls this function. However, often
522 * ob doesn't have any move type (when used to place exits)
523 * so the AND operation in OB_TYPE_MOVE_BLOCK doesn't work.
524 */
525
526 if (ob->move_type == 0 && GET_MAP_MOVE_BLOCK(m1, sx, sy) != MOVE_ALL)
527 continue;
528
529 /* A transport without move_type for a part should go through everything for that part. */
530 if (ob->type == TRANSPORT && part->move_type == 0)
531 continue;
532
533 /* Note it is intentional that we check ob - the movement type of the
534 * head of the object should correspond for the entire object.
535 */
536 if (OB_TYPE_MOVE_BLOCK(ob, GET_MAP_MOVE_BLOCK(m1, sx, sy)))
537 return AB_NO_PASS;
538 }
539 return 0;
540 }
541
542 /**
543 * Go through all the objects in a container (recursively) looking
544 * for objects whose arch says they are multipart yet according to the
545 * info we have, they only have the head (as would be expected when
546 * they are saved). We do have to look for the old maps that did save
547 * the more sections and not re-add sections for them.
548 *
549 * @param container
550 * object that contains the inventory.
551 */
552 static void fix_container_multipart(object *container) {
553 FOR_INV_PREPARE(container, tmp) {
554 archetype *at;
555 object *op, *last;
556
557 if (tmp->inv)
558 fix_container_multipart(tmp);
559 /* already multipart, or non-multipart arch - don't do anything more */
560 for (at = tmp->arch->more, last = tmp; at != NULL; at = at->more, last = op) {
561 /* FIXME: We can't reuse object_fix_multipart() since that only
562 * works for items directly on maps. Maybe factor out common code?
563 */
564 op = arch_to_object(at);
565 op->head = tmp;
566 op->env = tmp->env;
567 last->more = op;
568 if (tmp->name != op->name) {
569 if (op->name)
570 free_string(op->name);
571 op->name = add_string(tmp->name);
572 }
573 if (tmp->title != op->title) {
574 if (op->title)
575 free_string(op->title);
576 op->title = add_string(tmp->title);
577 }
578 CLEAR_FLAG(op, FLAG_REMOVED);
579 }
580 } FOR_INV_FINISH();
581 }
582
583 /**
584 * Go through all the objects on the map looking
585 * for objects whose arch says they are multipart yet according to the
586 * info we have, they only have the head (as would be expected when
587 * they are saved). We do have to look for the old maps that did save
588 * the more sections and not re-add sections for them.
589 *
590 * @param m
591 * map to check.
592 */
593 static void link_multipart_objects(mapstruct *m) {
594 int x, y;
595
596 for (x = 0; x < MAP_WIDTH(m); x++)
597 for (y = 0; y < MAP_HEIGHT(m); y++)
598 FOR_MAP_PREPARE(m, x, y, tmp) {
599 if (tmp->inv)
600 fix_container_multipart(tmp);
601
602 /* already multipart - don't do anything more */
603 if (tmp->head || tmp->more)
604 continue;
605
606 object_fix_multipart(tmp);
607 } FOR_MAP_FINISH(); /* for objects on this space */
608 }
609
610 /**
611 * Loads (and parses) the objects into a given map from the specified
612 * file pointer.
613 *
614 * @param m
615 * m being loaded.
616 * @param fp
617 * file to read from.
618 * @param mapflags
619 * the same as we get with mapfile_load()
620 */
621 static void load_objects(mapstruct *m, FILE *fp, int mapflags) {
622 int i, j, bufstate = LO_NEWFILE;
623 int unique;
624 object *op, *prev = NULL, *last_more = NULL;
625
626 op = object_new();
627 op->map = m; /* To handle buttons correctly */
628
629 PROFILE_BEGIN(long cum_body_time = 0;);
630 while ((i = load_object(fp, op, bufstate, mapflags))) {
631 /* Since the loading of the map header does not load an object
632 * anymore, we need to pass LO_NEWFILE for the first object loaded,
633 * and then switch to LO_REPEAT for faster loading.
634 */
635 bufstate = LO_REPEAT;
636
637 /* if the archetype for the object is null, means that we
638 * got an invalid object. Don't do anything with it - the game
639 * or editor will not be able to do anything with it either.
640 */
641 if (op->arch == NULL) {
642 LOG(llevDebug, "Discarding object without arch: %s\n", op->name ? op->name : "(null)");
643 continue;
644 }
645
646 /*
647 * You can NOT have players on a map being loaded.
648 * Trying to use such a type leads to crashes everywhere as op->contr is NULL.
649 */
650 if (op->type == PLAYER) {
651 LOG(llevError, "Discarding invalid item with type PLAYER in map %s\n", m->path);
652 continue;
653 }
654
655 /* don't use out_of_map because we don't want to consider tiling properties, we're loading a single map */
656 if (op->x < 0 || op->y < 0 || op->x >= MAP_WIDTH(m) || op->y >= MAP_HEIGHT(m)) {
657 LOG(llevError, " object %s not on valid map position %s:%d:%d\n", op->name ? op->name : "(null)", m->path, op->x, op->y);
658 if (op->x < 0) {
659 op->x = 0;
660 } else if (op->x >= MAP_WIDTH(m)) {
661 op->x = MAP_WIDTH(m) - 1;
662 }
663 if (op->y < 0) {
664 op->y = 0;
665 } else if (op->y >= MAP_HEIGHT(m)) {
666 op->y = MAP_HEIGHT(m) - 1;
667 }
668 }
669
670 PROFILE_BEGIN();
671 switch (i) {
672 case LL_NORMAL:
673 /* if we are loading an overlay, put the floors on the bottom */
674 if ((QUERY_FLAG(op, FLAG_IS_FLOOR) || QUERY_FLAG(op, FLAG_OVERLAY_FLOOR))
675 && mapflags&MAP_OVERLAY)
676 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);
677 else
678 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);
679
680 if (op->inv)
681 object_sum_weight(op);
682
683 prev = op,
684 last_more = op;
685 break;
686
687 case LL_MORE:
688 object_insert_in_map_at(op, m, op, INS_NO_MERGE|INS_NO_WALK_ON|INS_ABOVE_FLOOR_ONLY, op->x, op->y);
689 op->head = prev,
690 last_more->more = op,
691 last_more = op;
692 break;
693 }
694 if (mapflags&MAP_STYLE) {
695 object_remove_from_active_list(op);
696 }
697 PROFILE_END(diff, cum_body_time += diff);
698 op = object_new();
699 op->map = m;
700 }
701 PROFILE_END(diff, LOG(llevDebug,
702 "load_objects: while loop took %ld, body took %ld\n",
703 diff, cum_body_time));
704 for (i = 0; i < m->width; i++) {
705 for (j = 0; j < m->height; j++) {
706 unique = 0;
707 /* check for unique items, or unique squares */
708 FOR_MAP_PREPARE(m, i, j, otmp) {
709 if (QUERY_FLAG(otmp, FLAG_UNIQUE))
710 unique = 1;
711 if (!(mapflags&(MAP_OVERLAY|MAP_PLAYER_UNIQUE) || unique))
712 SET_FLAG(otmp, FLAG_OBJ_ORIGINAL);
713 } FOR_MAP_FINISH();
714 }
715 }
716 object_free_drop_inventory(op);
717 link_multipart_objects(m);
718 }
719
720 /**
721 * This saves all the objects on the map in a non destructive fashion.
722 * Modified by MSW 2001-07-01 to do in a single pass - reduces code,
723 * and we only save the head of multi part objects - this is needed
724 * in order to do map tiling properly.
725 *
726 * @param m
727 * map to save.
728 * @param fp
729 * file where regular objects are saved.
730 * @param fp2
731 * file to save unique objects.
732 * @param flag
733 * combination of @ref SAVE_FLAG_xxx "SAVE_FLAG_xxx" flags.
734 * @return
735 * one of @ref SAVE_ERROR_xxx "SAVE_ERROR_xxx" value.
736 */
737 static int save_objects(mapstruct *m, FILE *fp, FILE *fp2, int flag) {
738 int i, j = 0, unique = 0, res = 0;
739 unsigned int count = 0;
740
741 PROFILE_BEGIN();
742 /* first pass - save one-part objects */
743 for (i = 0; i < MAP_WIDTH(m); i++)
744 for (j = 0; j < MAP_HEIGHT(m); j++) {
745 unique = 0;
746 FOR_MAP_PREPARE(m, i, j, op) {
747 if (QUERY_FLAG(op, FLAG_IS_FLOOR) && QUERY_FLAG(op, FLAG_UNIQUE))
748 unique = 1;
749
750 if (op->type == PLAYER) {
751 LOG(llevDebug, "Player on map that is being saved\n");
752 continue;
753 }
754
755 if (op->head || object_get_owner(op) != NULL)
756 continue;
757
758 if (unique || QUERY_FLAG(op, FLAG_UNIQUE)) {
759 res = save_object(fp2, op, SAVE_FLAG_SAVE_UNPAID|SAVE_FLAG_NO_REMOVE);
760 count++ ;
761 } else if (flag == 0
762 || (flag == SAVE_FLAG_NO_REMOVE && (!QUERY_FLAG(op, FLAG_OBJ_ORIGINAL) && !QUERY_FLAG(op, FLAG_UNPAID)))) {
763 res = save_object(fp, op, SAVE_FLAG_SAVE_UNPAID|SAVE_FLAG_NO_REMOVE);
764 count++;
765 }
766
767 if (res != 0)
768 return res;
769 } FOR_MAP_FINISH(); /* for this space */
770 } /* for this j */
771
772 PROFILE_END(diff,
773 LOG(llevDebug, "save_objects on %s took %ld us (%u objects = %f us each)\n", m->path, diff, count, (double)diff/count));
774 return 0;
775 }
776
777 /**
778 * Allocates, initialises, and returns a pointer to a mapstruct.
779 * Modified to no longer take a path option which was not being
780 * used anyways. MSW 2001-07-01
781 *
782 * @return
783 * new structure.
784 *
785 * @note
786 * will never return NULL, but call fatal() if memory error.
787 */
788 mapstruct *get_linked_map(void) {
789 mapstruct *map = (mapstruct *)calloc(1, sizeof(mapstruct));
790 /* mapstruct *mp;*/
791
792 if (map == NULL)
793 fatal(OUT_OF_MEMORY);
794 /*
795 * Nothing in the code appears to require we add new maps to the end of the list.
796 * Why not just add them to the front instead? Its faster.
797 *
798 * SilverNexus 2016-05-18
799 *
800 for (mp = first_map; mp != NULL && mp->next != NULL; mp = mp->next)
801 ;
802 if (mp == NULL)
803 first_map = map;
804 else
805 mp->next = map;
806 */
807 map->next = first_map;
808 first_map = map;
809
810 map->in_memory = MAP_SWAPPED;
811 /* The maps used to pick up default x and y values from the
812 * map archetype. Mimic that behaviour.
813 */
814 MAP_WIDTH(map) = 16;
815 MAP_HEIGHT(map) = 16;
816 MAP_RESET_TIMEOUT(map) = 0;
817 MAP_TIMEOUT(map) = 300;
818 MAP_ENTER_X(map) = 0;
819 MAP_ENTER_Y(map) = 0;
820 map->last_reset_time = 0;
821 return map;
822 }
823
824 /** Calculate map size without intermediate sign extension. */
825 uint32_t map_size(mapstruct *m) {
826 return (uint32_t)m->width * (uint32_t)m->height;
827 }
828
829 /**
830 * This basically allocates the dynamic array of spaces for the
831 * map.
832 *
833 * @param m
834 * map to check.
835 *
836 * @note
837 * will never fail, since it calls fatal() if memory allocation failure.
838 */
839 static void allocate_map(mapstruct *m) {
840 m->in_memory = MAP_IN_MEMORY;
841 /* Log this condition and free the storage. We could I suppose
842 * realloc, but if the caller is presuming the data will be intact,
843 * that is their poor assumption.
844 */
845 if (m->spaces) {
846 LOG(llevError, "allocate_map called with already allocated map (%s)\n", m->path);
847 free(m->spaces);
848 }
849
850 m->spaces = calloc(map_size(m), sizeof(MapSpace));
851
852 if (m->spaces == NULL)
853 fatal(OUT_OF_MEMORY);
854 }
855
856 /**
857 * Creates and returns a map of the specific size. Used
858 * in random map code and the editor.
859 *
860 * @param sizex
861 * @param sizey
862 * map size.
863 * @return
864 * new map.
865 *
866 * @note
867 * will never return NULL, as get_linked_map() never fails.
868 */
869 mapstruct *get_empty_map(int sizex, int sizey) {
870 mapstruct *m = get_linked_map();
871 m->width = sizex;
872 m->height = sizey;
873 m->in_memory = MAP_SWAPPED;
874 allocate_map(m);
875 return m;
876 }
877
878 /**
879 * Takes a string from a map definition and outputs a pointer to the array of shopitems
880 * corresponding to that string. Memory is allocated for this, it must be freed
881 * at a later date.
882 * Called by parse_map_headers() below.
883 *
884 * @param input_string
885 * shop item line.
886 * @param map
887 * map for which to parse the string, in case of warning.
888 * @return
889 * new array that should be freed by the caller.
890 */
891 static shopitems *parse_shop_string(const char *input_string, const mapstruct *map) {
892 char *shop_string, *p, *q, *next_semicolon, *next_colon;
893 shopitems *items = NULL;
894 int i = 0, number_of_entries = 0;
895 const typedata *current_type;
896
897 shop_string = strdup_local(input_string);
898 p = shop_string;
899 LOG(llevDebug, "parsing %s\n", input_string);
900 /* first we'll count the entries, we'll need that for allocating the array shortly */
901 while (p) {
902 p = strchr(p, ';');
903 number_of_entries++;
904 if (p)
905 p++;
906 }
907 p = shop_string;
908 strip_endline(p);
909 items = CALLOC(number_of_entries+1, sizeof(shopitems));
910 /*
911 * The memset would always set at least one byte to zero,
912 * so a failed calloc would have segfaulted the program.
913 * Instead, check for a null and fail more gracefully.
914 */
915 if (!items)
916 fatal(OUT_OF_MEMORY);
917 /*
918 * calloc() already sets each byte to zero already
919 *
920 memset(items, 0, (sizeof(shopitems)*number_of_entries+1));
921 */
922 for (i = 0; i < number_of_entries; i++) {
923 if (!p) {
924 LOG(llevError, "parse_shop_string: I seem to have run out of string, that shouldn't happen.\n");
925 break;
926 }
927 next_semicolon = strchr(p, ';');
928 next_colon = strchr(p, ':');
929 /* if there is a stregth specified, figure out what it is, we'll need it soon. */
930 if (next_colon && (!next_semicolon || next_colon < next_semicolon))
931 items[i].strength = atoi(strchr(p, ':')+1);
932
933 if (isdigit(*p) || *p == '*') {
934 items[i].typenum = *p == '*' ? -1 : atoi(p);
935 current_type = get_typedata(items[i].typenum);
936 if (current_type) {
937 items[i].name = current_type->name;
938 items[i].name_pl = current_type->name_pl;
939 }
940 } else { /*we have a named type, let's figure out what it is */
941 q = strpbrk(p, ";:");
942 if (q)
943 *q = '\0';
944
945 current_type = get_typedata_by_name(p);
946 if (current_type) {
947 items[i].name = current_type->name;
948 items[i].typenum = current_type->number;
949 items[i].name_pl = current_type->name_pl;
950 } else {
951 /* oh uh, something's wrong, let's free up this one, and try
952 * the next entry while we're at it, better print a warning */
953 LOG(llevError, "invalid type %s defined in shopitems for %s in string %s\n", p, map->name, input_string);
954 }
955 }
956 items[i].index = number_of_entries;
957 if (next_semicolon)
958 p = ++next_semicolon;
959 else
960 p = NULL;
961 }
962 free(shop_string);
963 return items;
964 }
965
966 /**
967 * Opposite of parse string(), this puts the string that was originally fed in to
968 * the map (or something equivilent) into output_string.
969 *
970 * @param m
971 * map we're considering.
972 * @param output_string
973 * string to write to.
974 * @param size
975 * output_string's length.
976 */
977 static void print_shop_string(mapstruct *m, char *output_string, int size) {
978 int i;
979 char tmp[MAX_BUF];
980
981 output_string[0] = '\0';
982 for (i = 0; i < m->shopitems[0].index; i++) {
983 if (m->shopitems[i].typenum != -1) {
984 if (m->shopitems[i].strength) {
985 snprintf(tmp, sizeof(tmp), "%s:%d;", m->shopitems[i].name, m->shopitems[i].strength);
986 } else
987 snprintf(tmp, sizeof(tmp), "%s;", m->shopitems[i].name);
988 } else {
989 if (m->shopitems[i].strength) {
990 snprintf(tmp, sizeof(tmp), "*:%d;", m->shopitems[i].strength);
991 } else
992 snprintf(tmp, sizeof(tmp), "*;");
993 }
994 snprintf(output_string+strlen(output_string), size-strlen(output_string), "%s", tmp);
995 }
996
997 /* erase final ; else parsing back will lead to issues */
998 if (strlen(output_string) > 0) {
999 output_string[strlen(output_string) - 1] = '\0';
1000 }
1001 }
1002
1003 /**
1004 * This loads the header information of the map. The header
1005 * contains things like difficulty, size, timeout, etc.
1006 * this used to be stored in the map object, but with the
1007 * addition of tiling, fields beyond that easily named in an
1008 * object structure were needed, so it just made sense to
1009 * put all the stuff in the map object so that names actually make
1010 * sense.
1011 * This could be done in lex (like the object loader), but I think
1012 * currently, there are few enough fields this is not a big deal.
1013 * MSW 2001-07-01
1014 *
1015 * @param fp
1016 * file to read from.
1017 * @param m
1018 * map being read.
1019 * @return
1020 * 0 on success, 1 on failure.
1021 */
1022 static int load_map_header(FILE *fp, mapstruct *m) {
1023 char buf[HUGE_BUF], *key = NULL, *value;
1024
1025 m->width = m->height = 0;
1026 while (fgets(buf, sizeof(buf), fp) != NULL) {
1027 char *p;
1028
1029 p = strchr(buf, '\n');
1030 if (p == NULL) {
1031 LOG(llevError, "Error loading map header - did not find a newline - perhaps file is truncated? Buf=%s\n", buf);
1032 return 1;
1033 }
1034 *p = '\0';
1035
1036 key = buf;
1037 while (isspace(*key))
1038 key++;
1039 if (*key == 0)
1040 continue; /* empty line */
1041 value = strchr(key, ' ');
1042 if (value) {
1043 *value = 0;
1044 value++;
1045 while (isspace(*value)) {
1046 value++;
1047 if (*value == '\0') {
1048 /* Nothing but spaces. */
1049 value = NULL;
1050 break;
1051 }
1052 }
1053 }
1054
1055 /* key is the field name, value is what it should be set
1056 * to. We've already done the work to null terminate key,
1057 * and strip off any leading spaces for both of these.
1058 * We have not touched the newline at the end of the line -
1059 * these are needed for some values. the end pointer
1060 * points to the first of the newlines.
1061 * value could be NULL! It would be easy enough to just point
1062 * this to "" to prevent cores, but that would let more errors slide
1063 * through.
1064 *
1065 * First check for entries that do not use the value parameter, then
1066 * validate that value is given and check for the remaining entries
1067 * that use the parameter.
1068 */
1069
1070 if (!strcmp(key, "msg")) {
1071 char msgbuf[HUGE_BUF];
1072 int msgpos = 0;
1073
1074 while (fgets(buf, sizeof(buf), fp) != NULL) {
1075 if (!strcmp(buf, "endmsg\n"))
1076 break;
1077 else {
1078 snprintf(msgbuf+msgpos, sizeof(msgbuf)-msgpos, "%s", buf);
1079 msgpos += strlen(buf);
1080 }
1081 }
1082 /* There are lots of maps that have empty messages (eg, msg/endmsg
1083 * with nothing between). There is no reason in those cases to
1084 * keep the empty message. Also, msgbuf contains garbage data
1085 * when msgpos is zero, so copying it results in crashes
1086 */
1087 if (msgpos != 0) {
1088 /* When loading eg an overlay, message is already set, so free() current one. */
1089 free(m->msg);
1090 m->msg = strdup_local(msgbuf);
1091 }
1092 } else if (!strcmp(key, "maplore")) {
1093 char maplorebuf[HUGE_BUF];
1094 size_t maplorepos = 0;
1095
1096 while (fgets(buf, HUGE_BUF-1, fp) != NULL) {
1097 if (!strcmp(buf, "endmaplore\n"))
1098 break;
1099 else {
1100 if (maplorepos >= sizeof(maplorebuf)) {
1101 LOG(llevError, "Map lore exceeds buffer length\n");
1102 return 1;
1103 }
1104 snprintf(maplorebuf+maplorepos, sizeof(maplorebuf)-maplorepos, "%s", buf);
1105 maplorepos += strlen(buf);
1106 }
1107 }
1108 if (maplorepos != 0)
1109 m->maplore = strdup_local(maplorebuf);
1110 } else if (!strcmp(key, "end")) {
1111 break;
1112 } else if (value == NULL) {
1113 LOG(llevError, "Got '%s' line without parameter in map header\n", key);
1114 } else if (!strcmp(key, "arch")) {
1115 /* This is an oddity, but not something we care about much. */
1116 if (strcmp(value, "map")) {
1117 LOG(llevError, "load_map_header: expected 'arch map': check line endings?\n");
1118 return 1;
1119 }
1120 } else if (!strcmp(key, "name")) {
1121 /* When loading eg an overlay, the name is already set, so free() current one. */
1122 free(m->name);
1123 m->name = strdup_local(value);
1124 /* first strcmp value on these are old names supported
1125 * for compatibility reasons. The new values (second) are
1126 * what really should be used.
1127 */
1128 } else if (!strcmp(key, "enter_x")) {
1129 m->enter_x = atoi(value);
1130 } else if (!strcmp(key, "enter_y")) {
1131 m->enter_y = atoi(value);
1132 } else if (!strcmp(key, "width")) {
1133 m->width = atoi(value);
1134 } else if (!strcmp(key, "height")) {
1135 m->height = atoi(value);
1136 } else if (!strcmp(key, "reset_timeout")) {
1137 m->reset_timeout = atoi(value);
1138 } else if (!strcmp(key, "swap_time")) {
1139 m->timeout = atoi(value);
1140 } else if (!strcmp(key, "difficulty")) {
1141 m->difficulty = atoi(value);
1142 } else if (!strcmp(key, "darkness")) {
1143 m->darkness = atoi(value);
1144 } else if (!strcmp(key, "fixed_resettime")) {
1145 m->fixed_resettime = atoi(value);
1146 } else if (!strcmp(key, "unique")) {
1147 m->unique = atoi(value);
1148 } else if (!strcmp(key, "template")) {
1149 m->is_template = atoi(value);
1150 } else if (!strcmp(key, "region")) {
1151 m->region = get_region_by_name(value);
1152 } else if (!strcmp(key, "shopitems")) {
1153 m->shopitems = parse_shop_string(value, m);
1154 } else if (!strcmp(key, "shopgreed")) {
1155 m->shopgreed = atof(value);
1156 } else if (!strcmp(key, "shopmin")) {
1157 m->shopmin = atol(value);
1158 } else if (!strcmp(key, "shopmax")) {
1159 m->shopmax = atol(value);
1160 } else if (!strcmp(key, "shoprace")) {
1161 m->shoprace = strdup_local(value);
1162 } else if (!strcmp(key, "outdoor")) {
1163 m->outdoor = atoi(value);
1164 } else if (!strcmp(key, "nosmooth")) {
1165 m->nosmooth = atoi(value);
1166 } else if (!strcmp(key, "first_load")) {
1167 m->last_reset_time = atoi(value);
1168 } else if (!strncmp(key, "tile_path_", 10)) {
1169 int tile = atoi(key+10);
1170
1171 if (tile < 1 || tile > 4) {
1172 LOG(llevError, "load_map_header: tile location %d out of bounds (%s)\n", tile, m->path);
1173 } else {
1174 if (m->tile_path[tile-1]) {
1175 LOG(llevError, "load_map_header: tile location %d duplicated (%s)\n", tile, m->path);
1176 free(m->tile_path[tile-1]);
1177 }
1178 m->tile_path[tile-1] = strdup_local(value);
1179 } /* end if tile direction (in)valid */
1180 } else if (!strcmp(key, "background_music")) {
1181 m->background_music = strdup_local(value);
1182 } else {
1183 LOG(llevError, "Got unknown value in map header: %s %s\n", key, value);
1184 }
1185 }
1186 if ((m->width == 0) || (m->height == 0)) {
1187 LOG(llevError, "Map width or height not specified\n");
1188 return 1;
1189 }
1190 if (!key || strcmp(key, "end")) {
1191 LOG(llevError, "Got premature eof on map header!\n");
1192 return 1;
1193 }
1194 return 0;
1195 }
1196
1197 /**
1198 * Opens the file "filename" and reads information about the map
1199 * from the given file, and stores it in a newly allocated
1200 * mapstruct. A pointer to this structure is returned, or NULL on failure.
1201 * flags correspond to those in map.h. Main ones used are
1202 * ::MAP_PLAYER_UNIQUE, in which case we don't do any name changes, and
1203 *
1204 * @param map Map path
1205 * @param flags Additional options for loading the map:
1206 * \li ::MAP_PLAYER_UNIQUE: Load from a player-specific directory
1207 * \li ::MAP_OVERLAY: map is an overlay
1208 * \li ::MAP_STYLE: style map - don't add active objects, don't add to server managed map list.
1209 * @return
1210 * loaded map, or NULL if failure.
1211 */
1212 mapstruct *mapfile_load(const char *map, int flags) {
1213 FILE *fp;
1214 mapstruct *m;
1215 char pathname[MAX_BUF];
1216
1217 PROFILE_BEGIN();
1218
1219 if (flags&MAP_PLAYER_UNIQUE) {
1220 snprintf(pathname, sizeof(pathname), "%s/%s/%s", settings.localdir, settings.playerdir, map+1);
1221 }
1222 else if (flags&MAP_OVERLAY)
1223 create_overlay_pathname(map, pathname, MAX_BUF);
1224 else
1225 create_pathname(map, pathname, MAX_BUF);
1226
1227 if ((fp = fopen(pathname, "r")) == NULL) {
1228 LOG((flags&MAP_PLAYER_UNIQUE) ? llevDebug : llevError,
1229 "Can't open %s: %s\n", pathname, strerror(errno));
1230 return (NULL);
1231 }
1232
1233 m = get_linked_map();
1234
1235 safe_strncpy(m->path, map, HUGE_BUF);
1236 if (load_map_header(fp, m)) {
1237 LOG(llevError, "Error loading map header for %s, flags=%d\n", map, flags);
1238 delete_map(m);
1239 fclose(fp);
1240 return NULL;
1241 }
1242
1243 allocate_map(m);
1244
1245 m->in_memory = MAP_LOADING;
1246 load_objects(m, fp, flags & MAP_STYLE);
1247 fclose(fp);
1248 m->in_memory = MAP_IN_MEMORY;
1249 if (!MAP_DIFFICULTY(m))
1250 MAP_DIFFICULTY(m) = calculate_difficulty(m);
1251 set_map_reset_time(m);
1252
1253 /* In case other objects press some buttons down */
1254 update_buttons(m);
1255
1256 /* Handle for map load event */
1257 execute_global_event(EVENT_MAPLOAD, m);
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
1268 /**
1269 * Loads a map, which has been loaded earlier, from file.
1270 *
1271 * @param m
1272 * map we want to reload.
1273 * @return
1274 * 0 if success, non zero if failure, in which case error was LOG'ed.
1275 */
1276 static int load_temporary_map(mapstruct *m) {
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
1303 /**
1304 * Loads an overlay for a map, which has been loaded earlier, from file.
1305 * @param filename
1306 * filename for overlay.
1307 * @param m
1308 * map we want to load.
1309 * @return
1310 * 0 on success, non zero in case of error, which is LOG'ed.
1311 */
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
1341 /**
1342 * This goes through map 'm' and removes any unique items on the map.
1343 *
1344 * @param m
1345 * map to check.
1346 */
1347 static void delete_unique_items(mapstruct *m) {
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) {
1354 if (QUERY_FLAG(op, FLAG_IS_FLOOR) && QUERY_FLAG(op, FLAG_UNIQUE))
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);
1361 object_free_drop_inventory(op);
1362 }
1363 } FOR_MAP_FINISH();
1364 }
1365 }
1366
1367 /**
1368 * Loads unique objects from file(s) into the map which is in memory
1369 * @param m
1370 * map to load unique items into.
1371 */
1372 static void load_unique_objects(mapstruct *m) {
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
1404 /**
1405 * Saves a map to file. If flag is SAVE_MODE_INPLACE, it is saved into the same
1406 * file it was (originally) loaded from. Otherwise a temporary
1407 * filename will be genarated, and the file will be stored there.
1408 * The temporary filename will be stored in the mapstructure.
1409 * If the map is unique, we also save to the filename in the map
1410 * (this should have been updated when first loaded)
1411 *
1412 * @param m
1413 * map to save.
1414 * @param flag
1415 * One of @ref SAVE_MODE_xxx "SAVE_MODE_xxx" values.
1416 * @return
1417 * one of @ref SAVE_ERROR_xxx "SAVE_ERROR_xxx" values.
1418 */
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
1617 /**
1618 * Remove and free all objects in the inventory of the given object.
1619 *
1620 * @param op
1621 * object to clean.
1622 *
1623 * @todo
1624 * move to common/object.c ?
1625 */
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);
1632 object_free_drop_inventory(tmp);
1633 } FOR_INV_FINISH();
1634 }
1635
1636 /**
1637 * Remove and free all objects in the given map.
1638 *
1639 * @param m
1640 * map to free.
1641 */
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);
1664 object_free_drop_inventory(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(llevDebug, "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
1681 /**
1682 * Frees everything allocated by the given mapstructure.
1683 * Don't free tmpname - our caller is left to do that.
1684 * Mapstructure itself is not freed.
1685 *
1686 * @param m
1687 * map to free.
1688 */
1689 void free_map(mapstruct *m) {
1690 int i;
1691
1692 if (!m->in_memory) {
1693 LOG(llevError, "Trying to free freed map.\n");
1694 return;
1695 }
1696
1697 /* Handle for plugin map unload event. */
1698 execute_global_event(EVENT_MAPUNLOAD, m);
1699
1700 if (m->spaces)
1701 free_all_objects(m);
1702 if (m->name)
1703 FREE_AND_CLEAR(m->name);
1704 if (m->spaces)
1705 FREE_AND_CLEAR(m->spaces);
1706 if (m->msg)
1707 FREE_AND_CLEAR(m->msg);
1708 if (m->maplore)
1709 FREE_AND_CLEAR(m->maplore);
1710 if (m->shopitems)
1711 FREE_AND_CLEAR(m->shopitems);
1712 if (m->shoprace)
1713 FREE_AND_CLEAR(m->shoprace);
1714 if (m->background_music)
1715 FREE_AND_CLEAR(m->background_music);
1716 if (m->buttons)
1717 free_objectlinkpt(m->buttons);
1718 m->buttons = NULL;
1719 for (i = 0; i < 4; i++) {
1720 if (m->tile_path[i])
1721 FREE_AND_CLEAR(m->tile_path[i]);
1722 m->tile_map[i] = NULL;
1723 }
1724 m->in_memory = MAP_SWAPPED;
1725 }
1726
1727 /**
1728 * Frees the map, including the mapstruct.
1729 *
1730 * This deletes all the data on the map (freeing pointers)
1731 * and then removes this map from the global linked list of maps.
1732 *
1733 * @param m
1734 * pointer to mapstruct, if NULL no action. Will be invalid after this function.
1735 */
1736 void delete_map(mapstruct *m) {
1737 mapstruct *tmp, *last;
1738 int i;
1739
1740 if (!m)
1741 return;
1742 if (m->in_memory == MAP_IN_MEMORY) {
1743 /* change to MAP_SAVING, even though we are not,
1744 * so that object_remove() doesn't do as much work.
1745 */
1746 m->in_memory = MAP_SAVING;
1747 free_map(m);
1748 }
1749 /* move this out of free_map, since tmpname can still be needed if
1750 * the map is swapped out.
1751 */
1752 free(m->tmpname);
1753 m->tmpname = NULL;
1754 last = NULL;
1755 /* We need to look through all the maps and see if any maps
1756 * are pointing at this one for tiling information. Since
1757 * tiling can be assymetric, we just can not look to see which
1758 * maps this map tiles with and clears those.
1759 */
1760 for (tmp = first_map; tmp != NULL; tmp = tmp->next) {
1761 if (tmp->next == m)
1762 last = tmp;
1763
1764 /* This should hopefully get unrolled on a decent compiler */
1765 for (i = 0; i < 4; i++)
1766 if (tmp->tile_map[i] == m)
1767 tmp->tile_map[i] = NULL;
1768 }
1769
1770 /* If last is null, then this should be the first map in the list */
1771 if (!last) {
1772 if (m == first_map)
1773 first_map = m->next;
1774 else
1775 /* m->path is a static char, so should hopefully still have
1776 * some useful data in it.
1777 */
1778 LOG(llevError, "delete_map: Unable to find map %s in list\n", m->path);
1779 } else
1780 last->next = m->next;
1781
1782 free(m);
1783 }
1784
1785 /**
1786 * Makes sure the given map is loaded and swapped in.
1787 * @param name
1788 * path name of the map.
1789 * @param flags
1790 * @li 0x1 (::MAP_FLUSH): flush the map - always load from the map directory,
1791 * and don't do unique items or the like.
1792 * @li 0x2 (::MAP_PLAYER_UNIQUE) - this is a unique map for each player.
1793 * dont do any more name translation on it.
1794 *
1795 * @return
1796 * pointer to the given map, NULL on failure.
1797 */
1798 mapstruct *ready_map_name(const char *name, int flags) {
1799 mapstruct *m;
1800
1801 if (!name)
1802 return (NULL);
1803
1804 /* Have we been at this level before? */
1805 m = has_been_loaded(name);
1806
1807 /* Map is good to go, so just return it */
1808 if (m && (m->in_memory == MAP_LOADING || m->in_memory == MAP_IN_MEMORY)) {
1809 return m;
1810 }
1811
1812 /* Rewrite old paths starting with LOCALDIR/PLAYERDIR to new '~' paths. */
1813 char buf[MAX_BUF], buf2[MAX_BUF];
1814 snprintf(buf, sizeof(buf), "%s/%s", settings.localdir, settings.playerdir);
1815 if (strncmp(name, buf, strlen(buf)) == 0) {
1816 snprintf(buf2, sizeof(buf2), "~%s", name+strlen(buf)+1);
1817 name = buf2;
1818 }
1819
1820 /* Paths starting with '~' are unique. */
1821 if (name[0] == '~') {
1822 flags |= MAP_PLAYER_UNIQUE;
1823 }
1824
1825 /* unique maps always get loaded from their original location, and never
1826 * a temp location. Likewise, if map_flush is set, or we have never loaded
1827 * this map, load it now. I removed the reset checking from here -
1828 * it seems the probability of a player trying to enter a map that should
1829 * reset but hasn't yet is quite low, and removing that makes this function
1830 * a bit cleaner (and players probably shouldn't rely on exact timing for
1831 * resets in any case - if they really care, they should use the 'maps command.
1832 */
1833 if ((flags&(MAP_FLUSH|MAP_PLAYER_UNIQUE)) || !m) {
1834 /* first visit or time to reset */
1835 if (m) {
1836 clean_tmp_map(m); /* Doesn't make much difference */
1837 delete_map(m);
1838 }
1839
1840 m = mapfile_load(name, (flags&MAP_PLAYER_UNIQUE));
1841 if (m == NULL) return NULL;
1842
1843 /* If a player unique map, no extra unique object file to load.
1844 * if from the editor, likewise.
1845 */
1846 if (!(flags&(MAP_FLUSH|MAP_PLAYER_UNIQUE)))
1847 load_unique_objects(m);
1848
1849 if (!(flags&(MAP_FLUSH|MAP_PLAYER_UNIQUE|MAP_OVERLAY))) {
1850 if (load_overlay_map(name, m) != 0) {
1851 delete_map(m);
1852 m = mapfile_load(name, 0);
1853 if (m == NULL) {
1854 /* Really, this map is bad :( */
1855 return NULL;
1856 }
1857 }
1858 }
1859 } else {
1860 /* If in this loop, we found a temporary map, so load it up. */
1861
1862 if (load_temporary_map(m) != 0) {
1863 /*
1864 * There was a failure loading the temporary map, fall back to original one.
1865 * load_temporary_map() already logged the error.
1866 */
1867 delete_map(m);
1868 m = mapfile_load(name, 0);
1869 if (m == NULL) {
1870 /* Really, this map is bad :( */
1871 return NULL;
1872 }
1873 }
1874 load_unique_objects(m);
1875
1876 clean_tmp_map(m);
1877 m->in_memory = MAP_IN_MEMORY;
1878 /* tempnam() on sun systems (probably others) uses malloc
1879 * to allocated space for the string. Free it here.
1880 * In some cases, load_temporary_map above won't find the
1881 * temporary map, and so has reloaded a new map. If that
1882 * is the case, tmpname is now null
1883 */
1884 free(m->tmpname);
1885 m->tmpname = NULL;
1886 /* It's going to be saved anew anyway */
1887 }
1888
1889 /* Below here is stuff common to both first time loaded maps and
1890 * temp maps.
1891 */
1892
1893 decay_objects(m); /* start the decay */
1894
1895 if (m->outdoor)
1896 set_darkness_map(m);
1897
1898 if (!(flags&(MAP_FLUSH))) {
1899 if (m->last_reset_time == 0) {
1900 m->last_reset_time = seconds();
1901 }
1902 }
1903 return m;
1904 }
1905
1906 /**
1907 * This routine is supposed to find out the difficulty of the map.
1908 * Difficulty does not have a lot to do with character level,
1909 * but does have a lot to do with treasure on the map.
1910 *
1911 * Difficulty can now be set by the map creature. If the value stored
1912 * in the map is zero, then use this routine. Maps should really
1913 * have a difficulty set than using this function - human calculation
1914 * is much better than this functions guesswork.
1915 *
1916 * @param m
1917 * map for which to compute difficulty.
1918 * @return
1919 * difficulty of the map.
1920 */
1921 int calculate_difficulty(mapstruct *m) {
1922 archetype *at;
1923 int x, y;
1924 int diff = 0;
1925 int i;
1926 int64_t exp_pr_sq, total_exp = 0;
1927
1928 if (MAP_DIFFICULTY(m)) {
1929 return MAP_DIFFICULTY(m);
1930 }
1931
1932 for (x = 0; x < MAP_WIDTH(m); x++)
1933 for (y = 0; y < MAP_HEIGHT(m); y++)
1934 FOR_MAP_PREPARE(m, x, y, op) {
1935 if (QUERY_FLAG(op, FLAG_MONSTER))
1936 total_exp += op->stats.exp;
1937 if (QUERY_FLAG(op, FLAG_GENERATOR)) {
1938 total_exp += op->stats.exp;
1939 at = get_archetype_by_type_subtype(GENERATE_TYPE(op), -1);
1940 if (at != NULL)
1941 total_exp += at->clone.stats.exp*8;
1942 }
1943 } FOR_MAP_FINISH();
1944
1945 exp_pr_sq = ((double)1000*total_exp)/(MAP_WIDTH(m)*MAP_HEIGHT(m)+1);
1946 diff = 20;
1947 for (i = 1; i < 20; i++)
1948 if (exp_pr_sq <= level_exp(i, 1.0)) {
1949 diff = i;
1950 break;
1951 }
1952
1953 return diff;
1954 }
1955
1956 /**
1957 * Removse the temporary file used by the map.
1958 *
1959 * @param m
1960 * map, which mustn't be NULL but can have no temporary file set.
1961 */
1962 void clean_tmp_map(mapstruct *m) {
1963 if (m->tmpname == NULL)
1964 return;
1965 (void)unlink(m->tmpname);
1966 }
1967
1968 /**
1969 * Frees all allocated maps.
1970 */
1971 void free_all_maps(void) {
1972 int real_maps = 0;
1973
1974 while (first_map) {
1975 /* I think some of the callers above before it gets here set this to be
1976 * saving, but we still want to free this data
1977 */
1978 if (first_map->in_memory == MAP_SAVING)
1979 first_map->in_memory = MAP_IN_MEMORY;
1980 delete_map(first_map);
1981 real_maps++;
1982 }
1983 LOG(llevDebug, "free_all_maps: Freed %d maps\n", real_maps);
1984 }
1985
1986 /**
1987 * Used to change map light level (darkness)
1988 * up or down. It should now be possible to change a value by more than 1.
1989 *
1990 * Move this from los.c to map.c since this is more related
1991 * to maps than los.
1992 * postive values make it darker, negative make it brighter
1993 *
1994 * Will inform players on the map.
1995 *
1996 * @param m
1997 * map to change.
1998 * @param change
1999 * delta of light.
2000 * @return
2001 * TRUE if light changed, FALSE else.
2002 */
2003 int change_map_light(mapstruct *m, int change) {
2004 int new_level = m->darkness+change;
2005
2006 /* Nothing to do */
2007 if (!change
2008 || (new_level <= 0 && m->darkness == 0)
2009 || (new_level >= MAX_DARKNESS && m->darkness >= MAX_DARKNESS)) {
2010 return 0;
2011 }
2012
2013 /* inform all players on the map */
2014 if (change > 0)
2015 ext_info_map(NDI_BLACK, m, MSG_TYPE_MISC, MSG_SUBTYPE_NONE, "It becomes darker.");
2016 else
2017 ext_info_map(NDI_BLACK, m, MSG_TYPE_MISC, MSG_SUBTYPE_NONE, "It becomes brighter.");
2018
2019 /* Do extra checking. since m->darkness is a unsigned value,
2020 * we need to be extra careful about negative values.
2021 * In general, the checks below are only needed if change
2022 * is not +/-1
2023 */
2024 if (new_level < 0)
2025 m->darkness = 0;
2026 else if (new_level >= MAX_DARKNESS)
2027 m->darkness = MAX_DARKNESS;
2028 else
2029 m->darkness = new_level;
2030
2031 /* All clients need to get re-updated for the change */
2032 update_all_map_los(m);
2033 return 1;
2034 }
2035
2036 /**
2037 * This function is used for things that can have multiple
2038 * layers - NO_PICK, ITEM, LIVING, FLYING.
2039 * Basically, we want to store in the empty spot,
2040 * and if both full, store highest visiblity objects.
2041 * Since update_position() goes from bottom to top order,
2042 * if the new object is equal to existing we take the new
2043 * object since it is higher in the stack.
2044 * @param low_layer
2045 * lower bounds to check (inclusive).
2046 * @param high_layer
2047 * upper bounds to check (inclusive).
2048 * @param ob
2049 * object to add to the layer.
2050 * @param layers
2051 * layers to change.
2052 * @param honor_visibility
2053 * if it is set to 0,then we do a pure stacking logic - this is used
2054 * for the no pick layer, since stacking ordering there
2055 * is basically fixed - don't want to re-order walls,
2056 * pentagrams, etc.
2057 */
2058 static inline void add_face_layer(int low_layer, int high_layer, object *ob, object *layers[], int honor_visibility) {
2059 int l, l1;
2060 object *tmp;
2061
2062 for (l = low_layer; l <= high_layer; l++) {
2063 if (!layers[l]) {
2064 /* found an empty spot. now, we want to make sure
2065 * highest visibility at top, etc.
2066 */
2067 layers[l] = ob;
2068 if (!honor_visibility)
2069 return;
2070
2071 /* This is basically a mini bubble sort. Only swap
2072 * position if the lower face has greater (not equal)
2073 * visibility - map stacking is secondary consideration here.
2074 */
2075 for (l1 = (l-1); l1 >= low_layer; l1--) {
2076 if (layers[l1]->face->visibility > layers[l1+1]->face->visibility) {
2077 tmp = layers[l1+1];
2078 layers[l1+1] = layers[l1];
2079 layers[l1] = tmp;
2080 }
2081 }
2082 /* Nothing more to do - face inserted */
2083 return;
2084 }
2085 }
2086 /* If we get here, all the layers have an object..
2087 */
2088 if (!honor_visibility) {
2089 /* Basically, in this case, it is pure stacking logic, so
2090 * new object goes on the top.
2091 */
2092 for (l = low_layer; l < high_layer; l++)
2093 layers[l] = layers[l+1];
2094 layers[high_layer] = ob;
2095 /* If this object doesn't have higher visibility than
2096 * the lowest object, no reason to go further.
2097 */
2098 } else if (ob->face->visibility >= layers[low_layer]->face->visibility) {
2099 /*
2100 * Start at the top (highest visibility) layer and work down.
2101 * once this face exceed that of the layer, push down those
2102 * other layers, and then replace the layer with our object.
2103 */
2104 for (l = high_layer; l >= low_layer; l--) {
2105 if (ob->face->visibility >= layers[l]->face->visibility) {
2106 for (l1 = low_layer; l1 < l; l1++)
2107 layers[l1] = layers[l1+1];
2108 layers[l] = ob;
2109 break;
2110 }
2111 }
2112 }
2113 }
2114
2115 /**
2116 * This function updates various attributes about a specific space
2117 * on the map (what it looks like, whether it blocks magic,
2118 * has a living creatures, prevents people from passing
2119 * through, etc)
2120 *
2121 * @param m
2122 * map considered
2123 * @param x
2124 * @param y
2125 * coordinates to update
2126 */
2127 void update_position(mapstruct *m, int x, int y) {
2128 object *player = NULL;
2129 uint8_t flags = 0, oldflags, light = 0;
2130 object *layers[MAP_LAYERS];
2131
2132 MoveType move_block = 0, move_slow = 0, move_on = 0, move_off = 0, move_allow = 0;
2133
2134 oldflags = GET_MAP_FLAGS(m, x, y);
2135 if (!(oldflags&P_NEED_UPDATE)) {
2136 LOG(llevDebug, "update_position called with P_NEED_UPDATE not set: %s (%d, %d)\n", m->path, x, y);
2137 return;
2138 }
2139
2140 memset(layers, 0, MAP_LAYERS*sizeof(object *));
2141
2142 FOR_MAP_PREPARE(m, x, y, tmp) {
2143 /* DMs just don't do anything when hidden, including no light. */
2144 if (QUERY_FLAG(tmp, FLAG_WIZ) && tmp->contr->hidden)
2145 continue;
2146
2147 if (tmp->type == PLAYER)
2148 player = tmp;
2149
2150 /* This could be made additive I guess (two lights better than
2151 * one). But if so, it shouldn't be a simple additive - 2
2152 * light bulbs do not illuminate twice as far as once since
2153 * it is a dissipation factor that is squared (or is it cubed?)
2154 */
2155 if (tmp->glow_radius > light)
2156 light = tmp->glow_radius;
2157
2158 /* if this object is visible and not a blank face,
2159 * update the objects that show how this space
2160 * looks.
2161 */
2162 if (!tmp->invisible && tmp->face != blank_face) {
2163 if (tmp->map_layer) {
2164 add_face_layer(tmp->map_layer, map_layer_info[tmp->map_layer].high_layer,
2165 tmp, layers, map_layer_info[tmp->map_layer].honor_visibility);
2166 } else if (tmp->move_type&MOVE_FLYING) {
2167 add_face_layer(MAP_LAYER_FLY1, MAP_LAYER_FLY2, tmp, layers, 1);
2168 } else if ((tmp->type == PLAYER || QUERY_FLAG(tmp, FLAG_MONSTER))) {
2169 add_face_layer(MAP_LAYER_LIVING1, MAP_LAYER_LIVING2, tmp, layers, 1);
2170 } else if (QUERY_FLAG(tmp, FLAG_IS_FLOOR)) {
2171 layers[MAP_LAYER_FLOOR] = tmp;
2172 /* floors hide everything else */
2173 memset(layers+1, 0, (MAP_LAYERS-1)*sizeof(object *));
2174 /* Check for FLAG_SEE_ANYWHERE is removed - objects
2175 * with that flag should just have a high visibility
2176 * set - we shouldn't need special code here.
2177 */
2178 } else if (QUERY_FLAG(tmp, FLAG_NO_PICK)) {
2179 add_face_layer(MAP_LAYER_NO_PICK1, MAP_LAYER_NO_PICK2, tmp, layers, 0);
2180 } else {
2181 add_face_layer(MAP_LAYER_ITEM1, MAP_LAYER_ITEM3, tmp, layers, 1);
2182 }
2183 }
2184 if (tmp == tmp->above) {
2185 LOG(llevError, "Error in structure of map\n");
2186 exit(-1);
2187 }
2188
2189 move_slow |= tmp->move_slow;
2190 move_block |= tmp->move_block;
2191 move_on |= tmp->move_on;
2192 move_off |= tmp->move_off;
2193 move_allow |= tmp->move_allow;
2194
2195 if (QUERY_FLAG(tmp, FLAG_ALIVE))
2196 flags |= P_IS_ALIVE;
2197 if (QUERY_FLAG(tmp, FLAG_NO_MAGIC))
2198 flags |= P_NO_MAGIC;
2199 if (QUERY_FLAG(tmp, FLAG_DAMNED))
2200 flags |= P_NO_CLERIC;
2201
2202 if (QUERY_FLAG(tmp, FLAG_BLOCKSVIEW))
2203 flags |= P_BLOCKSVIEW;
2204 } FOR_MAP_FINISH(); /* for stack of objects */
2205
2206 if (player)
2207 flags |= P_PLAYER;
2208
2209 /* we don't want to rely on this function to have accurate flags, but
2210 * since we're already doing the work, we calculate them here.
2211 * if they don't match, logic is broken someplace.
2212 */
2213 if (((oldflags&~(P_NEED_UPDATE|P_NO_ERROR)) != flags)
2214 && (!(oldflags&P_NO_ERROR))) {
2215 LOG(llevDebug, "update_position: updated flags do not match old flags: %s (x=%d,y=%d) %x != %x\n",
2216 m->path, x, y, (oldflags&~P_NEED_UPDATE), flags);
2217 }
2218
2219 SET_MAP_FLAGS(m, x, y, flags);
2220 SET_MAP_MOVE_BLOCK(m, x, y, move_block&~move_allow);
2221 SET_MAP_MOVE_ON(m, x, y, move_on);
2222 SET_MAP_MOVE_OFF(m, x, y, move_off);
2223 SET_MAP_MOVE_SLOW(m, x, y, move_slow);
2224 SET_MAP_LIGHT(m, x, y, light);
2225
2226 /* Note that player may be NULL here, which is fine - if no player, need
2227 * to clear any value that may be set.
2228 */
2229 SET_MAP_PLAYER(m, x, y, player);
2230
2231 /* Note it is intentional we copy everything, including NULL values. */
2232 memcpy(GET_MAP_FACE_OBJS(m, x, y), layers, sizeof(object *)*MAP_LAYERS);
2233 }
2234
2235 /**
2236 * Updates the map's timeout.
2237 *
2238 * @param map
2239 * map to update.
2240 */
2241 void set_map_reset_time(mapstruct *map) {
2242 int timeout;
2243
2244 timeout = MAP_RESET_TIMEOUT(map);
2245 if (timeout <= 0)
2246 timeout = MAP_DEFAULTRESET;
2247 if (timeout >= MAP_MAXRESET)
2248 timeout = MAP_MAXRESET;
2249 MAP_RESET_TIMEOUT(map) = timeout;
2250 MAP_WHEN_RESET(map) = seconds()+timeout;
2251 }
2252
2253 /**
2254 * This updates the orig_map->tile_map[tile_num] value after loading
2255 * the map. It also takes care of linking back the freshly loaded
2256 * maps tile_map values if it tiles back to this one. It returns
2257 * the value of orig_map->tile_map[tile_num]. It really only does this
2258 * so that it is easier for calling functions to verify success.
2259 *
2260 * @param orig_map
2261 * map for which we load the tiled map.
2262 * @param tile_num
2263 * tile to load. Must be between 0 and 3 inclusive.
2264 * @return
2265 * linked map, or NULL on failure.
2266 */
2267 static mapstruct *load_and_link_tiled_map(mapstruct *orig_map, int tile_num) {
2268 int dest_tile = (tile_num+2)%4;
2269 char path[HUGE_BUF];
2270
2271 path_combine_and_normalize(orig_map->path, orig_map->tile_path[tile_num], path, sizeof(path));
2272
2273 orig_map->tile_map[tile_num] = ready_map_name(path, 0);
2274 if (orig_map->tile_map[tile_num] == NULL) {
2275 LOG(llevError, "%s has invalid tiled map %s\n", orig_map->path, path);
2276 free(orig_map->tile_path[tile_num]);
2277 orig_map->tile_path[tile_num] = NULL;
2278 return NULL;
2279 }
2280
2281 /* need to do a strcmp here as the orig_map->path is not a shared string */
2282 if (orig_map->tile_map[tile_num]->tile_path[dest_tile]
2283 && !strcmp(orig_map->tile_map[tile_num]->tile_path[dest_tile], orig_map->path))
2284 orig_map->tile_map[tile_num]->tile_map[dest_tile] = orig_map;
2285
2286 return orig_map->tile_map[tile_num];
2287 }
2288
2289 /**
2290 * this returns TRUE if the coordinates (x,y) are out of
2291 * map m. This function also takes into account any
2292 * tiling considerations, loading adjacant maps as needed.
2293 * This is the function should always be used when it
2294 * necessary to check for valid coordinates.
2295 * This function will recursively call itself for the
2296 * tiled maps.
2297 *
2298 * @param m
2299 * map to consider. Must not be NULL.
2300 * @param x
2301 * @param y
2302 * coordinates.
2303 * @return
2304 * 1 if out of map, 0 else
2305 */
2306 int out_of_map(mapstruct *m, int x, int y) {
2307
2308 /* Simple case - coordinates are within this local
2309 * map.
2310 */
2311 if (x >= 0 && x < MAP_WIDTH(m) && y >= 0 && y < MAP_HEIGHT(m))
2312 return 0;
2313
2314 if (x < 0) {
2315 if (!m->tile_path[3])
2316 return 1;
2317 if (!m->tile_map[3] || m->tile_map[3]->in_memory != MAP_IN_MEMORY) {
2318 load_and_link_tiled_map(m, 3);
2319 /* Verify the tile map loaded correctly */
2320 if (!m->tile_map[3])
2321 return 0;
2322 }
2323 return (out_of_map(m->tile_map[3], x+MAP_WIDTH(m->tile_map[3]), y));
2324 } else if (x >= MAP_WIDTH(m)) {
2325 if (!m->tile_path[1])
2326 return 1;
2327 if (!m->tile_map[1] || m->tile_map[1]->in_memory != MAP_IN_MEMORY) {
2328 load_and_link_tiled_map(m, 1);
2329 /* Verify the tile map loaded correctly */
2330 if (!m->tile_map[1])
2331 return 0;
2332 }
2333 return (out_of_map(m->tile_map[1], x-MAP_WIDTH(m), y));
2334 }
2335
2336 if (y < 0) {
2337 if (!m->tile_path[0])
2338 return 1;
2339 if (!m->tile_map[0] || m->tile_map[0]->in_memory != MAP_IN_MEMORY) {
2340 load_and_link_tiled_map(m, 0);
2341 /* Verify the tile map loaded correctly */
2342 if (!m->tile_map[0])
2343 return 0;
2344 }
2345 return (out_of_map(m->tile_map[0], x, y+MAP_HEIGHT(m->tile_map[0])));
2346 } else if (y >= MAP_HEIGHT(m)) {
2347 if (!m->tile_path[2])
2348 return 1;
2349 if (!m->tile_map[2] || m->tile_map[2]->in_memory != MAP_IN_MEMORY) {
2350 load_and_link_tiled_map(m, 2);
2351 /* Verify the tile map loaded correctly */
2352 if (!m->tile_map[2])
2353 return 0;
2354 }
2355 return (out_of_map(m->tile_map[2], x, y-MAP_HEIGHT(m)));
2356 }
2357 return 1;
2358 }
2359
2360 /**
2361 * This is basically the same as out_of_map above(), but
2362 * instead we return NULL if no map is valid (coordinates
2363 * out of bounds and no tiled map), otherwise it returns
2364 * the map as that the coordinates are really on, and
2365 * updates x and y to be the localized coordinates.
2366 * Using this is more efficient than calling out_of_map
2367 * and then figuring out what the real map is
2368 *
2369 * @param m
2370 * map we want to look at. Must not be NULL.
2371 * @param x
2372 * @param y
2373 * coordinates, which will contain the real position that was checked.
2374 * @return
2375 * map that is at specified location. Will be NULL if not on any map.
2376 *
2377 * @note refactored to remove the recursion. This should help stack space and optimization.
2378 */
2379 mapstruct *get_map_from_coord(mapstruct *m, int16_t *x, int16_t *y) {
2380
2381 /* Simple case - coordinates are within this local
2382 * map.
2383 */
2384
2385 if ( !m ) return NULL;
2386 if (*x >= 0 && *x < MAP_WIDTH(m) && *y >= 0 && *y < MAP_HEIGHT(m))
2387 return m;
2388
2389 do /* With the first case there, we can assume we are out of the map if we get here */
2390 {
2391 // Figure out what map should be in the direction we are off the map, and then
2392 // load that map and look again.
2393 if (*x < 0) {
2394 if (!m->tile_path[3])
2395 return NULL;
2396 if (!m->tile_map[3] || m->tile_map[3]->in_memory != MAP_IN_MEMORY){
2397 load_and_link_tiled_map(m, 3);
2398 /* Make sure we loaded properly. */
2399 if (!m->tile_map[3])
2400 return NULL;
2401 }
2402 *x += MAP_WIDTH(m->tile_map[3]);
2403 m = m->tile_map[3];
2404 }
2405 else if (*x >= MAP_WIDTH(m)) {
2406 if (!m->tile_path[1])
2407 return NULL;
2408 if (!m->tile_map[1] || m->tile_map[1]->in_memory != MAP_IN_MEMORY){
2409 load_and_link_tiled_map(m, 1);
2410 /* Make sure we loaded properly. */
2411 if (!m->tile_map[1])
2412 return NULL;
2413 }
2414 *x -= MAP_WIDTH(m);
2415 m = m->tile_map[1];
2416 }
2417 // It is possible that x and y be considered separate compare groups,
2418 // But using an else-if here retains the old behavior that recursion produced.
2419 else if (*y < 0) {
2420 if (!m->tile_path[0])
2421 return NULL;
2422 if (!m->tile_map[0] || m->tile_map[0]->in_memory != MAP_IN_MEMORY){
2423 load_and_link_tiled_map(m, 0);
2424 /* Make sure we loaded properly. */
2425 if (!m->tile_map[0])
2426 return NULL;
2427 }
2428 *y += MAP_HEIGHT(m->tile_map[0]);
2429 m = m->tile_map[0];
2430 }
2431 else if (*y >= MAP_HEIGHT(m)) {
2432 if (!m->tile_path[2])
2433 return NULL;
2434 if (!m->tile_map[2] || m->tile_map[2]->in_memory != MAP_IN_MEMORY){
2435 load_and_link_tiled_map(m, 2);
2436 /* Make sure we loaded properly. */
2437 if (!m->tile_map[2])
2438 return NULL;
2439 }
2440 *y -= MAP_HEIGHT(m);
2441 m = m->tile_map[2];
2442 }
2443 // The check here is if our single tile is in the map.
2444 // That is exactly what the OUT_OF_MAP macro does.
2445 } while (OUT_OF_REAL_MAP(m, *x, *y));
2446 return m; /* We have found our map */
2447 }
2448
2449 /**
2450 * Return whether map2 is adjacent to map1. If so, store the distance from
2451 * map1 to map2 in dx/dy.
2452 *
2453 * @param map1
2454 * @param map2
2455 * maps to consider.
2456 * @param dx
2457 * @param dy
2458 * distance. Must not be NULL. Not altered if returns 0.
2459 * @return
2460 * 1 if maps are adjacent, 0 else.
2461 */
2462 static int adjacent_map(const mapstruct *map1, const mapstruct *map2, int *dx, int *dy) {
2463 if (!map1 || !map2)
2464 return 0;
2465
2466 if (map1 == map2) {
2467 *dx = 0;
2468 *dy = 0;
2469 } else if (map1->tile_map[0] == map2) { /* up */
2470 *dx = 0;
2471 *dy = -MAP_HEIGHT(map2);
2472 } else if (map1->tile_map[1] == map2) { /* right */
2473 *dx = MAP_WIDTH(map1);
2474 *dy = 0;
2475 } else if (map1->tile_map[2] == map2) { /* down */
2476 *dx = 0;
2477 *dy = MAP_HEIGHT(map1);
2478 } else if (map1->tile_map[3] == map2) { /* left */
2479 *dx = -MAP_WIDTH(map2);
2480 *dy = 0;
2481 } else if (map1->tile_map[0] && map1->tile_map[0]->tile_map[1] == map2) { /* up right */
2482 *dx = MAP_WIDTH(map1->tile_map[0]);
2483 *dy = -MAP_HEIGHT(map1->tile_map[0]);
2484 } else if (map1->tile_map[0] && map1->tile_map[0]->tile_map[3] == map2) { /* up left */
2485 *dx = -MAP_WIDTH(map2);
2486 *dy = -MAP_HEIGHT(map1->tile_map[0]);
2487 } else if (map1->tile_map[1] && map1->tile_map[1]->tile_map[0] == map2) { /* right up */
2488 *dx = MAP_WIDTH(map1);
2489 *dy = -MAP_HEIGHT(map2);
2490 } else if (map1->tile_map[1] && map1->tile_map[1]->tile_map[2] == map2) { /* right down */
2491 *dx = MAP_WIDTH(map1);
2492 *dy = MAP_HEIGHT(map1->tile_map[1]);
2493 } else if (map1->tile_map[2] && map1->tile_map[2]->tile_map[1] == map2) { /* down right */
2494 *dx = MAP_WIDTH(map1->tile_map[2]);
2495 *dy = MAP_HEIGHT(map1);
2496 } else if (map1->tile_map[2] && map1->tile_map[2]->tile_map[3] == map2) { /* down left */
2497 *dx = -MAP_WIDTH(map2);
2498 *dy = MAP_HEIGHT(map1);
2499 } else if (map1->tile_map[3] && map1->tile_map[3]->tile_map[0] == map2) { /* left up */
2500 *dx = -MAP_WIDTH(map1->tile_map[3]);
2501 *dy = -MAP_HEIGHT(map2);
2502 } else if (map1->tile_map[3] && map1->tile_map[3]->tile_map[2] == map2) { /* left down */
2503 *dx = -MAP_WIDTH(map1->tile_map[3]);
2504 *dy = MAP_HEIGHT(map1->tile_map[3]);
2505 } else { /* not "adjacent" enough */
2506 return 0;
2507 }
2508
2509 return 1;
2510 }
2511
2512 /**
2513 * From map.c
2514 * This is used by get_player to determine where the other
2515 * creature is. get_rangevector takes into account map tiling,
2516 * so you just can not look the the map coordinates and get the
2517 * right value. distance_x/y are distance away, which
2518 * can be negative. direction is the crossfire direction scheme
2519 * that the creature should head. part is the part of the
2520 * monster that is closest.
2521 *
2522 * get_rangevector looks at op1 and op2, and fills in the
2523 * structure for op1 to get to op2.
2524 * We already trust that the caller has verified that the
2525 * two objects are at least on adjacent maps. If not,
2526 * results are not likely to be what is desired.
2527 *
2528 * @param op1
2529 * object which wants to go to op2's location.
2530 * @param op2
2531 * target of op1.
2532 * @param retval
2533 * vector for op1 to go to op2.
2534 * @param flags
2535 * if 1, don't translate for closest body part of 'op1'
2536 * @return
2537 * 1=ok; 0=the objects are not on the same map
2538 */
2539 int get_rangevector(object *op1, const object *op2, rv_vector *retval, int flags) {
2540 if (!adjacent_map(op1->map, op2->map, &retval->distance_x, &retval->distance_y)) {
2541 /* be conservative and fill in _some_ data */
2542 retval->distance = 100000;
2543 retval->distance_x = 32767;
2544 retval->distance_y = 32767;
2545 retval->direction = 0;
2546 retval->part = NULL;
2547 return 0;
2548 } else {
2549 object *best;
2550
2551 retval->distance_x += op2->x-op1->x;
2552 retval->distance_y += op2->y-op1->y;
2553
2554 best = op1;
2555 /* If this is multipart, find the closest part now */
2556 if (!(flags&0x1) && op1->more) {
2557 object *tmp;
2558 int best_distance = retval->distance_x*retval->distance_x+
2559 retval->distance_y*retval->distance_y, tmpi;
2560
2561 /* we just take the offset of the piece to head to figure
2562 * distance instead of doing all that work above again
2563 * since the distance fields we set above are positive in the
2564 * same axis as is used for multipart objects, the simply arithmetic
2565 * below works.
2566 */
2567 for (tmp = op1->more; tmp != NULL; tmp = tmp->more) {
2568 tmpi = (op1->x-tmp->x+retval->distance_x)*(op1->x-tmp->x+retval->distance_x)+
2569 (op1->y-tmp->y+retval->distance_y)*(op1->y-tmp->y+retval->distance_y);
2570 if (tmpi < best_distance) {
2571 best_distance = tmpi;
2572 best = tmp;
2573 }
2574 }
2575 if (best != op1) {
2576 retval->distance_x += op1->x-best->x;
2577 retval->distance_y += op1->y-best->y;
2578 }
2579 }
2580 retval->part = best;
2581 retval->distance = isqrt(retval->distance_x*retval->distance_x+retval->distance_y*retval->distance_y);
2582 retval->direction = find_dir_2(-retval->distance_x, -retval->distance_y);
2583 return 1;
2584 }
2585 }
2586
2587 /**
2588 * This is basically the same as get_rangevector() above, but instead of
2589 * the first parameter being an object, it instead is the map
2590 * and x,y coordinates - this is used for path to player -
2591 * since the object is not infact moving but we are trying to traverse
2592 * the path, we need this.
2593 * flags has no meaning for this function at this time - I kept it in to
2594 * be more consistant with the above function and also in case they are needed
2595 * for something in the future. Also, since no object is pasted, the best
2596 * field of the rv_vector is set to NULL.
2597 *
2598 * @param m
2599 * map to consider.
2600 * @param x
2601 * @param y
2602 * origin coordinates.
2603 * @param op2
2604 * target object.
2605 * @param retval
2606 * vector to get to op2.
2607 * @param flags
2608 * unused.
2609 * @return
2610 * 1=ok; 0=the objects are not on the same map
2611 */
2612 int get_rangevector_from_mapcoord(const mapstruct *m, int x, int y, const object *op2, rv_vector *retval, int flags) {
2613 (void)flags; // unused [avoid compiler warning]
2614 if (!adjacent_map(m, op2->map, &retval->distance_x, &retval->distance_y)) {
2615 /* be conservative and fill in _some_ data */
2616 retval->distance = 100000;
2617 retval->distance_x = 32767;
2618 retval->distance_y = 32767;
2619 retval->direction = 0;
2620 retval->part = NULL;
2621 return 0;
2622 } else {
2623 retval->distance_x += op2->x-x;
2624 retval->distance_y += op2->y-y;
2625
2626 retval->part = NULL;
2627 retval->distance = isqrt(retval->distance_x*retval->distance_x+retval->distance_y*retval->distance_y);
2628 retval->direction = find_dir_2(-retval->distance_x, -retval->distance_y);
2629 return 1;
2630 }
2631 }
2632
2633 /**
2634 * Checks whether 2 objects are on the same map or not.
2635 *
2636 * Note we only look one map out to keep the processing simple
2637 * and efficient. This could probably be a macro.
2638 * MSW 2001-08-05
2639 *
2640 * @param op1
2641 * first object.
2642 * @param op2
2643 * second object.
2644 * @return
2645 * TRUE if op1 and op2 are effectively on the same map (as related to map tiling).
2646 *
2647 * @note
2648 * This looks for a path from op1 to op2, so if the tiled maps are assymetric and op2 has a path
2649 * to op1, this will still return false.
2650 */
2651 int on_same_map(const object *op1, const object *op2) {
2652 int dx, dy;
2653
2654 return adjacent_map(op1->map, op2->map, &dx, &dy);
2655 }
2656
2657 /**
2658 * Finds an object in a map tile by flag number. Checks the objects' heads.
2659 *
2660 * @param map
2661 * the map to search.
2662 * @param x
2663 * the x-coordiate to search.
2664 * @param y
2665 * the y-coordiate to search.
2666 * @param flag
2667 * the flag to seacrh for
2668 * @return
2669 * first object's head in the tile that has the flag set. NULL if no match.
2670 *
2671 * @note
2672 * will not search in inventory of objects.
2673 */
2674 object *map_find_by_flag(mapstruct *map, int x, int y, int flag) {
2675 object *tmp;
2676
2677 for (tmp = GET_MAP_OB(map, x, y); tmp != NULL; tmp = tmp->above) {
2678 object *head;
2679
2680 head = HEAD(tmp);
2681 if (QUERY_FLAG(head, flag))
2682 return head;
2683 }
2684 return NULL;
2685 }
2686
2687 /**
2688 * Remove files containing the map's unique items.
2689 * @param map
2690 */
2691 void map_remove_unique_files(const mapstruct *map) {
2692 char base[HUGE_BUF], path[HUGE_BUF];
2693 int count;
2694
2695 if (map->unique) {
2696 snprintf(path, sizeof(path), "%s/%s/%s", settings.localdir, settings.playerdir, map->path+1);
2697 if (unlink(path) != 0) {
2698 LOG(llevError, "Could not delete %s: %s\n", path, strerror(errno));
2699 }
2700 return;
2701 }
2702
2703 create_items_path(map->path, base, sizeof(base));
2704
2705 for (count = 0; count < 10; count++) {
2706 snprintf(path, sizeof(path), "%s.v%02d", base, count);
2707 unlink(path);
2708 }
2709 }
2710
2711 /**
2712 * Return the map path on which the specified item is.
2713 * @param item what to return the map path for.
2714 * @return path, map's name, or error string, never NULL.
2715 */
2716 const char *map_get_path(const object *item) {
2717 if (item->map != NULL) {
2718 if (strlen(item->map->path) > 0) {
2719 return item->map->path;
2720 }
2721
2722 return item->map->name ? item->map->name : "(empty path and name)";
2723 }
2724
2725 if (item->env != NULL)
2726 return map_get_path(item->env);
2727
2728 return "(no map and no env!)";
2729 }