]> git.pond.sub.org Git - empserver/blob - src/lib/common/path.c
Fix when best_path() prints A* 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     int res;
102
103     if (!mybestpath)
104         mybestpath = bp_init();
105     adp = mybestpath->adp;
106     ap = as_find_cachepath(from->sct_x, from->sct_y, to->sct_x, to->sct_y);
107     if (ap == NULL) {
108         adp->from.x = from->sct_x;
109         adp->from.y = from->sct_y;
110         adp->to.x = to->sct_x;
111         adp->to.y = to->sct_y;
112         mybestpath->bp_mobtype = mob_type;
113
114         res = as_search(adp);
115 #ifdef AS_STATS
116         as_stats(adp, stderr);
117         fprintf(stderr, "neighbor cache %zu bytes\n",
118                 WORLD_SZ() * 6 * sizeof(struct sctstr *));
119 #endif
120         if (res < 0)
121             return -1;
122         ap = adp->path;
123     }
124
125     if (bp_path(ap, path) < 0)
126         return -1;
127     return 0;
128 }
129
130 /*
131  * Translate an A* path into an empire movement string.  Return 0 on
132  * success, -1 on failure.
133  */
134 static int
135 bp_path(struct as_path *pp, char *buf)
136 {
137     struct as_path *np;
138     char *cp = buf;
139     int dx, dy;
140     int n;
141
142     np = pp->next;
143     while (np) {
144         dx = np->c.x - pp->c.x;
145         /* deal with wraparound from non-neg coords */
146         if (dx < -2)
147             dx += WORLD_X;
148         else if (dx > 2)
149             dx -= WORLD_X;
150         dy = np->c.y - pp->c.y;
151         if (dy < -1)
152             dy += WORLD_Y;
153         else if (dy > 1)
154             dy -= WORLD_Y;
155         for (n = 1; n <= 6; n++)
156             if (dx == diroff[n][0] && dy == diroff[n][1])
157                 break;
158         if (n > 6)
159             return -1;
160
161         *cp++ = dirch[n];
162         pp = np;
163         np = np->next;
164     }
165     *cp = '\0';
166     return 0;
167 }
168
169 /*
170  * Find coords neighboring this sector; return number of such
171  * coords, and coordinartes themselves in an array pointed
172  * to by *cpp.
173  * XXX need to check ownership, sector types, etc.
174  */
175 static int
176 bp_neighbors(struct as_coord c, struct as_coord *cp, void *pp)
177 {
178     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
179     struct bestp *bp = pp;
180     coord x, y;
181     coord nx, ny;
182     int n = 0, i;
183     struct sctstr *sp, *from, **ssp;
184     /* Six pointers, just in case our cache isn't there */
185     struct sctstr *tsp[] = { NULL, NULL, NULL, NULL, NULL, NULL };
186     int sx, sy, offset;
187
188     x = c.x;
189     y = c.y;
190     sx = XNORM(x);
191     sy = YNORM(y);
192     offset = XYOFFSET(sx, sy);
193     from = &sectp[offset];
194
195     if (neighsects == NULL)
196         ssp = (struct sctstr **)&tsp[0];
197     else
198         ssp = (struct sctstr **)&neighsects[offset * 6];
199     for (i = 1; i <= 6; i++, ssp++) {
200         if (*ssp == NULL) {
201             /* We haven't cached this neighbor yet */
202             nx = x + diroff[i][0];
203             ny = y + diroff[i][1];
204             sx = XNORM(nx);
205             sy = YNORM(ny);
206             offset = XYOFFSET(sx, sy);
207             sp = &sectp[offset];
208             *ssp = sp;
209         } else {
210             sp = *ssp;
211             sx = XNORM(sp->sct_x);
212             sy = YNORM(sp->sct_y);
213         }
214         /* No need to calculate cost each time, just make sure we can
215            move through it.  We calculate it later. */
216         if (dchr[sp->sct_type].d_mob0 < 0)
217             continue;
218         if (bp->bp_mobtype == MOB_RAIL && !SCT_HAS_RAIL(sp))
219             continue;
220         if (sp->sct_own != from->sct_own)
221             continue;
222         cp[n].x = sx;
223         cp[n].y = sy;
224         n++;
225     }
226     return n;
227 }
228
229 /*
230  * Compute a lower-bound on the cost from "from" to "to".
231  */
232 /*ARGSUSED*/
233 static double
234 bp_lbcost(struct as_coord from, struct as_coord to, void *pp)
235 {
236     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
237     struct bestp *bp = pp;
238     int x, y, sx, sy, offset;
239
240     x = to.x;
241     y = to.y;
242     sx = XNORM(x);
243     sy = YNORM(y);
244     offset = XYOFFSET(sx, sy);
245     return sector_mcost(&sectp[offset], bp->bp_mobtype);
246 }
247
248 /*
249  * Compute the real cost to move from "from" to "to".
250  */
251 static double
252 bp_realcost(struct as_coord from, struct as_coord to, void *pp)
253 {
254     return bp_lbcost(from, to, pp);
255 }
256
257 /*
258  * Tie breaker secondary metric (only used when lower bound costs
259  * are equal).
260  */
261 /*ARGSUSED*/
262 static double
263 bp_seccost(struct as_coord from, struct as_coord to, void *pp)
264 {
265     return mapdist((coord)from.x, (coord)from.y,
266                    (coord)to.x, (coord)to.y);
267 }
268
269 /*
270  * Hash a coordinate into an integer.
271  */
272 static int
273 bp_coord_hash(struct as_coord c)
274 {
275     return ((abs(c.x) + 1) << 3) ^ abs(c.y);
276 }
277
278 void
279 bp_enable_cachepath(void)
280 {
281     as_enable_cachepath();
282 }
283
284 void
285 bp_disable_cachepath(void)
286 {
287     as_disable_cachepath();
288 }
289
290 void
291 bp_clear_cachepath(void)
292 {
293     as_clear_cachepath();
294 }
295
296 double
297 pathcost(struct sctstr *start, char *path, int mob_type)
298 {
299     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
300     unsigned i;
301     int o;
302     int cx, cy;
303     double cost = 0.0;
304     struct sctstr *sp;
305     int sx, sy, offset;
306
307     cx = start->sct_x;
308     cy = start->sct_y;
309
310     while (*path) {
311         if (*path == 'h') {
312             path++;
313             continue;
314         }
315         i = *path - 'a';
316         if (CANT_HAPPEN(i >= sizeof(dirindex) / sizeof(*dirindex)))
317             break;
318         o = dirindex[i];
319         if (CANT_HAPPEN(o < 0))
320             break;
321         cx += diroff[o][0];
322         cy += diroff[o][1];
323         sx = XNORM(cx);
324         sy = YNORM(cy);
325         offset = XYOFFSET(sx, sy);
326         sp = &sectp[offset];
327         cost += sector_mcost(sp, mob_type);
328         path++;
329     }
330
331     return cost;
332 }
333
334 char *
335 BestDistPath(char *path,
336              struct sctstr *from,
337              struct sctstr *to, double *cost)
338 {
339     return BestLandPath(path, from, to, cost, MOB_MOVE);
340 }
341
342 char *
343 BestLandPath(char *path,
344              struct sctstr *from,
345              struct sctstr *to, double *cost, int mob_type)
346 {
347     int length;
348
349     *path = 0;
350     *cost = 0.0;
351     if (best_path(from, to, path, mob_type) < 0)
352         return NULL;
353     *cost = pathcost(from, path, mob_type);
354     length = strlen(path);
355     path[length] = 'h';
356     path[length + 1] = '\0';
357     return path;
358 }
359
360 char *
361 BestShipPath(char *path, int fx, int fy, int tx, int ty, int owner)
362 {
363     char *map;
364
365     map = ef_ptr(EF_BMAP, owner);
366     if (!map)
367         return NULL;
368     return bestownedpath(path, map, fx, fy, tx, ty, owner);
369 }
370
371 char *
372 BestAirPath(char *path, int fx, int fy, int tx, int ty)
373 {
374     return bestownedpath(path, NULL, fx, fy, tx, ty, -1);
375 }