]> git.pond.sub.org Git - empserver/blob - src/lib/common/path.c
Permit disabling of A* path cache at compile-time
[empserver] / src / lib / common / path.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2010, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ---
21  *
22  *  See files README, COPYING and CREDITS in the root of the source
23  *  tree for related information and legal notices.  It is expected
24  *  that future projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  path.c: Empire/A* Interface code.
29  *
30  *  Known contributors to this file:
31  *     Phil Lapsley, 1991
32  *     Dave Pare, 1991
33  *     Thomas Ruschak, 1993
34  *     Steve McClure, 1997
35  */
36
37 /*
38  * Define AS_STATS for A* statistics on stderr.
39  *
40  * Define AS_NO_PATH_CACHE to disable the path cache.  The path cache
41  * saves a lot of work, but uses lots of memory.  It should be a
42  * significant net win, unless you run out of memory.
43  */
44
45 #include <config.h>
46
47 #include <stdio.h>
48 #include "../as/as.h"
49 #include "file.h"
50 #include "misc.h"
51 #include "optlist.h"
52 #include "path.h"
53 #include "prototypes.h"
54 #include "sect.h"
55 #include "xy.h"
56
57 #define BP_ASHASHSIZE   128     /* A* queue hash table size */
58 #define BP_NEIGHBORS    6       /* max number of neighbors */
59
60 struct bestp {
61     int bp_mobtype;
62     struct as_data *adp;
63 };
64
65 static int bp_path(struct as_path *pp, char *buf);
66 static int bp_neighbors(struct as_coord c, struct as_coord *cp, void *);
67 static double bp_lbcost(struct as_coord from, struct as_coord to, void *);
68 static double bp_realcost(struct as_coord from, struct as_coord to, void *);
69 static double bp_seccost(struct as_coord from, struct as_coord to, void *);
70 static int bp_coord_hash(struct as_coord c);
71
72 /* We use this for caching neighbors.  It never changes except
73  * at reboot time (maybe) so we never need to free it */
74 static struct sctstr **neighsects;
75
76 static struct bestp *
77 bp_init(void)
78 {
79     struct bestp *bp;
80
81     bp = malloc(sizeof(*bp));
82     memset(bp, 0, sizeof(*bp));
83     bp->adp = as_init(BP_NEIGHBORS, BP_ASHASHSIZE, bp_coord_hash,
84                       bp_neighbors, bp_lbcost, bp_realcost,
85                       bp_seccost, bp);
86
87     if (bp->adp == NULL)
88         return NULL;
89
90     if (neighsects == NULL)
91         neighsects = calloc(WORLD_SZ() * 6, sizeof(struct sctstr *));
92
93     return bp;
94 }
95
96 /*
97  * Find the best path from sector to to sector, and put the Empire movement
98  * string in path.  Return 0 on success, -1 on error.
99  * FIXME unsafe by design: assumes path[] has space; buffer overrun
100  * when path gets long!
101  */
102 static int
103 best_path(struct sctstr *from, struct sctstr *to, char *path, int mob_type)
104 {
105     static struct bestp *mybestpath;
106     struct as_data *adp;
107     struct as_path *ap;
108     int res;
109
110     if (!mybestpath)
111         mybestpath = bp_init();
112     adp = mybestpath->adp;
113 #ifdef AS_NO_PATH_CACHE
114     ap = NULL;
115 #else
116     ap = as_find_cachepath(from->sct_x, from->sct_y, to->sct_x, to->sct_y);
117 #endif
118     if (ap == NULL) {
119         adp->from.x = from->sct_x;
120         adp->from.y = from->sct_y;
121         adp->to.x = to->sct_x;
122         adp->to.y = to->sct_y;
123         mybestpath->bp_mobtype = mob_type;
124
125         res = as_search(adp);
126 #ifdef AS_STATS
127         as_stats(adp, stderr);
128         fprintf(stderr, "neighbor cache %zu bytes\n",
129                 WORLD_SZ() * 6 * sizeof(struct sctstr *));
130 #endif
131         if (res < 0)
132             return -1;
133         ap = adp->path;
134     }
135
136     if (bp_path(ap, path) < 0)
137         return -1;
138     return 0;
139 }
140
141 /*
142  * Translate an A* path into an empire movement string.  Return 0 on
143  * success, -1 on failure.
144  */
145 static int
146 bp_path(struct as_path *pp, char *buf)
147 {
148     struct as_path *np;
149     char *cp = buf;
150     int dx, dy;
151     int n;
152
153     np = pp->next;
154     while (np) {
155         dx = np->c.x - pp->c.x;
156         /* deal with wraparound from non-neg coords */
157         if (dx < -2)
158             dx += WORLD_X;
159         else if (dx > 2)
160             dx -= WORLD_X;
161         dy = np->c.y - pp->c.y;
162         if (dy < -1)
163             dy += WORLD_Y;
164         else if (dy > 1)
165             dy -= WORLD_Y;
166         for (n = 1; n <= 6; n++)
167             if (dx == diroff[n][0] && dy == diroff[n][1])
168                 break;
169         if (n > 6)
170             return -1;
171
172         *cp++ = dirch[n];
173         pp = np;
174         np = np->next;
175     }
176     *cp = '\0';
177     return 0;
178 }
179
180 /*
181  * Find coords neighboring this sector; return number of such
182  * coords, and coordinartes themselves in an array pointed
183  * to by *cpp.
184  * XXX need to check ownership, sector types, etc.
185  */
186 static int
187 bp_neighbors(struct as_coord c, struct as_coord *cp, void *pp)
188 {
189     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
190     struct bestp *bp = pp;
191     coord x, y;
192     coord nx, ny;
193     int n = 0, i;
194     struct sctstr *sp, *from, **ssp;
195     /* Six pointers, just in case our cache isn't there */
196     struct sctstr *tsp[] = { NULL, NULL, NULL, NULL, NULL, NULL };
197     int sx, sy, offset;
198
199     x = c.x;
200     y = c.y;
201     sx = XNORM(x);
202     sy = YNORM(y);
203     offset = XYOFFSET(sx, sy);
204     from = &sectp[offset];
205
206     if (neighsects == NULL)
207         ssp = (struct sctstr **)&tsp[0];
208     else
209         ssp = (struct sctstr **)&neighsects[offset * 6];
210     for (i = 1; i <= 6; i++, ssp++) {
211         if (*ssp == NULL) {
212             /* We haven't cached this neighbor yet */
213             nx = x + diroff[i][0];
214             ny = y + diroff[i][1];
215             sx = XNORM(nx);
216             sy = YNORM(ny);
217             offset = XYOFFSET(sx, sy);
218             sp = &sectp[offset];
219             *ssp = sp;
220         } else {
221             sp = *ssp;
222             sx = XNORM(sp->sct_x);
223             sy = YNORM(sp->sct_y);
224         }
225         /* No need to calculate cost each time, just make sure we can
226            move through it.  We calculate it later. */
227         if (dchr[sp->sct_type].d_mob0 < 0)
228             continue;
229         if (bp->bp_mobtype == MOB_RAIL && !SCT_HAS_RAIL(sp))
230             continue;
231         if (sp->sct_own != from->sct_own)
232             continue;
233         cp[n].x = sx;
234         cp[n].y = sy;
235         n++;
236     }
237     return n;
238 }
239
240 /*
241  * Compute a lower-bound on the cost from "from" to "to".
242  */
243 /*ARGSUSED*/
244 static double
245 bp_lbcost(struct as_coord from, struct as_coord to, void *pp)
246 {
247     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
248     struct bestp *bp = pp;
249     int x, y, sx, sy, offset;
250
251     x = to.x;
252     y = to.y;
253     sx = XNORM(x);
254     sy = YNORM(y);
255     offset = XYOFFSET(sx, sy);
256     return sector_mcost(&sectp[offset], bp->bp_mobtype);
257 }
258
259 /*
260  * Compute the real cost to move from "from" to "to".
261  */
262 static double
263 bp_realcost(struct as_coord from, struct as_coord to, void *pp)
264 {
265     return bp_lbcost(from, to, pp);
266 }
267
268 /*
269  * Tie breaker secondary metric (only used when lower bound costs
270  * are equal).
271  */
272 /*ARGSUSED*/
273 static double
274 bp_seccost(struct as_coord from, struct as_coord to, void *pp)
275 {
276     return mapdist((coord)from.x, (coord)from.y,
277                    (coord)to.x, (coord)to.y);
278 }
279
280 /*
281  * Hash a coordinate into an integer.
282  */
283 static int
284 bp_coord_hash(struct as_coord c)
285 {
286     return ((abs(c.x) + 1) << 3) ^ abs(c.y);
287 }
288
289 void
290 bp_enable_cachepath(void)
291 {
292 #ifndef AS_NO_PATH_CACHE
293     as_enable_cachepath();
294 #endif
295 }
296
297 void
298 bp_disable_cachepath(void)
299 {
300 #ifndef AS_NO_PATH_CACHE
301     as_disable_cachepath();
302 #endif
303 }
304
305 void
306 bp_clear_cachepath(void)
307 {
308 #ifndef AS_NO_PATH_CACHE
309     as_clear_cachepath();
310 #endif
311 }
312
313 double
314 pathcost(struct sctstr *start, char *path, int mob_type)
315 {
316     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
317     unsigned i;
318     int o;
319     int cx, cy;
320     double cost = 0.0;
321     struct sctstr *sp;
322     int sx, sy, offset;
323
324     cx = start->sct_x;
325     cy = start->sct_y;
326
327     while (*path) {
328         if (*path == 'h') {
329             path++;
330             continue;
331         }
332         i = *path - 'a';
333         if (CANT_HAPPEN(i >= sizeof(dirindex) / sizeof(*dirindex)))
334             break;
335         o = dirindex[i];
336         if (CANT_HAPPEN(o < 0))
337             break;
338         cx += diroff[o][0];
339         cy += diroff[o][1];
340         sx = XNORM(cx);
341         sy = YNORM(cy);
342         offset = XYOFFSET(sx, sy);
343         sp = &sectp[offset];
344         cost += sector_mcost(sp, mob_type);
345         path++;
346     }
347
348     return cost;
349 }
350
351 char *
352 BestDistPath(char *path,
353              struct sctstr *from,
354              struct sctstr *to, double *cost)
355 {
356     return BestLandPath(path, from, to, cost, MOB_MOVE);
357 }
358
359 char *
360 BestLandPath(char *path,
361              struct sctstr *from,
362              struct sctstr *to, double *cost, int mob_type)
363 {
364     int length;
365
366     *path = 0;
367     *cost = 0.0;
368     if (best_path(from, to, path, mob_type) < 0)
369         return NULL;
370     *cost = pathcost(from, path, mob_type);
371     length = strlen(path);
372     path[length] = 'h';
373     path[length + 1] = '\0';
374     return path;
375 }
376
377 char *
378 BestShipPath(char *path, int fx, int fy, int tx, int ty, int owner)
379 {
380     char *map;
381
382     map = ef_ptr(EF_BMAP, owner);
383     if (!map)
384         return NULL;
385     return bestownedpath(path, map, fx, fy, tx, ty, owner);
386 }
387
388 char *
389 BestAirPath(char *path, int fx, int fy, int tx, int ty)
390 {
391     return bestownedpath(path, NULL, fx, fy, tx, ty, -1);
392 }