]> git.pond.sub.org Git - empserver/blob - src/lib/common/path.c
Merge branch 'pathfind' 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: Path finding 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  *     Markus Armbruster, 2011
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  * Define AS_NO_NEIGHBOR_CACHE to disable the neighbor cache.  The
45  * neighbor cache trades a modest amount of memory to save a bit of
46  * work.  In its current form, it doesn't really make a difference.
47  */
48
49 #include <config.h>
50
51 #include <string.h>
52 #include "../as/as.h"
53 #include "file.h"
54 #include "optlist.h"
55 #include "path.h"
56 #include "prototypes.h"
57 #include "sect.h"
58 #include "xy.h"
59
60 #ifdef USE_PATH_FIND
61 void
62 bp_enable_cachepath(void)
63 {
64 }
65
66 void
67 bp_disable_cachepath(void)
68 {
69 }
70
71 void
72 bp_clear_cachepath(void)
73 {
74 }
75
76 char *
77 BestLandPath(char *path,
78              struct sctstr *from,
79              struct sctstr *to, double *cost, int mob_type)
80 {
81     double c;
82     size_t len;
83
84     *cost = 0.0;
85     *path = 0;
86
87     /*
88      * Note: passing from->sct_own for actor is funny, but works: its
89      * only effect is to confine the search to that nation's land.  It
90      * doesn't affect mobility costs.  The real actor is different for
91      * marching in allied land, and passing it would break path
92      * finding there.
93      */
94     c = path_find(from->sct_x, from->sct_y, to->sct_x, to->sct_y,
95                   from->sct_own, mob_type);
96     if (c < 0)
97         return NULL;
98     len = path_find_route(path, 1024,
99                           from->sct_x, from->sct_y,
100                           to->sct_x, to->sct_y);
101     if (len + 1 >= 1024)
102         return NULL;
103     strcpy(path + len, "h");
104     *cost = c;
105     return path;
106 }
107
108 char *
109 BestDistPath(char *path,
110              struct sctstr *from,
111              struct sctstr *to, double *cost)
112 {
113     return BestLandPath(path, from, to, cost, MOB_MOVE);
114 }
115
116 char *
117 BestShipPath(char *path, int fx, int fy, int tx, int ty, int owner)
118 {
119     size_t len;
120
121     if (path_find(fx, fy, tx, ty, owner, MOB_SAIL) < 0)
122         return NULL;
123     len = path_find_route(path, 100, fx, fy, tx, ty);
124     if (len >= 100)
125         return NULL;
126     if (len == 0)
127         strcpy(path, "h");
128     return path;
129 }
130
131 char *
132 BestAirPath(char *path, int fx, int fy, int tx, int ty)
133 {
134     size_t len;
135
136     if (path_find(fx, fy, tx, ty, 0, MOB_FLY) < 0)
137         return NULL;
138     len = path_find_route(path, 100, fx, fy, tx, ty);
139     if (len >= 100)
140         return NULL;
141     if (len == 0)
142         strcpy(path, "h");
143     return path;
144 }
145 #else   /* !USE_PATH_FIND */
146 #define BP_ASHASHSIZE   128     /* A* queue hash table size */
147 #define BP_NEIGHBORS    6       /* max number of neighbors */
148
149 struct bestp {
150     int bp_mobtype;
151     struct as_data *adp;
152 };
153
154 static int bp_path(struct as_path *pp, char *buf);
155 static int bp_neighbors(struct as_coord c, struct as_coord *cp, void *);
156 static double bp_lbcost(struct as_coord from, struct as_coord to, void *);
157 static double bp_realcost(struct as_coord from, struct as_coord to, void *);
158 static double bp_seccost(struct as_coord from, struct as_coord to, void *);
159 static int bp_coord_hash(struct as_coord c);
160
161 /* We use this for caching neighbors.  It never changes except
162  * at reboot time (maybe) so we never need to free it */
163 static struct sctstr **neighsects;
164
165 static struct bestp *
166 bp_init(void)
167 {
168     struct bestp *bp;
169
170     bp = malloc(sizeof(*bp));
171     memset(bp, 0, sizeof(*bp));
172     bp->adp = as_init(BP_NEIGHBORS, BP_ASHASHSIZE, bp_coord_hash,
173                       bp_neighbors, bp_lbcost, bp_realcost,
174                       bp_seccost, bp);
175
176     if (bp->adp == NULL)
177         return NULL;
178
179 #ifndef AS_NO_NEIGHBOR_CACHE
180     if (neighsects == NULL)
181         neighsects = calloc(WORLD_SZ() * 6, sizeof(struct sctstr *));
182 #endif
183
184     return bp;
185 }
186
187 /*
188  * Find the best path from sector to to sector, and put the Empire movement
189  * string in path.  Return 0 on success, -1 on error.
190  * FIXME unsafe by design: assumes path[] has space; buffer overrun
191  * when path gets long!
192  */
193 static int
194 best_path(struct sctstr *from, struct sctstr *to, char *path, int mob_type)
195 {
196     static struct bestp *mybestpath;
197     struct as_data *adp;
198     struct as_path *ap;
199     int res;
200
201     if (!mybestpath)
202         mybestpath = bp_init();
203     adp = mybestpath->adp;
204 #ifdef AS_NO_PATH_CACHE
205     ap = NULL;
206 #else
207     ap = as_find_cachepath(from->sct_x, from->sct_y, to->sct_x, to->sct_y);
208 #endif
209     if (ap == NULL) {
210         adp->from.x = from->sct_x;
211         adp->from.y = from->sct_y;
212         adp->to.x = to->sct_x;
213         adp->to.y = to->sct_y;
214         mybestpath->bp_mobtype = mob_type;
215
216         res = as_search(adp);
217 #ifdef AS_STATS
218         as_stats(adp, stderr);
219 #ifndef AS_NO_NEIGHBOR_CACHE
220         fprintf(stderr, "neighbor cache %zu bytes\n",
221                 WORLD_SZ() * 6 * sizeof(struct sctstr *));
222 #endif
223 #endif
224         if (res < 0)
225             return -1;
226         ap = adp->path;
227     }
228
229     if (bp_path(ap, path) < 0)
230         return -1;
231     return 0;
232 }
233
234 /*
235  * Translate an A* path into an empire movement string.  Return 0 on
236  * success, -1 on failure.
237  */
238 static int
239 bp_path(struct as_path *pp, char *buf)
240 {
241     struct as_path *np;
242     char *cp = buf;
243     int dx, dy;
244     int n;
245
246     np = pp->next;
247     while (np) {
248         dx = np->c.x - pp->c.x;
249         /* deal with wraparound from non-neg coords */
250         if (dx < -2)
251             dx += WORLD_X;
252         else if (dx > 2)
253             dx -= WORLD_X;
254         dy = np->c.y - pp->c.y;
255         if (dy < -1)
256             dy += WORLD_Y;
257         else if (dy > 1)
258             dy -= WORLD_Y;
259         for (n = 1; n <= 6; n++)
260             if (dx == diroff[n][0] && dy == diroff[n][1])
261                 break;
262         if (n > 6)
263             return -1;
264
265         *cp++ = dirch[n];
266         pp = np;
267         np = np->next;
268     }
269     *cp = '\0';
270     return 0;
271 }
272
273 /*
274  * Find coords neighboring this sector; return number of such
275  * coords, and coordinartes themselves in an array pointed
276  * to by *cpp.
277  * XXX need to check ownership, sector types, etc.
278  */
279 static int
280 bp_neighbors(struct as_coord c, struct as_coord *cp, void *pp)
281 {
282     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
283     struct bestp *bp = pp;
284     coord x, y;
285     coord nx, ny;
286     int n = 0, i;
287     struct sctstr *sp, *from, **ssp;
288     /* Six pointers, just in case our cache isn't there */
289     struct sctstr *tsp[] = { NULL, NULL, NULL, NULL, NULL, NULL };
290     int sx, sy, offset;
291
292     x = c.x;
293     y = c.y;
294     sx = XNORM(x);
295     sy = YNORM(y);
296     offset = XYOFFSET(sx, sy);
297     from = &sectp[offset];
298
299     if (neighsects == NULL)
300         ssp = (struct sctstr **)&tsp[0];
301     else
302         ssp = (struct sctstr **)&neighsects[offset * 6];
303     for (i = 1; i <= 6; i++, ssp++) {
304         if (*ssp == NULL) {
305             /* We haven't cached this neighbor yet */
306             nx = x + diroff[i][0];
307             ny = y + diroff[i][1];
308             sx = XNORM(nx);
309             sy = YNORM(ny);
310             offset = XYOFFSET(sx, sy);
311             sp = &sectp[offset];
312             *ssp = sp;
313         } else {
314             sp = *ssp;
315             sx = sp->sct_x;
316             sy = sp->sct_y;
317         }
318         /* No need to calculate cost each time, just make sure we can
319            move through it.  We calculate it later. */
320         if (dchr[sp->sct_type].d_mob0 < 0)
321             continue;
322         if (bp->bp_mobtype == MOB_RAIL && !SCT_HAS_RAIL(sp))
323             continue;
324         if (sp->sct_own != from->sct_own)
325             continue;
326         cp[n].x = sx;
327         cp[n].y = sy;
328         n++;
329     }
330     return n;
331 }
332
333 /*
334  * Compute a lower-bound on the cost from "from" to "to".
335  */
336 /*ARGSUSED*/
337 static double
338 bp_lbcost(struct as_coord from, struct as_coord to, void *pp)
339 {
340     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
341     struct bestp *bp = pp;
342     int x, y, sx, sy, offset;
343
344     x = to.x;
345     y = to.y;
346     sx = XNORM(x);
347     sy = YNORM(y);
348     offset = XYOFFSET(sx, sy);
349     return sector_mcost(&sectp[offset], bp->bp_mobtype);
350 }
351
352 /*
353  * Compute the real cost to move from "from" to "to".
354  */
355 static double
356 bp_realcost(struct as_coord from, struct as_coord to, void *pp)
357 {
358     return bp_lbcost(from, to, pp);
359 }
360
361 /*
362  * Tie breaker secondary metric (only used when lower bound costs
363  * are equal).
364  */
365 /*ARGSUSED*/
366 static double
367 bp_seccost(struct as_coord from, struct as_coord to, void *pp)
368 {
369     return mapdist((coord)from.x, (coord)from.y,
370                    (coord)to.x, (coord)to.y);
371 }
372
373 /*
374  * Hash a coordinate into an integer.
375  */
376 static int
377 bp_coord_hash(struct as_coord c)
378 {
379     return ((abs(c.x) + 1) << 3) ^ abs(c.y);
380 }
381
382 void
383 bp_enable_cachepath(void)
384 {
385 #ifndef AS_NO_PATH_CACHE
386     as_enable_cachepath();
387 #endif
388 }
389
390 void
391 bp_disable_cachepath(void)
392 {
393 #ifndef AS_NO_PATH_CACHE
394     as_disable_cachepath();
395 #endif
396 }
397
398 void
399 bp_clear_cachepath(void)
400 {
401 #ifndef AS_NO_PATH_CACHE
402     as_clear_cachepath();
403 #endif
404 }
405
406 double
407 pathcost(struct sctstr *start, char *path, int mob_type)
408 {
409     struct sctstr *sectp = (void *)empfile[EF_SECTOR].cache;
410     unsigned i;
411     int o;
412     int cx, cy;
413     double cost = 0.0;
414     struct sctstr *sp;
415     int sx, sy, offset;
416
417     cx = start->sct_x;
418     cy = start->sct_y;
419
420     while (*path) {
421         if (*path == 'h') {
422             path++;
423             continue;
424         }
425         i = *path - 'a';
426         if (CANT_HAPPEN(i >= sizeof(dirindex) / sizeof(*dirindex)))
427             break;
428         o = dirindex[i];
429         if (CANT_HAPPEN(o < 0))
430             break;
431         cx += diroff[o][0];
432         cy += diroff[o][1];
433         sx = XNORM(cx);
434         sy = YNORM(cy);
435         offset = XYOFFSET(sx, sy);
436         sp = &sectp[offset];
437         cost += sector_mcost(sp, mob_type);
438         path++;
439     }
440
441     return cost;
442 }
443
444 char *
445 BestDistPath(char *path,
446              struct sctstr *from,
447              struct sctstr *to, double *cost)
448 {
449     return BestLandPath(path, from, to, cost, MOB_MOVE);
450 }
451
452 char *
453 BestLandPath(char *path,
454              struct sctstr *from,
455              struct sctstr *to, double *cost, int mob_type)
456 {
457     int length;
458
459     *path = 0;
460     *cost = 0.0;
461     if (best_path(from, to, path, mob_type) < 0)
462         return NULL;
463     *cost = pathcost(from, path, mob_type);
464     length = strlen(path);
465     path[length] = 'h';
466     path[length + 1] = '\0';
467     return path;
468 }
469
470 char *
471 BestShipPath(char *path, int fx, int fy, int tx, int ty, int owner)
472 {
473     char *map;
474
475     map = ef_ptr(EF_BMAP, owner);
476     if (!map)
477         return NULL;
478     return bestownedpath(path, map, fx, fy, tx, ty, owner);
479 }
480
481 char *
482 BestAirPath(char *path, int fx, int fy, int tx, int ty)
483 {
484     return bestownedpath(path, NULL, fx, fy, tx, ty, -1);
485 }
486 #endif  /* !USE_PATH_FIND */