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