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