]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/bots.qc
tetris: no longer switch fonts
[divverent/nexuiz.git] / data / qcsrc / server / bots.qc
1 .float aistatus;
2 float AI_STATUS_ROAMING                         = 1;    // Bot is just crawling the map. No enemies at sight
3 float AI_STATUS_ATTACKING                       = 2;    // There are enemies at sight
4 float AI_STATUS_RUNNING                         = 4;    // Bot is bunny hopping
5 float AI_STATUS_DANGER_AHEAD                    = 8;    // There is lava/slime/trigger_hurt ahead
6 float AI_STATUS_OUT_JUMPPAD                     = 16;   // Trying to get out of a "vertical" jump pad
7 float AI_STATUS_OUT_WATER                       = 32;   // Trying to get out of water
8 float AI_STATUS_WAYPOINT_PERSONAL_LINKING       = 64;   // Waiting for the personal waypoint to be linked
9 float AI_STATUS_WAYPOINT_PERSONAL_GOING         = 128;  // Going to a personal waypoint
10 float AI_STATUS_WAYPOINT_PERSONAL_REACHED       = 256;  // Personal waypoint reached
11 #ifdef BOT_JETPACK_NAVIGATION
12 float AI_STATUS_JETPACK_FLYING                  = 512;
13 float AI_STATUS_JETPACK_LANDING                 = 1024;
14 #endif
15
16 // utilities for path debugging
17 #ifdef DEBUG_TRACEWALK
18
19 float DEBUG_NODE_SUCCESS        = 1;
20 float DEBUG_NODE_WARNING        = 2;
21 float DEBUG_NODE_FAIL           = 3;
22
23 vector debuglastnode;
24
25 void debugresetnodes()
26 {
27         debuglastnode = '0 0 0';
28 }
29
30 void debugnode(vector node)
31 {
32         if not(self.classname=="player")
33                 return;
34
35         if(debuglastnode=='0 0 0')
36         {
37                 debuglastnode = node;
38                 return;
39         }
40
41         te_lightning2(world, node, debuglastnode);
42         debuglastnode = node;
43 }
44
45 void debugnodestatus(vector position, float status)
46 {
47         vector color;
48
49         switch (status)
50         {
51                 case DEBUG_NODE_SUCCESS:
52                         color = '0 15 0';
53                         break;
54                 case DEBUG_NODE_WARNING:
55                         color = '15 15 0';
56                         break;
57                 case DEBUG_NODE_FAIL:
58                         color = '15 0 0';
59                         break;
60                 default:
61                         color = '15 15 15';
62         }
63
64         te_customflash(position, 40,  2, color);
65 }
66
67 #endif
68
69 // rough simulation of walking from one point to another to test if a path
70 // can be traveled, used for waypoint linking and havocbot
71
72 vector stepheightvec;
73 float bot_navigation_movemode;
74 float navigation_testtracewalk;
75 float tracewalk(entity e, vector start, vector m1, vector m2, vector end, float movemode)
76 {
77         local vector org;
78         local vector move;
79         local vector dir;
80         local float dist;
81         local float totaldist;
82         local float stepdist;
83         local float yaw;
84         local float ignorehazards;
85         local float swimming;
86
87         #ifdef DEBUG_TRACEWALK
88                 debugresetnodes();
89                 debugnode(start);
90         #endif
91
92         move = end - start;
93         move_z = 0;
94         org = start;
95         dist = totaldist = vlen(move);
96         dir = normalize(move);
97         stepdist = 32;
98         ignorehazards = FALSE;
99
100         // Analyze starting point
101         traceline(start, start, MOVE_NORMAL, e);
102         if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
103                 ignorehazards = TRUE;
104         else
105         {
106                 traceline( start, start + '0 0 -65536', MOVE_NORMAL, e);
107                 if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
108                 {
109                         ignorehazards = TRUE;
110                         swimming = TRUE;
111                 }
112         }
113         tracebox(start, m1, m2, start, MOVE_NOMONSTERS, e);
114         if (trace_startsolid)
115         {
116                 // Bad start
117                 #ifdef DEBUG_TRACEWALK
118                         debugnodestatus(start, DEBUG_NODE_FAIL);
119                 #endif
120                 //print("tracewalk: ", vtos(start), " is a bad start\n");
121                 return FALSE;
122         }
123
124         // Movement loop
125         yaw = vectoyaw(move);
126         move = end - org;
127         for (;;)
128         {
129                 if (boxesoverlap(end, end, org + m1 + '-1 -1 -1', org + m2 + '1 1 1'))
130                 {
131                         // Succeeded
132                         #ifdef DEBUG_TRACEWALK
133                                 debugnodestatus(org, DEBUG_NODE_SUCCESS);
134                         #endif
135                         //print("tracewalk: ", vtos(start), " can reach ", vtos(end), "\n");
136                         return TRUE;
137                 }
138                 #ifdef DEBUG_TRACEWALK
139                         debugnode(org);
140                 #endif
141
142                 if (dist <= 0)
143                         break;
144                 if (stepdist > dist)
145                         stepdist = dist;
146                 dist = dist - stepdist;
147                 traceline(org, org, MOVE_NORMAL, e);
148                 if (!ignorehazards)
149                 {
150                         if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
151                         {
152                                 // hazards blocking path
153                                 #ifdef DEBUG_TRACEWALK
154                                         debugnodestatus(org, DEBUG_NODE_FAIL);
155                                 #endif
156                                 //print("tracewalk: ", vtos(start), " hits a hazard when trying to reach ", vtos(end), "\n");
157                                 return FALSE;
158                         }
159                 }
160                 if (trace_dpstartcontents & DPCONTENTS_LIQUIDSMASK)
161                 {
162                         move = normalize(end - org);
163                         tracebox(org, m1, m2, org + move * stepdist, movemode, e);
164
165                         #ifdef DEBUG_TRACEWALK
166                                 debugnode(trace_endpos);
167                         #endif
168
169                         if (trace_fraction < 1)
170                         {
171                                 swimming = TRUE;
172                                 org = trace_endpos - normalize(org - trace_endpos) * stepdist;
173                                 for(; org_z < end_z + self.maxs_z; org_z += stepdist)
174                                 {
175                                                 #ifdef DEBUG_TRACEWALK
176                                                         debugnode(org);
177                                                 #endif
178                                         if(pointcontents(org) == CONTENT_EMPTY)
179                                                         break;
180                                 }
181
182                                 if not (pointcontents(org + '0 0 1') == CONTENT_EMPTY)
183                                 {
184                                         #ifdef DEBUG_TRACEWALK
185                                                 debugnodestatus(org, DEBUG_NODE_FAIL);
186                                         #endif
187                                         return FALSE;
188                                         //print("tracewalk: ", vtos(start), " failed under water\n");
189                                 }
190                                 continue;
191
192                         }
193                         else
194                                 org = trace_endpos;
195                 }
196                 else
197                 {
198                         move = dir * stepdist + org;
199                         tracebox(org, m1, m2, move, movemode, e);
200
201                         #ifdef DEBUG_TRACEWALK
202                                 debugnode(trace_endpos);
203                         #endif
204
205                         // hit something
206                         if (trace_fraction < 1)
207                         {
208                                 // check if we can walk over this obstacle
209                                 tracebox(org + stepheightvec, m1, m2, move + stepheightvec, movemode, e);
210                                 if (trace_fraction < 1 || trace_startsolid)
211                                 {
212                                         #ifdef DEBUG_TRACEWALK
213                                                 debugnodestatus(trace_endpos, DEBUG_NODE_WARNING);
214                                         #endif
215
216                                         // check for doors
217                                         traceline( org, move, movemode, e);
218                                         if ( trace_ent.classname == "door_rotating" || trace_ent.classname == "door")
219                                         {
220                                                 local vector nextmove;
221                                                 move = trace_endpos;
222                                                 while(trace_ent.classname == "door_rotating" || trace_ent.classname == "door")
223                                                 {
224                                                         nextmove = move + (dir * stepdist);
225                                                         traceline( move, nextmove, movemode, e);
226                                                         move = nextmove;
227                                                 }
228                                         }
229                                         else
230                                         {
231                                                 #ifdef DEBUG_TRACEWALK
232                                                         debugnodestatus(trace_endpos, DEBUG_NODE_FAIL);
233                                                 #endif
234                                                 //print("tracewalk: ", vtos(start), " hit something when trying to reach ", vtos(end), "\n");
235                                                 //te_explosion(trace_endpos);
236                                                 //print(ftos(e.dphitcontentsmask), "\n");
237                                                 return FALSE; // failed
238                                         }
239                                 }
240                                 else
241                                         move = trace_endpos;
242                         }
243                         else
244                                 move = trace_endpos;
245
246                         // trace down from stepheight as far as possible and move there,
247                         // if this starts in solid we try again without the stepup, and
248                         // if that also fails we assume it is a wall
249                         // (this is the same logic as the Quake walkmove function used)
250                         tracebox(move, m1, m2, move + '0 0 -65536', movemode, e);
251
252                         // moved successfully
253                         if(swimming)
254                         {
255                                 local float c;
256                                 c = pointcontents(org + '0 0 1');
257                                 if not(c == CONTENT_WATER || c == CONTENT_LAVA || c == CONTENT_SLIME)
258                                         swimming = FALSE;
259                                 else
260                                         continue;
261                         }
262
263                         org = trace_endpos;
264                 }
265         }
266
267         //print("tracewalk: ", vtos(start), " did not arrive at ", vtos(end), " but at ", vtos(org), "\n");
268
269         // moved but didn't arrive at the intended destination
270         #ifdef DEBUG_TRACEWALK
271                 debugnodestatus(org, DEBUG_NODE_FAIL);
272         #endif
273
274         return FALSE;
275 };
276
277
278 // grenade tracing to decide the best pitch to fire at
279
280 entity tracetossent;
281 entity tracetossfaketarget;
282
283 // traces multiple trajectories to find one that will impact the target
284 // 'end' vector is the place it aims for,
285 // returns TRUE only if it hit targ (don't target non-solid entities)
286 vector findtrajectory_velocity;
287 float findtrajectorywithleading(vector org, vector m1, vector m2, entity targ, float shotspeed, float shotspeedupward, float maxtime, float shotdelay, entity ignore)
288 {
289         local float c, savesolid, shottime;
290         local vector dir, end, v;
291         if (shotspeed < 1)
292                 return FALSE; // could cause division by zero if calculated
293         if (targ.solid < SOLID_BBOX) // SOLID_NOT and SOLID_TRIGGER
294                 return FALSE; // could never hit it
295         if (!tracetossent)
296                 tracetossent = spawn();
297         tracetossent.owner = ignore;
298         setsize(tracetossent, m1, m2);
299         savesolid = targ.solid;
300         targ.solid = SOLID_NOT;
301         shottime = ((vlen(targ.origin - org) / shotspeed) + shotdelay);
302         v = targ.velocity * shottime + targ.origin;
303         tracebox(targ.origin, targ.mins, targ.maxs, v, FALSE, targ);
304         v = trace_endpos;
305         end = v + (targ.mins + targ.maxs) * 0.5;
306         if ((vlen(end - org) / shotspeed + 0.2) > maxtime)
307         {
308                 // out of range
309                 targ.solid = savesolid;
310                 return FALSE;
311         }
312
313         if (!tracetossfaketarget)
314                 tracetossfaketarget = spawn();
315         tracetossfaketarget.solid = savesolid;
316         tracetossfaketarget.movetype = targ.movetype;
317         setmodel(tracetossfaketarget, targ.model); // no low precision
318         tracetossfaketarget.model = targ.model;
319         tracetossfaketarget.modelindex = targ.modelindex;
320         setsize(tracetossfaketarget, targ.mins, targ.maxs);
321         setorigin(tracetossfaketarget, v);
322
323         c = 0;
324         dir = normalize(end - org);
325         while (c < 10) // 10 traces
326         {
327                 setorigin(tracetossent, org); // reset
328                 tracetossent.velocity = findtrajectory_velocity = normalize(dir) * shotspeed + shotspeedupward * '0 0 1';
329                 tracetoss(tracetossent, ignore); // love builtin functions...
330                 if (trace_ent == tracetossfaketarget) // done
331                 {
332                         targ.solid = savesolid;
333
334                         // make it disappear
335                         tracetossfaketarget.solid = SOLID_NOT;
336                         tracetossfaketarget.movetype = MOVETYPE_NONE;
337                         tracetossfaketarget.model = "";
338                         tracetossfaketarget.modelindex = 0;
339                         // relink to remove it from physics considerations
340                         setorigin(tracetossfaketarget, v);
341
342                         return TRUE;
343                 }
344                 dir_z = dir_z + 0.1; // aim up a little more
345                 c = c + 1;
346         }
347         targ.solid = savesolid;
348
349         // make it disappear
350         tracetossfaketarget.solid = SOLID_NOT;
351         tracetossfaketarget.movetype = MOVETYPE_NONE;
352         tracetossfaketarget.model = "";
353         tracetossfaketarget.modelindex = 0;
354         // relink to remove it from physics considerations
355         setorigin(tracetossfaketarget, v);
356
357         // leave a valid one even if it won't reach
358         findtrajectory_velocity = normalize(end - org) * shotspeed + shotspeedupward * '0 0 1';
359         return FALSE;
360 };
361
362
363
364 // lag simulation
365
366 .void(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4) lag_func;
367
368 // upto 5 queued messages
369 .float lag1_time;
370 .float lag1_float1;
371 .float lag1_float2;
372 .entity lag1_entity1;
373 .vector lag1_vec1;
374 .vector lag1_vec2;
375 .vector lag1_vec3;
376 .vector lag1_vec4;
377
378 .float lag2_time;
379 .float lag2_float1;
380 .float lag2_float2;
381 .entity lag2_entity1;
382 .vector lag2_vec1;
383 .vector lag2_vec2;
384 .vector lag2_vec3;
385 .vector lag2_vec4;
386
387 .float lag3_time;
388 .float lag3_float1;
389 .float lag3_float2;
390 .entity lag3_entity1;
391 .vector lag3_vec1;
392 .vector lag3_vec2;
393 .vector lag3_vec3;
394 .vector lag3_vec4;
395
396 .float lag4_time;
397 .float lag4_float1;
398 .float lag4_float2;
399 .entity lag4_entity1;
400 .vector lag4_vec1;
401 .vector lag4_vec2;
402 .vector lag4_vec3;
403 .vector lag4_vec4;
404
405 .float lag5_time;
406 .float lag5_float1;
407 .float lag5_float2;
408 .entity lag5_entity1;
409 .vector lag5_vec1;
410 .vector lag5_vec2;
411 .vector lag5_vec3;
412 .vector lag5_vec4;
413
414 void lag_update()
415 {
416         if (self.lag1_time) if (time > self.lag1_time) {self.lag_func(self.lag1_time, self.lag1_float1, self.lag1_float2, self.lag1_entity1, self.lag1_vec1, self.lag1_vec2, self.lag1_vec3, self.lag1_vec4);self.lag1_time = 0;}
417         if (self.lag2_time) if (time > self.lag2_time) {self.lag_func(self.lag2_time, self.lag2_float1, self.lag2_float2, self.lag2_entity1, self.lag2_vec1, self.lag2_vec2, self.lag2_vec3, self.lag2_vec4);self.lag2_time = 0;}
418         if (self.lag3_time) if (time > self.lag3_time) {self.lag_func(self.lag3_time, self.lag3_float1, self.lag3_float2, self.lag3_entity1, self.lag3_vec1, self.lag3_vec2, self.lag3_vec3, self.lag3_vec4);self.lag3_time = 0;}
419         if (self.lag4_time) if (time > self.lag4_time) {self.lag_func(self.lag4_time, self.lag4_float1, self.lag4_float2, self.lag4_entity1, self.lag4_vec1, self.lag4_vec2, self.lag4_vec3, self.lag4_vec4);self.lag4_time = 0;}
420         if (self.lag5_time) if (time > self.lag5_time) {self.lag_func(self.lag5_time, self.lag5_float1, self.lag5_float2, self.lag5_entity1, self.lag5_vec1, self.lag5_vec2, self.lag5_vec3, self.lag5_vec4);self.lag5_time = 0;}
421 };
422
423 float lag_additem(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4)
424 {
425         if (self.lag1_time == 0) {self.lag1_time = t;self.lag1_float1 = f1;self.lag1_float2 = f2;self.lag1_entity1 = e1;self.lag1_vec1 = v1;self.lag1_vec2 = v2;self.lag1_vec3 = v3;self.lag1_vec4 = v4;return TRUE;}
426         if (self.lag2_time == 0) {self.lag2_time = t;self.lag2_float1 = f1;self.lag2_float2 = f2;self.lag2_entity1 = e1;self.lag2_vec1 = v1;self.lag2_vec2 = v2;self.lag2_vec3 = v3;self.lag2_vec4 = v4;return TRUE;}
427         if (self.lag3_time == 0) {self.lag3_time = t;self.lag3_float1 = f1;self.lag3_float2 = f2;self.lag3_entity1 = e1;self.lag3_vec1 = v1;self.lag3_vec2 = v2;self.lag3_vec3 = v3;self.lag3_vec4 = v4;return TRUE;}
428         if (self.lag4_time == 0) {self.lag4_time = t;self.lag4_float1 = f1;self.lag4_float2 = f2;self.lag4_entity1 = e1;self.lag4_vec1 = v1;self.lag4_vec2 = v2;self.lag4_vec3 = v3;self.lag4_vec4 = v4;return TRUE;}
429         if (self.lag5_time == 0) {self.lag5_time = t;self.lag5_float1 = f1;self.lag5_float2 = f2;self.lag5_entity1 = e1;self.lag5_vec1 = v1;self.lag5_vec2 = v2;self.lag5_vec3 = v3;self.lag5_vec4 = v4;return TRUE;}
430         // no room for it (what is the best thing to do here??)
431         return FALSE;
432 };
433
434
435 // Random skill system
436 .float bot_thinkskill;
437 .float bot_mouseskill;
438 .float bot_predictionskill;
439 .float bot_offsetskill;
440
441
442 // spawnfunc_waypoint navigation system
443
444 // itemscore = (howmuchmoreIwant / howmuchIcanwant) / itemdistance
445 // waypointscore = 0.7 / waypointdistance
446
447 .entity wp00, wp01, wp02, wp03, wp04, wp05, wp06, wp07;
448 .entity wp08, wp09, wp10, wp11, wp12, wp13, wp14, wp15;
449 .entity wp16, wp17, wp18, wp19, wp20, wp21, wp22, wp23, wp24, wp25, wp26, wp27, wp28, wp29, wp30, wp31;
450 .float wp00mincost, wp01mincost, wp02mincost, wp03mincost, wp04mincost, wp05mincost, wp06mincost, wp07mincost;
451 .float wp08mincost, wp09mincost, wp10mincost, wp11mincost, wp12mincost, wp13mincost, wp14mincost, wp15mincost;
452 .float wp16mincost, wp17mincost, wp18mincost, wp19mincost, wp20mincost, wp21mincost, wp22mincost, wp23mincost, wp24mincost, wp25mincost, wp26mincost, wp27mincost, wp28mincost, wp29mincost, wp30mincost, wp31mincost;
453 .float wpfire, wpcost, wpconsidered;
454 .float wpisbox;
455 .float wpflags;
456 .vector wpnearestpoint;
457 .float wplinked;
458
459 // stack of current goals (the last one of which may be an item or other
460 // desirable object, the rest are typically waypoints to reach it)
461 .entity goalcurrent, goalstack01, goalstack02, goalstack03;
462 .entity goalstack04, goalstack05, goalstack06, goalstack07;
463 .entity goalstack08, goalstack09, goalstack10, goalstack11;
464 .entity goalstack12, goalstack13, goalstack14, goalstack15;
465 .entity goalstack16, goalstack17, goalstack18, goalstack19;
466 .entity goalstack20, goalstack21, goalstack22, goalstack23;
467 .entity goalstack24, goalstack25, goalstack26, goalstack27;
468 .entity goalstack28, goalstack29, goalstack30, goalstack31;
469
470 .entity nearestwaypoint;
471 .float nearestwaypointtimeout;
472
473 // used during navigation_goalrating_begin/end sessions
474 #define MAX_BESTGOALS 3
475 float bestgoalswindex;
476 float bestgoalsrindex;
477 float navigation_bestrating;
478 entity navigation_bestgoals[MAX_BESTGOALS];
479 .float navigation_hasgoals;
480
481 /////////////////////////////////////////////////////////////////////////////
482 // spawnfunc_waypoint management
483 /////////////////////////////////////////////////////////////////////////////
484
485 // waypoints with this flag are not saved, they are automatically generated
486 // waypoints like jump pads, teleporters, and items
487 float WAYPOINTFLAG_GENERATED = 8388608;
488 float WAYPOINTFLAG_ITEM = 4194304;
489 float WAYPOINTFLAG_TELEPORT = 2097152;
490 float WAYPOINTFLAG_NORELINK = 1048576;
491 float WAYPOINTFLAG_PERSONAL = 524288;
492
493 // add a new link to the spawnfunc_waypoint, replacing the furthest link it already has
494 void waypoint_addlink(entity from, entity to)
495 {
496         local float c;
497
498         if (from == to)
499                 return;
500         if (from.wpflags & WAYPOINTFLAG_NORELINK)
501                 return;
502
503         if (from.wp00 == to) return;if (from.wp01 == to) return;if (from.wp02 == to) return;if (from.wp03 == to) return;
504         if (from.wp04 == to) return;if (from.wp05 == to) return;if (from.wp06 == to) return;if (from.wp07 == to) return;
505         if (from.wp08 == to) return;if (from.wp09 == to) return;if (from.wp10 == to) return;if (from.wp11 == to) return;
506         if (from.wp12 == to) return;if (from.wp13 == to) return;if (from.wp14 == to) return;if (from.wp15 == to) return;
507         if (from.wp16 == to) return;if (from.wp17 == to) return;if (from.wp18 == to) return;if (from.wp19 == to) return;
508         if (from.wp20 == to) return;if (from.wp21 == to) return;if (from.wp22 == to) return;if (from.wp23 == to) return;
509         if (from.wp24 == to) return;if (from.wp25 == to) return;if (from.wp26 == to) return;if (from.wp27 == to) return;
510         if (from.wp28 == to) return;if (from.wp29 == to) return;if (from.wp30 == to) return;if (from.wp31 == to) return;
511
512         if (to.wpisbox || from.wpisbox)
513         {
514                 // if either is a box we have to find the nearest points on them to
515                 // calculate the distance properly
516                 local vector v1, v2, m1, m2;
517                 v1 = from.origin;
518                 m1 = to.absmin;
519                 m2 = to.absmax;
520                 v1_x = bound(m1_x, v1_x, m2_x);
521                 v1_y = bound(m1_y, v1_y, m2_y);
522                 v1_z = bound(m1_z, v1_z, m2_z);
523                 v2 = to.origin;
524                 m1 = from.absmin;
525                 m2 = from.absmax;
526                 v2_x = bound(m1_x, v2_x, m2_x);
527                 v2_y = bound(m1_y, v2_y, m2_y);
528                 v2_z = bound(m1_z, v2_z, m2_z);
529                 v2 = to.origin;
530                 c = vlen(v2 - v1);
531         }
532         else
533                 c = vlen(to.origin - from.origin);
534
535         if (from.wp31mincost < c) return;
536         if (from.wp30mincost < c) {from.wp31 = to;from.wp31mincost = c;return;} from.wp31 = from.wp30;from.wp31mincost = from.wp30mincost;
537         if (from.wp29mincost < c) {from.wp30 = to;from.wp30mincost = c;return;} from.wp30 = from.wp29;from.wp30mincost = from.wp29mincost;
538         if (from.wp28mincost < c) {from.wp29 = to;from.wp29mincost = c;return;} from.wp29 = from.wp28;from.wp29mincost = from.wp28mincost;
539         if (from.wp27mincost < c) {from.wp28 = to;from.wp28mincost = c;return;} from.wp28 = from.wp27;from.wp28mincost = from.wp27mincost;
540         if (from.wp26mincost < c) {from.wp27 = to;from.wp27mincost = c;return;} from.wp27 = from.wp26;from.wp27mincost = from.wp26mincost;
541         if (from.wp25mincost < c) {from.wp26 = to;from.wp26mincost = c;return;} from.wp26 = from.wp25;from.wp26mincost = from.wp25mincost;
542         if (from.wp24mincost < c) {from.wp25 = to;from.wp25mincost = c;return;} from.wp25 = from.wp24;from.wp25mincost = from.wp24mincost;
543         if (from.wp23mincost < c) {from.wp24 = to;from.wp24mincost = c;return;} from.wp24 = from.wp23;from.wp24mincost = from.wp23mincost;
544         if (from.wp22mincost < c) {from.wp23 = to;from.wp23mincost = c;return;} from.wp23 = from.wp22;from.wp23mincost = from.wp22mincost;
545         if (from.wp21mincost < c) {from.wp22 = to;from.wp22mincost = c;return;} from.wp22 = from.wp21;from.wp22mincost = from.wp21mincost;
546         if (from.wp20mincost < c) {from.wp21 = to;from.wp21mincost = c;return;} from.wp21 = from.wp20;from.wp21mincost = from.wp20mincost;
547         if (from.wp19mincost < c) {from.wp20 = to;from.wp20mincost = c;return;} from.wp20 = from.wp19;from.wp20mincost = from.wp19mincost;
548         if (from.wp18mincost < c) {from.wp19 = to;from.wp19mincost = c;return;} from.wp19 = from.wp18;from.wp19mincost = from.wp18mincost;
549         if (from.wp17mincost < c) {from.wp18 = to;from.wp18mincost = c;return;} from.wp18 = from.wp17;from.wp18mincost = from.wp17mincost;
550         if (from.wp16mincost < c) {from.wp17 = to;from.wp17mincost = c;return;} from.wp17 = from.wp16;from.wp17mincost = from.wp16mincost;
551         if (from.wp15mincost < c) {from.wp16 = to;from.wp16mincost = c;return;} from.wp16 = from.wp15;from.wp16mincost = from.wp15mincost;
552         if (from.wp14mincost < c) {from.wp15 = to;from.wp15mincost = c;return;} from.wp15 = from.wp14;from.wp15mincost = from.wp14mincost;
553         if (from.wp13mincost < c) {from.wp14 = to;from.wp14mincost = c;return;} from.wp14 = from.wp13;from.wp14mincost = from.wp13mincost;
554         if (from.wp12mincost < c) {from.wp13 = to;from.wp13mincost = c;return;} from.wp13 = from.wp12;from.wp13mincost = from.wp12mincost;
555         if (from.wp11mincost < c) {from.wp12 = to;from.wp12mincost = c;return;} from.wp12 = from.wp11;from.wp12mincost = from.wp11mincost;
556         if (from.wp10mincost < c) {from.wp11 = to;from.wp11mincost = c;return;} from.wp11 = from.wp10;from.wp11mincost = from.wp10mincost;
557         if (from.wp09mincost < c) {from.wp10 = to;from.wp10mincost = c;return;} from.wp10 = from.wp09;from.wp10mincost = from.wp09mincost;
558         if (from.wp08mincost < c) {from.wp09 = to;from.wp09mincost = c;return;} from.wp09 = from.wp08;from.wp09mincost = from.wp08mincost;
559         if (from.wp07mincost < c) {from.wp08 = to;from.wp08mincost = c;return;} from.wp08 = from.wp07;from.wp08mincost = from.wp07mincost;
560         if (from.wp06mincost < c) {from.wp07 = to;from.wp07mincost = c;return;} from.wp07 = from.wp06;from.wp07mincost = from.wp06mincost;
561         if (from.wp05mincost < c) {from.wp06 = to;from.wp06mincost = c;return;} from.wp06 = from.wp05;from.wp06mincost = from.wp05mincost;
562         if (from.wp04mincost < c) {from.wp05 = to;from.wp05mincost = c;return;} from.wp05 = from.wp04;from.wp05mincost = from.wp04mincost;
563         if (from.wp03mincost < c) {from.wp04 = to;from.wp04mincost = c;return;} from.wp04 = from.wp03;from.wp04mincost = from.wp03mincost;
564         if (from.wp02mincost < c) {from.wp03 = to;from.wp03mincost = c;return;} from.wp03 = from.wp02;from.wp03mincost = from.wp02mincost;
565         if (from.wp01mincost < c) {from.wp02 = to;from.wp02mincost = c;return;} from.wp02 = from.wp01;from.wp02mincost = from.wp01mincost;
566         if (from.wp00mincost < c) {from.wp01 = to;from.wp01mincost = c;return;} from.wp01 = from.wp00;from.wp01mincost = from.wp00mincost;
567         from.wp00 = to;from.wp00mincost = c;return;
568 };
569
570 // fields you can query using prvm_global server to get some statistics about waypoint linking culling
571 float relink_total, relink_walkculled, relink_pvsculled, relink_lengthculled;
572
573 // relink this spawnfunc_waypoint
574 // (precompile a list of all reachable waypoints from this spawnfunc_waypoint)
575 // (SLOW!)
576 void waypoint_think()
577 {
578         local entity e;
579         local vector sv, sm1, sm2, ev, em1, em2, dv;
580
581         stepheightvec = cvar("sv_stepheight") * '0 0 1';
582         bot_navigation_movemode = ((cvar("bot_navigation_ignoreplayers")) ? MOVE_NOMONSTERS : MOVE_NORMAL);
583
584         //dprint("waypoint_think wpisbox = ", ftos(self.wpisbox), "\n");
585         sm1 = self.origin + self.mins;
586         sm2 = self.origin + self.maxs;
587         for(e = world; (e = find(e, classname, "waypoint")); )
588         {
589                 if (boxesoverlap(self.absmin, self.absmax, e.absmin, e.absmax))
590                 {
591                         waypoint_addlink(self, e);
592                         waypoint_addlink(e, self);
593                 }
594                 else
595                 {
596                         ++relink_total;
597                         if(!checkpvs(self.origin, e))
598                         {
599                                 ++relink_pvsculled;
600                                 continue;
601                         }
602                         sv = e.origin;
603                         sv_x = bound(sm1_x, sv_x, sm2_x);
604                         sv_y = bound(sm1_y, sv_y, sm2_y);
605                         sv_z = bound(sm1_z, sv_z, sm2_z);
606                         ev = self.origin;
607                         em1 = e.origin + e.mins;
608                         em2 = e.origin + e.maxs;
609                         ev_x = bound(em1_x, ev_x, em2_x);
610                         ev_y = bound(em1_y, ev_y, em2_y);
611                         ev_z = bound(em1_z, ev_z, em2_z);
612                         dv = ev - sv;
613                         dv_z = 0;
614                         if (vlen(dv) >= 1050) // max search distance in XY
615                         {
616                                 ++relink_lengthculled;
617                                 continue;
618                         }
619                         navigation_testtracewalk = 0;
620                         if (!self.wpisbox)
621                         {
622                                 tracebox(sv - PL_MIN_z * '0 0 1', PL_MIN, PL_MAX, sv, FALSE, self);
623                                 if (!trace_startsolid)
624                                 {
625                                         //dprint("sv deviation", vtos(trace_endpos - sv), "\n");
626                                         sv = trace_endpos + '0 0 1';
627                                 }
628                         }
629                         if (!e.wpisbox)
630                         {
631                                 tracebox(ev - PL_MIN_z * '0 0 1', PL_MIN, PL_MAX, ev, FALSE, e);
632                                 if (!trace_startsolid)
633                                 {
634                                         //dprint("ev deviation", vtos(trace_endpos - ev), "\n");
635                                         ev = trace_endpos + '0 0 1';
636                                 }
637                         }
638                         //traceline(self.origin, e.origin, FALSE, world);
639                         //if (trace_fraction == 1)
640                         if (!self.wpisbox && tracewalk(self, sv, PL_MIN, PL_MAX, ev, MOVE_NOMONSTERS))
641                                 waypoint_addlink(self, e);
642                         else
643                                 relink_walkculled += 0.5;
644                         if (!e.wpisbox && tracewalk(e, ev, PL_MIN, PL_MAX, sv, MOVE_NOMONSTERS))
645                                 waypoint_addlink(e, self);
646                         else
647                                 relink_walkculled += 0.5;
648                 }
649         }
650         navigation_testtracewalk = 0;
651         self.wplinked = TRUE;
652 };
653
654 void waypoint_clearlinks(entity wp)
655 {
656         // clear links to other waypoints
657         local float f;
658         f = 10000000;
659         wp.wp00 = wp.wp01 = wp.wp02 = wp.wp03 = wp.wp04 = wp.wp05 = wp.wp06 = wp.wp07 = world;wp.wp00mincost = wp.wp01mincost = wp.wp02mincost = wp.wp03mincost = wp.wp04mincost = wp.wp05mincost = wp.wp06mincost = wp.wp07mincost = f;
660         wp.wp08 = wp.wp09 = wp.wp10 = wp.wp11 = wp.wp12 = wp.wp13 = wp.wp14 = wp.wp15 = world;wp.wp08mincost = wp.wp09mincost = wp.wp10mincost = wp.wp11mincost = wp.wp12mincost = wp.wp13mincost = wp.wp14mincost = wp.wp15mincost = f;
661         wp.wp16 = wp.wp17 = wp.wp18 = wp.wp19 = wp.wp20 = wp.wp21 = wp.wp22 = wp.wp23 = world;wp.wp16mincost = wp.wp17mincost = wp.wp18mincost = wp.wp19mincost = wp.wp20mincost = wp.wp21mincost = wp.wp22mincost = wp.wp23mincost = f;
662         wp.wp24 = wp.wp25 = wp.wp26 = wp.wp27 = wp.wp28 = wp.wp29 = wp.wp30 = wp.wp31 = world;wp.wp24mincost = wp.wp25mincost = wp.wp26mincost = wp.wp27mincost = wp.wp28mincost = wp.wp29mincost = wp.wp30mincost = wp.wp31mincost = f;
663         wp.wplinked = FALSE;
664 };
665
666 // tell a spawnfunc_waypoint to relink
667 void waypoint_schedulerelink(entity wp)
668 {
669         if (wp == world)
670                 return;
671         // TODO: add some sort of visible box in edit mode for box waypoints
672         if (cvar("g_waypointeditor"))
673         {
674                 local vector m1, m2;
675                 m1 = wp.mins;
676                 m2 = wp.maxs;
677                 setmodel(wp, "models/runematch/rune.mdl"); wp.effects = EF_LOWPRECISION;
678                 setsize(wp, m1, m2);
679                 if (wp.wpflags & WAYPOINTFLAG_ITEM)
680                         wp.colormod = '1 0 0';
681                 else if (wp.wpflags & WAYPOINTFLAG_GENERATED)
682                         wp.colormod = '1 1 0';
683                 else
684                         wp.colormod = '1 1 1';
685         }
686         else
687                 wp.model = "";
688         wp.wpisbox = vlen(wp.size) > 0;
689         wp.enemy = world;
690         if (!(wp.wpflags & WAYPOINTFLAG_PERSONAL))
691                 wp.owner = world;
692         if (!(wp.wpflags & WAYPOINTFLAG_NORELINK))
693                 waypoint_clearlinks(wp);
694         // schedule an actual relink on next frame
695         wp.think = waypoint_think;
696         wp.nextthink = time;
697         wp.effects = EF_LOWPRECISION;
698 }
699
700 // create a new spawnfunc_waypoint and automatically link it to other waypoints, and link
701 // them back to it as well
702 // (suitable for spawnfunc_waypoint editor)
703 entity waypoint_spawn(vector m1, vector m2, float f)
704 {
705         local entity w;
706         local vector org;
707         w = find(world, classname, "waypoint");
708
709         if not(f & WAYPOINTFLAG_PERSONAL)
710         while (w)
711         {
712                 // if a matching spawnfunc_waypoint already exists, don't add a duplicate
713                 if (boxesoverlap(m1, m2, w.absmin, w.absmax))
714                         return w;
715                 w = find(w, classname, "waypoint");
716         }
717
718         w = spawn();
719         w.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP;
720         w.classname = "waypoint";
721         w.wpflags = f;
722         setorigin(w, (m1 + m2) * 0.5);
723         setsize(w, m1 - w.origin, m2 - w.origin);
724         if (vlen(w.size) > 0)
725                 w.wpisbox = TRUE;
726
727         if(!(f & WAYPOINTFLAG_GENERATED))
728         if(!w.wpisbox)
729         {
730                 traceline(w.origin + '0 0 1', w.origin + PL_MIN_z * '0 0 1' - '0 0 1', MOVE_NOMONSTERS, w);
731                 if (trace_fraction < 1)
732                         setorigin(w, trace_endpos - PL_MIN_z * '0 0 1');
733
734                 // check if the start position is stuck
735                 tracebox(w.origin, PL_MIN + '-1 -1 -1', PL_MAX + '1 1 1', w.origin, MOVE_NOMONSTERS, w);
736                 if (trace_startsolid)
737                 {
738                         org = w.origin + '0 0 26';
739                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
740                         if(trace_startsolid)
741                         {
742                                 org = w.origin + '2 2 2';
743                                 tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
744                                 if(trace_startsolid)
745                                 {
746                                         org = w.origin + '-2 -2 2';
747                                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
748                                         if(trace_startsolid)
749                                         {
750                                                 org = w.origin + '-2 2 2';
751                                                 tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
752                                                 if(trace_startsolid)
753                                                 {
754                                                         org = w.origin + '2 -2 2';
755                                                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
756                                                         if(trace_startsolid)
757                                                         {
758                                                                 // this WP is in solid, refuse it
759                                                                 dprint("Killed a waypoint that was stuck in solid at ", vtos(org), "\n");
760                                                                 remove(w);
761                                                                 return world;
762                                                         }
763                                                 }
764                                         }
765                                 }
766                         }
767                         setorigin(w, org * 0.05 + trace_endpos * 0.95); // don't trust the trace fully
768                 }
769
770                 tracebox(w.origin, PL_MIN, PL_MAX, w.origin - '0 0 128', MOVE_WORLDONLY, w);
771                 if(trace_startsolid)
772                 {
773                         dprint("Killed a waypoint that was stuck in solid ", vtos(w.origin), "\n");
774                         remove(w);
775                         return world;
776                 }
777                 if (!trace_inwater)
778                 {
779                         if(trace_fraction == 1)
780                         {
781                                 dprint("Killed a waypoint that was stuck in air at ", vtos(w.origin), "\n");
782                                 remove(w);
783                                 return world;
784                         }
785                         trace_endpos_z += 0.1; // don't trust the trace fully
786 //                      dprint("Moved waypoint at ", vtos(w.origin), " by ", ftos(vlen(w.origin - trace_endpos)));
787 //                      dprint(" direction: ", vtos((trace_endpos - w.origin)), "\n");
788                         setorigin(w, trace_endpos);
789                 }
790         }
791
792         waypoint_clearlinks(w);
793         //waypoint_schedulerelink(w);
794
795         if (cvar("g_waypointeditor"))
796         {
797                 m1 = w.mins;
798                 m2 = w.maxs;
799                 setmodel(w, "models/runematch/rune.mdl"); w.effects = EF_LOWPRECISION;
800                 setsize(w, m1, m2);
801                 if (w.wpflags & WAYPOINTFLAG_ITEM)
802                         w.colormod = '1 0 0';
803                 else if (w.wpflags & WAYPOINTFLAG_GENERATED)
804                         w.colormod = '1 1 0';
805                 else
806                         w.colormod = '1 1 1';
807         }
808         else
809                 w.model = "";
810
811         return w;
812 };
813
814 // spawnfunc_waypoint map entity
815 void spawnfunc_waypoint()
816 {
817         setorigin(self, self.origin);
818         // schedule a relink after other waypoints have had a chance to spawn
819         waypoint_clearlinks(self);
820         //waypoint_schedulerelink(self);
821 };
822
823 // remove a spawnfunc_waypoint, and schedule all neighbors to relink
824 void waypoint_remove(entity e)
825 {
826         // tell all linked waypoints that they need to relink
827         waypoint_schedulerelink(e.wp00);
828         waypoint_schedulerelink(e.wp01);
829         waypoint_schedulerelink(e.wp02);
830         waypoint_schedulerelink(e.wp03);
831         waypoint_schedulerelink(e.wp04);
832         waypoint_schedulerelink(e.wp05);
833         waypoint_schedulerelink(e.wp06);
834         waypoint_schedulerelink(e.wp07);
835         waypoint_schedulerelink(e.wp08);
836         waypoint_schedulerelink(e.wp09);
837         waypoint_schedulerelink(e.wp10);
838         waypoint_schedulerelink(e.wp11);
839         waypoint_schedulerelink(e.wp12);
840         waypoint_schedulerelink(e.wp13);
841         waypoint_schedulerelink(e.wp14);
842         waypoint_schedulerelink(e.wp15);
843         waypoint_schedulerelink(e.wp16);
844         waypoint_schedulerelink(e.wp17);
845         waypoint_schedulerelink(e.wp18);
846         waypoint_schedulerelink(e.wp19);
847         waypoint_schedulerelink(e.wp20);
848         waypoint_schedulerelink(e.wp21);
849         waypoint_schedulerelink(e.wp22);
850         waypoint_schedulerelink(e.wp23);
851         waypoint_schedulerelink(e.wp24);
852         waypoint_schedulerelink(e.wp25);
853         waypoint_schedulerelink(e.wp26);
854         waypoint_schedulerelink(e.wp27);
855         waypoint_schedulerelink(e.wp28);
856         waypoint_schedulerelink(e.wp29);
857         waypoint_schedulerelink(e.wp30);
858         waypoint_schedulerelink(e.wp31);
859         // and now remove the spawnfunc_waypoint
860         remove(e);
861 };
862
863 // empties the map of waypoints
864 void waypoint_removeall()
865 {
866         local entity head, next;
867         head = findchain(classname, "waypoint");
868         while (head)
869         {
870                 next = head.chain;
871                 remove(head);
872                 head = next;
873         }
874 };
875
876 // tell all waypoints to relink
877 // (is this useful at all?)
878 void waypoint_schedulerelinkall()
879 {
880         local entity head;
881         relink_total = relink_walkculled = relink_pvsculled = relink_lengthculled = 0;
882         head = findchain(classname, "waypoint");
883         while (head)
884         {
885                 waypoint_schedulerelink(head);
886                 head = head.chain;
887         }
888 };
889
890 // Load waypoint links from file
891 float botframe_cachedwaypointlinks;
892 float waypoint_load_links()
893 {
894         local string filename, s;
895         local float file, tokens, c, found;
896         local entity wp_from, wp_to;
897         local vector wp_to_pos, wp_from_pos;
898         filename = strcat("maps/", mapname);
899         filename = strcat(filename, ".waypoints.cache");
900         file = fopen(filename, FILE_READ);
901
902         if (file < 0)
903         {
904                 dprint("waypoint links load from ");
905                 dprint(filename);
906                 dprint(" failed\n");
907                 return FALSE;
908         }
909
910         while (1)
911         {
912                 s = fgets(file);
913                 if (!s)
914                         break;
915
916                 tokens = tokenizebyseparator(s, "*");
917
918                 if (tokens!=2)
919                 {
920                         // bad file format
921                         fclose(file);
922                         return FALSE;
923                 }
924
925                 wp_from_pos     = stov(argv(0));
926                 wp_to_pos       = stov(argv(1));
927
928                 // Search "from" waypoint
929                 if(wp_from.origin!=wp_from_pos)
930                 {
931                         wp_from = findradius(wp_from_pos, 1);
932                         found = FALSE;
933                         while(wp_from)
934                         {
935                                 if(vlen(wp_from.origin-wp_from_pos)<1)
936                                 if(wp_from.classname == "waypoint")
937                                 {
938                                         found = TRUE;
939                                         break;
940                                 }
941                                 wp_from = wp_from.chain;
942                         }
943
944                         if(!found)
945                         {
946                                 // can't find that waypoint
947                                 fclose(file);
948                                 return FALSE;
949                         }
950                 }
951
952                 // Search "to" waypoint
953                 wp_to = findradius(wp_to_pos, 1);
954                 found = FALSE;
955                 while(wp_to)
956                 {
957                         if(vlen(wp_to.origin-wp_to_pos)<1)
958                         if(wp_to.classname == "waypoint")
959                         {
960                                 found = TRUE;
961                                 break;
962                         }
963                         wp_to = wp_to.chain;
964                 }
965
966                 if(!found)
967                 {
968                         // can't find that waypoint
969                         fclose(file);
970                         return FALSE;
971                 }
972
973                 ++c;
974                 waypoint_addlink(wp_from, wp_to);
975         }
976
977         fclose(file);
978
979         dprint("loaded ");
980         dprint(ftos(c));
981         dprint(" waypoint links from maps/");
982         dprint(mapname);
983         dprint(".waypoints.cache\n");
984
985         botframe_cachedwaypointlinks = TRUE;
986         return TRUE;
987 };
988
989 float botframe_loadedforcedlinks;
990 void waypoint_load_links_hardwired()
991 {
992         local string filename, s;
993         local float file, tokens, c, found;
994         local entity wp_from, wp_to;
995         local vector wp_to_pos, wp_from_pos;
996         filename = strcat("maps/", mapname);
997         filename = strcat(filename, ".waypoints.hardwired");
998         file = fopen(filename, FILE_READ);
999
1000         botframe_loadedforcedlinks = TRUE;
1001
1002         if (file < 0)
1003         {
1004                 dprint("waypoint links load from ");
1005                 dprint(filename);
1006                 dprint(" failed\n");
1007                 return;
1008         }
1009
1010         for (;;)
1011         {
1012                 s = fgets(file);
1013                 if (!s)
1014                         break;
1015
1016                 if(substring(s, 0, 2)=="//")
1017                         continue;
1018
1019                 if(substring(s, 0, 1)=="#")
1020                         continue;
1021
1022                 tokens = tokenizebyseparator(s, "*");
1023
1024                 if (tokens!=2)
1025                         continue;
1026
1027                 wp_from_pos     = stov(argv(0));
1028                 wp_to_pos       = stov(argv(1));
1029
1030                 // Search "from" waypoint
1031                 if(wp_from.origin!=wp_from_pos)
1032                 {
1033                         wp_from = findradius(wp_from_pos, 1);
1034                         found = FALSE;
1035                         while(wp_from)
1036                         {
1037                                 if(vlen(wp_from.origin-wp_from_pos)<1)
1038                                 if(wp_from.classname == "waypoint")
1039                                 {
1040                                         found = TRUE;
1041                                         break;
1042                                 }
1043                                 wp_from = wp_from.chain;
1044                         }
1045
1046                         if(!found)
1047                         {
1048                                 print(strcat("NOTICE: Can not find waypoint at ", vtos(wp_from_pos), ". Path skipped\n"));
1049                                 continue;
1050                         }
1051                 }
1052
1053                 // Search "to" waypoint
1054                 wp_to = findradius(wp_to_pos, 1);
1055                 found = FALSE;
1056                 while(wp_to)
1057                 {
1058                         if(vlen(wp_to.origin-wp_to_pos)<1)
1059                         if(wp_to.classname == "waypoint")
1060                         {
1061                                 found = TRUE;
1062                                 break;
1063                         }
1064                         wp_to = wp_to.chain;
1065                 }
1066
1067                 if(!found)
1068                 {
1069                         print(strcat("NOTICE: Can not find waypoint at ", vtos(wp_to_pos), ". Path skipped\n"));
1070                         continue;
1071                 }
1072
1073                 ++c;
1074                 waypoint_addlink(wp_from, wp_to);
1075         }
1076
1077         fclose(file);
1078
1079         dprint("loaded ");
1080         dprint(ftos(c));
1081         dprint(" waypoint links from maps/");
1082         dprint(mapname);
1083         dprint(".waypoints.hardwired\n");
1084 };
1085
1086
1087 // Save all waypoint links to a file
1088 void waypoint_save_links()
1089 {
1090         local string filename, s;
1091         local float file, c, i;
1092         local entity w, link;
1093         filename = strcat("maps/", mapname);
1094         filename = strcat(filename, ".waypoints.cache");
1095         file = fopen(filename, FILE_WRITE);
1096         if (file < 0)
1097         {
1098                 print("waypoint links save to ");
1099                 print(filename);
1100                 print(" failed\n");
1101         }
1102         c = 0;
1103         w = findchain(classname, "waypoint");
1104         while (w)
1105         {
1106                 for(i=0;i<32;++i)
1107                 {
1108                         // :S
1109                         switch(i)
1110                         {
1111                                 //      for i in $(seq -w 0 31); do echo "case $i:link = w.wp$i; break;"; done;
1112                                 case 00:link = w.wp00; break;
1113                                 case 01:link = w.wp01; break;
1114                                 case 02:link = w.wp02; break;
1115                                 case 03:link = w.wp03; break;
1116                                 case 04:link = w.wp04; break;
1117                                 case 05:link = w.wp05; break;
1118                                 case 06:link = w.wp06; break;
1119                                 case 07:link = w.wp07; break;
1120                                 case 08:link = w.wp08; break;
1121                                 case 09:link = w.wp09; break;
1122                                 case 10:link = w.wp10; break;
1123                                 case 11:link = w.wp11; break;
1124                                 case 12:link = w.wp12; break;
1125                                 case 13:link = w.wp13; break;
1126                                 case 14:link = w.wp14; break;
1127                                 case 15:link = w.wp15; break;
1128                                 case 16:link = w.wp16; break;
1129                                 case 17:link = w.wp17; break;
1130                                 case 18:link = w.wp18; break;
1131                                 case 19:link = w.wp19; break;
1132                                 case 20:link = w.wp20; break;
1133                                 case 21:link = w.wp21; break;
1134                                 case 22:link = w.wp22; break;
1135                                 case 23:link = w.wp23; break;
1136                                 case 24:link = w.wp24; break;
1137                                 case 25:link = w.wp25; break;
1138                                 case 26:link = w.wp26; break;
1139                                 case 27:link = w.wp27; break;
1140                                 case 28:link = w.wp28; break;
1141                                 case 29:link = w.wp29; break;
1142                                 case 30:link = w.wp30; break;
1143                                 case 31:link = w.wp31; break;
1144                         }
1145
1146                         if(link==world)
1147                                 continue;
1148
1149                         s = strcat(vtos(w.origin), "*", vtos(link.origin), "\n");
1150                         fputs(file, s);
1151                         ++c;
1152                 }
1153                 w = w.chain;
1154         }
1155         fclose(file);
1156         botframe_cachedwaypointlinks = TRUE;
1157
1158         print("saved ");
1159         print(ftos(c));
1160         print(" waypoints links to maps/");
1161         print(mapname);
1162         print(".waypoints.cache\n");
1163 };
1164
1165 // save waypoints to gamedir/data/maps/mapname.waypoints
1166 void waypoint_saveall()
1167 {
1168         local string filename, s;
1169         local float file, c;
1170         local entity w;
1171         filename = strcat("maps/", mapname);
1172         filename = strcat(filename, ".waypoints");
1173         file = fopen(filename, FILE_WRITE);
1174         if (file >= 0)
1175         {
1176                 c = 0;
1177                 w = findchain(classname, "waypoint");
1178                 while (w)
1179                 {
1180                         if (!(w.wpflags & WAYPOINTFLAG_GENERATED))
1181                         {
1182                                 s = strcat(vtos(w.origin + w.mins), "\n");
1183                                 s = strcat(s, vtos(w.origin + w.maxs));
1184                                 s = strcat(s, "\n");
1185                                 s = strcat(s, ftos(w.wpflags));
1186                                 s = strcat(s, "\n");
1187                                 fputs(file, s);
1188                                 c = c + 1;
1189                         }
1190                         w = w.chain;
1191                 }
1192                 fclose(file);
1193                 bprint("saved ");
1194                 bprint(ftos(c));
1195                 bprint(" waypoints to maps/");
1196                 bprint(mapname);
1197                 bprint(".waypoints\n");
1198         }
1199         else
1200         {
1201                 bprint("waypoint save to ");
1202                 bprint(filename);
1203                 bprint(" failed\n");
1204         }
1205         waypoint_save_links();
1206         botframe_loadedforcedlinks = FALSE;
1207 };
1208
1209 // load waypoints from file
1210 float waypoint_loadall()
1211 {
1212         local string filename, s;
1213         local float file, cwp, cwb, fl;
1214         local vector m1, m2;
1215         cwp = 0;
1216         cwb = 0;
1217         filename = strcat("maps/", mapname);
1218         filename = strcat(filename, ".waypoints");
1219         file = fopen(filename, FILE_READ);
1220         if (file >= 0)
1221         {
1222                 while (1)
1223                 {
1224                         s = fgets(file);
1225                         if (!s)
1226                                 break;
1227                         m1 = stov(s);
1228                         s = fgets(file);
1229                         if (!s)
1230                                 break;
1231                         m2 = stov(s);
1232                         s = fgets(file);
1233                         if (!s)
1234                                 break;
1235                         fl = stof(s);
1236                         waypoint_spawn(m1, m2, fl);
1237                         if (m1 == m2)
1238                                 cwp = cwp + 1;
1239                         else
1240                                 cwb = cwb + 1;
1241                 }
1242                 fclose(file);
1243                 dprint("loaded ");
1244                 dprint(ftos(cwp));
1245                 dprint(" waypoints and ");
1246                 dprint(ftos(cwb));
1247                 dprint(" wayboxes from maps/");
1248                 dprint(mapname);
1249                 dprint(".waypoints\n");
1250         }
1251         else
1252         {
1253                 dprint("waypoint load from ");
1254                 dprint(filename);
1255                 dprint(" failed\n");
1256         }
1257         return cwp + cwb;
1258 };
1259
1260 void waypoint_spawnforitem(entity e)
1261 {
1262         local entity w;
1263         local vector org;
1264
1265         if(!bot_waypoints_for_items)
1266                 return;
1267
1268         // Center of entity
1269         org = (e.absmax + e.absmin) * 0.5;
1270
1271         // Fix the waypoint altitude if necessary
1272         traceline(org, org + '0 0 -65535', TRUE, e);
1273         if(
1274                 org_z - trace_endpos_z > PL_MAX_z - PL_MIN_z + 10 // If middle of entiy is above player heigth
1275                 || org_z - trace_endpos_z < (PL_MAX_z - PL_MIN_z) * 0.5 // or below half player height
1276         )
1277                 org_z = trace_endpos_z + PL_MAX_z - PL_MIN_z;
1278
1279         // TODO: Cleaner solution
1280         if(e.classname!="item_flag_team")
1281                 e.nearestwaypointtimeout = time + 1000000000;
1282
1283         // don't spawn an item spawnfunc_waypoint if it already exists
1284         w = findchain(classname, "waypoint");
1285         while (w)
1286         {
1287                 if (w.wpisbox)
1288                 {
1289                         if (boxesoverlap(org, org, w.absmin, w.absmax))
1290                         {
1291                                 e.nearestwaypoint = w;
1292                                 return;
1293                         }
1294                 }
1295                 else
1296                 {
1297                         if (vlen(w.origin - org) < 16)
1298                         {
1299                                 e.nearestwaypoint = w;
1300                                 return;
1301                         }
1302                 }
1303                 w = w.chain;
1304         }
1305         e.nearestwaypoint = waypoint_spawn(org, org, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_ITEM);
1306 };
1307
1308 void waypoint_spawnforteleporter(entity e, vector destination, float timetaken)
1309 {
1310         local entity w;
1311         local entity dw;
1312         w = waypoint_spawn(e.absmin, e.absmax, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_TELEPORT | WAYPOINTFLAG_NORELINK);
1313         dw = waypoint_spawn(destination, destination, WAYPOINTFLAG_GENERATED);
1314         // one way link to the destination
1315         w.wp00 = dw;
1316         w.wp00mincost = timetaken; // this is just for jump pads
1317         // the teleporter's nearest spawnfunc_waypoint is this one
1318         // (teleporters are not goals, so this is probably useless)
1319         e.nearestwaypoint = w;
1320         e.nearestwaypointtimeout = time + 1000000000;
1321 };
1322
1323 entity waypoint_spawnpersonal(vector position)
1324 {
1325         entity w;
1326
1327         // drop the waypoint to a proper location:
1328         //   first move it up by a player height
1329         //   then move it down to hit the floor with player bbox size
1330         traceline(position, position + '0 0 1' * (PL_MAX_z - PL_MIN_z), MOVE_NOMONSTERS, world);
1331         tracebox(trace_endpos, PL_MIN, PL_MAX, trace_endpos + '0 0 -1024', MOVE_NOMONSTERS, world);
1332         if(trace_fraction < 1)
1333                 position = trace_endpos;
1334
1335         w = waypoint_spawn(position, position, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_PERSONAL);
1336         w.nearestwaypoint = world;
1337         w.nearestwaypointtimeout = 0;
1338         w.owner = self;
1339
1340         waypoint_schedulerelink(w);
1341
1342         return w;
1343 };
1344
1345 /////////////////////////////////////////////////////////////////////////////
1346 // goal stack
1347 /////////////////////////////////////////////////////////////////////////////
1348
1349 // completely empty the goal stack, used when deciding where to go
1350 void navigation_clearroute()
1351 {
1352         //print("bot ", etos(self), " clear\n");
1353         self.navigation_hasgoals = FALSE;
1354         self.goalcurrent = world;
1355         self.goalstack01 = world;
1356         self.goalstack02 = world;
1357         self.goalstack03 = world;
1358         self.goalstack04 = world;
1359         self.goalstack05 = world;
1360         self.goalstack06 = world;
1361         self.goalstack07 = world;
1362         self.goalstack08 = world;
1363         self.goalstack09 = world;
1364         self.goalstack10 = world;
1365         self.goalstack11 = world;
1366         self.goalstack12 = world;
1367         self.goalstack13 = world;
1368         self.goalstack14 = world;
1369         self.goalstack15 = world;
1370         self.goalstack16 = world;
1371         self.goalstack17 = world;
1372         self.goalstack18 = world;
1373         self.goalstack19 = world;
1374         self.goalstack20 = world;
1375         self.goalstack21 = world;
1376         self.goalstack22 = world;
1377         self.goalstack23 = world;
1378         self.goalstack24 = world;
1379         self.goalstack25 = world;
1380         self.goalstack26 = world;
1381         self.goalstack27 = world;
1382         self.goalstack28 = world;
1383         self.goalstack29 = world;
1384         self.goalstack30 = world;
1385         self.goalstack31 = world;
1386 };
1387
1388 // add a new goal at the beginning of the stack
1389 // (in other words: add a new prerequisite before going to the later goals)
1390 void navigation_pushroute(entity e)
1391 {
1392         //print("bot ", etos(self), " push ", etos(e), "\n");
1393         self.goalstack31 = self.goalstack30;
1394         self.goalstack30 = self.goalstack29;
1395         self.goalstack29 = self.goalstack28;
1396         self.goalstack28 = self.goalstack27;
1397         self.goalstack27 = self.goalstack26;
1398         self.goalstack26 = self.goalstack25;
1399         self.goalstack25 = self.goalstack24;
1400         self.goalstack24 = self.goalstack23;
1401         self.goalstack23 = self.goalstack22;
1402         self.goalstack22 = self.goalstack21;
1403         self.goalstack21 = self.goalstack20;
1404         self.goalstack20 = self.goalstack19;
1405         self.goalstack19 = self.goalstack18;
1406         self.goalstack18 = self.goalstack17;
1407         self.goalstack17 = self.goalstack16;
1408         self.goalstack16 = self.goalstack15;
1409         self.goalstack15 = self.goalstack14;
1410         self.goalstack14 = self.goalstack13;
1411         self.goalstack13 = self.goalstack12;
1412         self.goalstack12 = self.goalstack11;
1413         self.goalstack11 = self.goalstack10;
1414         self.goalstack10 = self.goalstack09;
1415         self.goalstack09 = self.goalstack08;
1416         self.goalstack08 = self.goalstack07;
1417         self.goalstack07 = self.goalstack06;
1418         self.goalstack06 = self.goalstack05;
1419         self.goalstack05 = self.goalstack04;
1420         self.goalstack04 = self.goalstack03;
1421         self.goalstack03 = self.goalstack02;
1422         self.goalstack02 = self.goalstack01;
1423         self.goalstack01 = self.goalcurrent;
1424         self.goalcurrent = e;
1425 };
1426
1427 // remove first goal from stack
1428 // (in other words: remove a prerequisite for reaching the later goals)
1429 // (used when a spawnfunc_waypoint is reached)
1430 void navigation_poproute()
1431 {
1432         //print("bot ", etos(self), " pop\n");
1433         self.goalcurrent = self.goalstack01;
1434         self.goalstack01 = self.goalstack02;
1435         self.goalstack02 = self.goalstack03;
1436         self.goalstack03 = self.goalstack04;
1437         self.goalstack04 = self.goalstack05;
1438         self.goalstack05 = self.goalstack06;
1439         self.goalstack06 = self.goalstack07;
1440         self.goalstack07 = self.goalstack08;
1441         self.goalstack08 = self.goalstack09;
1442         self.goalstack09 = self.goalstack10;
1443         self.goalstack10 = self.goalstack11;
1444         self.goalstack11 = self.goalstack12;
1445         self.goalstack12 = self.goalstack13;
1446         self.goalstack13 = self.goalstack14;
1447         self.goalstack14 = self.goalstack15;
1448         self.goalstack15 = self.goalstack16;
1449         self.goalstack16 = self.goalstack17;
1450         self.goalstack17 = self.goalstack18;
1451         self.goalstack18 = self.goalstack19;
1452         self.goalstack19 = self.goalstack20;
1453         self.goalstack20 = self.goalstack21;
1454         self.goalstack21 = self.goalstack22;
1455         self.goalstack22 = self.goalstack23;
1456         self.goalstack23 = self.goalstack24;
1457         self.goalstack24 = self.goalstack25;
1458         self.goalstack25 = self.goalstack26;
1459         self.goalstack26 = self.goalstack27;
1460         self.goalstack27 = self.goalstack28;
1461         self.goalstack28 = self.goalstack29;
1462         self.goalstack29 = self.goalstack30;
1463         self.goalstack30 = self.goalstack31;
1464         self.goalstack31 = world;
1465 };
1466
1467 // find the spawnfunc_waypoint near a dynamic goal such as a dropped weapon
1468 entity navigation_findnearestwaypoint(entity ent, float walkfromwp)
1469 {
1470         local entity waylist, w, best;
1471         local float dist, bestdist;
1472         local vector v, org, pm1, pm2;
1473         pm1 = ent.origin + PL_MIN;
1474         pm2 = ent.origin + PL_MAX;
1475         waylist = findchain(classname, "waypoint");
1476
1477         // do two scans, because box test is cheaper
1478         w = waylist;
1479         while (w)
1480         {
1481                 // if object is touching spawnfunc_waypoint
1482                 if(w != ent)
1483                         if (boxesoverlap(pm1, pm2, w.absmin, w.absmax))
1484                                 return w;
1485                 w = w.chain;
1486         }
1487
1488         org = ent.origin + (ent.mins_z - PL_MIN_z) * '0 0 1';
1489         if(ent.tag_entity)
1490                 org = org + ent.tag_entity.origin;
1491         if (navigation_testtracewalk)
1492                 te_plasmaburn(org);
1493
1494         best = world;
1495         bestdist = 1050;
1496
1497         // box check failed, try walk
1498         w = waylist;
1499         while (w)
1500         {
1501                 // if object can walk from spawnfunc_waypoint
1502                 if(w != ent)
1503                 {
1504                         if (w.wpisbox)
1505                         {
1506                                 local vector wm1, wm2;
1507                                 wm1 = w.origin + w.mins;
1508                                 wm2 = w.origin + w.maxs;
1509                                 v_x = bound(wm1_x, org_x, wm2_x);
1510                                 v_y = bound(wm1_y, org_y, wm2_y);
1511                                 v_z = bound(wm1_z, org_z, wm2_z);
1512                         }
1513                         else
1514                                 v = w.origin;
1515                         dist = vlen(v - org);
1516                         if (bestdist > dist)
1517                         {
1518                                 traceline(v, org, TRUE, ent);
1519                                 if (trace_fraction == 1)
1520                                 {
1521                                         if (walkfromwp)
1522                                         {
1523                                                 //print("^1can I reach ", vtos(org), " from ", vtos(v), "?\n");
1524                                                 if (tracewalk(ent, v, PL_MIN, PL_MAX, org, bot_navigation_movemode))
1525                                                 {
1526                                                         bestdist = dist;
1527                                                         best = w;
1528                                                 }
1529                                         }
1530                                         else
1531                                         {
1532                                                 if (tracewalk(ent, org, PL_MIN, PL_MAX, v, bot_navigation_movemode))
1533                                                 {
1534                                                         bestdist = dist;
1535                                                         best = w;
1536                                                 }
1537                                         }
1538                                 }
1539                         }
1540                 }
1541                 w = w.chain;
1542         }
1543         return best;
1544 }
1545
1546 // finds the waypoints near the bot initiating a navigation query
1547 float navigation_markroutes_nearestwaypoints(entity waylist, float maxdist)
1548 {
1549         local entity head;
1550         local vector v, m1, m2, diff;
1551         local float c;
1552 //      navigation_testtracewalk = TRUE;
1553         c = 0;
1554         head = waylist;
1555         while (head)
1556         {
1557                 if (!head.wpconsidered)
1558                 {
1559                         if (head.wpisbox)
1560                         {
1561                                 m1 = head.origin + head.mins;
1562                                 m2 = head.origin + head.maxs;
1563                                 v = self.origin;
1564                                 v_x = bound(m1_x, v_x, m2_x);
1565                                 v_y = bound(m1_y, v_y, m2_y);
1566                                 v_z = bound(m1_z, v_z, m2_z);
1567                         }
1568                         else
1569                                 v = head.origin;
1570                         diff = v - self.origin;
1571                         diff_z = max(0, diff_z);
1572                         if (vlen(diff) < maxdist)
1573                         {
1574                                 head.wpconsidered = TRUE;
1575                                 if (tracewalk(self, self.origin, self.mins, self.maxs, v, bot_navigation_movemode))
1576                                 {
1577                                         head.wpnearestpoint = v;
1578                                         head.wpcost = vlen(v - self.origin) + head.dmg;
1579                                         head.wpfire = 1;
1580                                         head.enemy = world;
1581                                         c = c + 1;
1582                                 }
1583                         }
1584                 }
1585                 head = head.chain;
1586         }
1587         //navigation_testtracewalk = FALSE;
1588         return c;
1589 }
1590
1591 // updates a path link if a spawnfunc_waypoint link is better than the current one
1592 void navigation_markroutes_checkwaypoint(entity w, entity wp, float cost2, vector p)
1593 {
1594         local vector m1;
1595         local vector m2;
1596         local vector v;
1597         if (wp.wpisbox)
1598         {
1599                 m1 = wp.absmin;
1600                 m2 = wp.absmax;
1601                 v_x = bound(m1_x, p_x, m2_x);
1602                 v_y = bound(m1_y, p_y, m2_y);
1603                 v_z = bound(m1_z, p_z, m2_z);
1604         }
1605         else
1606                 v = wp.origin;
1607         cost2 = cost2 + vlen(v);
1608         if (wp.wpcost > cost2)
1609         {
1610                 wp.wpcost = cost2;
1611                 wp.enemy = w;
1612                 wp.wpfire = 1;
1613                 wp.wpnearestpoint = v;
1614         }
1615 };
1616
1617 // queries the entire spawnfunc_waypoint network for pathes leading away from the bot
1618 void navigation_markroutes()
1619 {
1620         local entity w, wp, waylist;
1621         local float searching, cost, cost2;
1622         local vector p;
1623         w = waylist = findchain(classname, "waypoint");
1624         while (w)
1625         {
1626                 w.wpconsidered = FALSE;
1627                 w.wpnearestpoint = '0 0 0';
1628                 w.wpcost = 10000000;
1629                 w.wpfire = 0;
1630                 w.enemy = world;
1631                 w = w.chain;
1632         }
1633
1634         // try a short range search for the nearest waypoints, and expand the search repeatedly if none are found
1635         // as this search is expensive we will use lower values if the bot is on the air
1636         local float i, increment, maxdistance;
1637         if(self.flags & FL_ONGROUND)
1638         {
1639                 increment = 750;
1640                 maxdistance = 50000;
1641         }
1642         else
1643         {
1644                 increment = 500;
1645                 maxdistance = 1500;
1646         }
1647
1648         for(i=increment;!navigation_markroutes_nearestwaypoints(waylist, i)&&i<maxdistance;i+=increment);
1649
1650         searching = TRUE;
1651         while (searching)
1652         {
1653                 searching = FALSE;
1654                 w = waylist;
1655                 while (w)
1656                 {
1657                         if (w.wpfire)
1658                         {
1659                                 searching = TRUE;
1660                                 w.wpfire = 0;
1661                                 cost = w.wpcost;
1662                                 p = w.wpnearestpoint;
1663                                 wp = w.wp00;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp00mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1664                                 wp = w.wp01;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp01mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1665                                 wp = w.wp02;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp02mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1666                                 wp = w.wp03;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp03mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1667                                 wp = w.wp04;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp04mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1668                                 wp = w.wp05;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp05mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1669                                 wp = w.wp06;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp06mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1670                                 wp = w.wp07;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp07mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1671                                 wp = w.wp08;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp08mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1672                                 wp = w.wp09;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp09mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1673                                 wp = w.wp10;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp10mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1674                                 wp = w.wp11;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp11mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1675                                 wp = w.wp12;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp12mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1676                                 wp = w.wp13;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp13mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1677                                 wp = w.wp14;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp14mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1678                                 wp = w.wp15;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp15mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1679                                 wp = w.wp16;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp16mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1680                                 wp = w.wp17;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp17mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1681                                 wp = w.wp18;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp18mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1682                                 wp = w.wp19;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp19mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1683                                 wp = w.wp20;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp20mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1684                                 wp = w.wp21;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp21mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1685                                 wp = w.wp22;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp22mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1686                                 wp = w.wp23;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp23mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1687                                 wp = w.wp24;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp24mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1688                                 wp = w.wp25;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp25mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1689                                 wp = w.wp26;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp26mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1690                                 wp = w.wp27;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp27mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1691                                 wp = w.wp28;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp28mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1692                                 wp = w.wp29;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp29mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1693                                 wp = w.wp30;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp30mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1694                                 wp = w.wp31;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp31mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1695                                 }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
1696                         }
1697                         w = w.chain;
1698                 }
1699         }
1700 };
1701
1702 void navigation_bestgoals_reset()
1703 {
1704         local float i;
1705
1706         bestgoalswindex = 0;
1707         bestgoalsrindex = 0;
1708
1709         for(i=0;i>MAX_BESTGOALS-1;++i)
1710         {
1711                 navigation_bestgoals[i] = world;
1712         }
1713 }
1714
1715 void navigation_add_bestgoal(entity goal)
1716 {
1717         if(bestgoalsrindex>0)
1718         {
1719                 ++bestgoalsrindex;
1720
1721                 if(bestgoalsrindex==MAX_BESTGOALS)
1722                         bestgoalsrindex = 0;
1723         }
1724
1725         if(bestgoalswindex==MAX_BESTGOALS)
1726         {
1727                 bestgoalswindex=0;
1728                 if(bestgoalsrindex==0)
1729                         bestgoalsrindex=1;
1730         }
1731
1732         navigation_bestgoals[bestgoalswindex] = goal;
1733
1734         ++bestgoalswindex;
1735 }
1736
1737 entity navigation_get_bestgoal()
1738 {
1739         local entity ent;
1740
1741         ent = navigation_bestgoals[bestgoalsrindex];
1742         navigation_bestgoals[bestgoalsrindex] = world;
1743
1744         ++bestgoalsrindex;
1745
1746         if(bestgoalsrindex==MAX_BESTGOALS)
1747                 bestgoalsrindex = 0;
1748
1749         return ent;
1750 }
1751
1752 #ifdef BOT_JETPACK_NAVIGATION
1753 // fields required for jetpack navigation
1754 .entity navigation_jetpack_goal;
1755 .vector navigation_jetpack_point;
1756 #endif
1757
1758 // updates the best goal according to a weighted calculation of travel cost and item value of a new proposed item
1759 .void() havocbot_role;
1760 void() havocbot_role_ctf_offense;
1761 void navigation_routerating(entity e, float f, float rangebias)
1762 {
1763         if (!e)
1764                 return;
1765
1766 #ifdef BOT_JETPACK_NAVIGATION
1767         // Evaluate path using jetpack
1768         if(g_jetpack)
1769         if(self.items & IT_JETPACK)
1770         if(cvar("bot_ai_navigation_jetpack"))
1771         if(vlen(self.origin - e.origin) > cvar("bot_ai_navigation_jetpack_mindistance"))
1772         {
1773                 vector pointa, pointb;
1774
1775         //      dprint("jetpack ai: evaluating path for ", e.classname,"\n");
1776
1777                 // Point A
1778                 traceline(self.origin, self.origin + '0 0 65535', MOVE_NORMAL, self);
1779                 pointa = trace_endpos - '0 0 1';
1780
1781                 // Point B
1782                 traceline(e.origin, e.origin + '0 0 65535', MOVE_NORMAL, e);
1783                 pointb = trace_endpos - '0 0 1';
1784
1785                 // Can I see these two points from the sky?
1786                 traceline(pointa, pointb, MOVE_NORMAL, self);
1787
1788                 if(trace_fraction==1)
1789                 {
1790                 //      dprint("jetpack ai: can bridge these two points\n");
1791
1792                         // Lower the altitude of these points as much as possible
1793                         local float zdistance, xydistance, cost, t, fuel;
1794                         local vector down, npa, npb;
1795
1796                         down = '0 0 -1' * (PL_MAX_z - PL_MIN_z) * 10;
1797
1798                         do{
1799                                 npa = pointa + down;
1800                                 npb = pointb + down;
1801
1802                                 if(npa_z<=self.absmax_z)
1803                                         break;
1804
1805                                 if(npb_z<=e.absmax_z)
1806                                         break;
1807
1808                                 traceline(npa, npb, MOVE_NORMAL, self);
1809                                 if(trace_fraction==1)
1810                                 {
1811                                         pointa = npa;
1812                                         pointb = npb;
1813                                 }
1814                         }
1815                         while(trace_fraction == 1);
1816
1817
1818                         // Rough estimation of fuel consumption
1819                         // (ignores acceleration and current xyz velocity)
1820                         xydistance = vlen(pointa - pointb);
1821                         zdistance = fabs(pointa_z - self.origin_z);
1822
1823                         t = zdistance / cvar("g_jetpack_maxspeed_up");
1824                         t += xydistance / cvar("g_jetpack_maxspeed_side");
1825                         fuel = t * cvar("g_jetpack_fuel") * 0.8;
1826
1827                 //      dprint("jetpack ai: required fuel ", ftos(fuel), " self.ammo_fuel ", ftos(self.ammo_fuel),"\n");
1828
1829                         // enough fuel ?
1830                         if(self.ammo_fuel>fuel)
1831                         {
1832                                 // Estimate cost
1833                                 // (as onground costs calculation is mostly based on distances, here we do the same establishing some relationship
1834                                 //  - between air and ground speeds)
1835
1836                                 cost = xydistance / (cvar("g_jetpack_maxspeed_side")/cvar("sv_maxspeed"));
1837                                 cost += zdistance / (cvar("g_jetpack_maxspeed_up")/cvar("sv_maxspeed"));
1838                                 cost *= 1.5;
1839
1840                                 // Compare against other goals
1841                                 f = f * rangebias / (rangebias + cost);
1842
1843                                 if (navigation_bestrating < f)
1844                                 {
1845                         //              dprint("jetpack path: added goal", e.classname, " (with rating ", ftos(f), ")\n");
1846                                         navigation_bestrating = f;
1847                                         navigation_add_bestgoal(e);
1848                                         self.navigation_jetpack_goal = e;
1849                                         self.navigation_jetpack_point = pointb;
1850                                 }
1851                                 return;
1852                         }
1853                 }
1854         }
1855         #endif
1856
1857         //te_wizspike(e.origin);
1858         //bprint(etos(e));
1859         //bprint("\n");
1860         // update the cached spawnfunc_waypoint link on a dynamic item entity
1861         if (time > e.nearestwaypointtimeout)
1862         {
1863                 e.nearestwaypoint = navigation_findnearestwaypoint(e, TRUE);
1864
1865                 // TODO: Cleaner solution, probably handling this timeout from ctf.qc
1866                 if(e.classname=="item_flag_team")
1867                         e.nearestwaypointtimeout = time + 2;
1868                 else
1869                         e.nearestwaypointtimeout = time + random() * 3 + 5;
1870         }
1871
1872         //dprint("-- checking ", e.classname, " (with cost ", ftos(e.nearestwaypoint.wpcost), ")\n");
1873         if (e.nearestwaypoint)
1874         if (e.nearestwaypoint.wpcost < 10000000)
1875         {
1876                 //te_wizspike(e.nearestwaypoint.wpnearestpoint);
1877         //      dprint(e.classname, " ", ftos(f), "/(1+", ftos((e.nearestwaypoint.wpcost + vlen(e.origin - e.nearestwaypoint.wpnearestpoint))), "/", ftos(rangebias), ") = ");
1878                 f = f * rangebias / (rangebias + (e.nearestwaypoint.wpcost + vlen(e.origin - e.nearestwaypoint.wpnearestpoint)));
1879                 //if (self.havocbot_role == havocbot_role_ctf_offense)
1880                 //dprint("considering ", e.classname, " (with rating ", ftos(f), ")\n");
1881                 //dprint(ftos(f));
1882                 if (navigation_bestrating < f)
1883                 {
1884                 //      dprint("ground path: added goal ", e.classname, " (with rating ", ftos(f), ")\n");
1885                         navigation_bestrating = f;
1886                         navigation_add_bestgoal(e);
1887                 }
1888         }
1889         //dprint("\n");
1890 };
1891
1892 // adds an item to the the goal stack with the path to a given item
1893 float navigation_routetogoal(entity e, vector startposition)
1894 {
1895         self.goalentity = e;
1896
1897         // if there is no goal, just exit
1898         if (!e)
1899                 return FALSE;
1900
1901         self.navigation_hasgoals = TRUE;
1902
1903         // put the entity on the goal stack
1904         navigation_pushroute(e);
1905
1906 #ifdef BOT_JETPACK_NAVIGATION
1907         if(g_jetpack)
1908         if(e==self.navigation_jetpack_goal)
1909                 return TRUE;
1910 #endif
1911
1912         // if it can reach the goal there is nothing more to do
1913         if (tracewalk(self, startposition, PL_MIN, PL_MAX, e.origin, bot_navigation_movemode))
1914                 return TRUE;
1915
1916         // see if there are waypoints describing a path to the item
1917         e = e.nearestwaypoint;
1918         if(e == world)
1919                 return FALSE;
1920
1921         for (;;)
1922         {
1923                 // add the spawnfunc_waypoint to the path
1924                 navigation_pushroute(e);
1925                 e = e.enemy;
1926
1927                 if(e==world)
1928                         break;
1929         }
1930
1931         return FALSE;
1932 };
1933
1934 void navigation_routetogoals()
1935 {
1936         entity g1, g2;
1937
1938         navigation_clearroute();
1939
1940         g1 = navigation_get_bestgoal();
1941         for(;;)
1942         {
1943                 if(g2==world)
1944                         g2 = navigation_get_bestgoal();
1945
1946                 if(g2==world)
1947                 {
1948                         navigation_routetogoal(g1, self.origin);
1949                         return;
1950                 }
1951
1952                 if(navigation_routetogoal(g1, g2.origin))
1953                 {
1954                         g1 = g2;
1955                         g2 = world;
1956                         continue;
1957                 }
1958
1959                 navigation_clearroute();
1960                 g1 = g2;
1961                 g2 = world;
1962         }
1963 }
1964
1965 // removes any currently touching waypoints from the goal stack
1966 // (this is how bots detect if they have reached a goal)
1967 .float lastteleporttime;
1968
1969 void navigation_poptouchedgoals()
1970 {
1971         local vector org, m1, m2;
1972         org = self.origin;
1973         m1 = org + self.mins;
1974         m2 = org + self.maxs;
1975
1976         if(self.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT)
1977         {
1978                 if(self.lastteleporttime>0)
1979                 if(time-self.lastteleporttime<0.15)
1980                 {
1981                         navigation_poproute();
1982                         return;
1983                 }
1984         }
1985
1986         // Loose goal touching check when running
1987         if(self.aistatus & AI_STATUS_RUNNING)
1988         if(self.goalcurrent.classname=="waypoint")
1989         {
1990                 if(vlen(self.origin - self.goalcurrent.origin)<150)
1991                 {
1992                         traceline(self.origin + self.view_ofs , self.goalcurrent.origin, TRUE, world);
1993                         if(trace_fraction==1)
1994                         {
1995                                 // Detect personal waypoints
1996                                 if(self.aistatus & AI_STATUS_WAYPOINT_PERSONAL_GOING)
1997                                 if(self.goalcurrent.wpflags & WAYPOINTFLAG_PERSONAL && self.goalcurrent.owner==self)
1998                                 {
1999                                         self.aistatus &~= AI_STATUS_WAYPOINT_PERSONAL_GOING;
2000                                         self.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_REACHED;
2001                                 }
2002
2003                                 navigation_poproute();
2004                         }
2005                 }
2006         }
2007
2008         while (self.goalcurrent && boxesoverlap(m1, m2, self.goalcurrent.absmin, self.goalcurrent.absmax))
2009         {
2010                 // Detect personal waypoints
2011                 if(self.aistatus & AI_STATUS_WAYPOINT_PERSONAL_GOING)
2012                 if(self.goalcurrent.wpflags & WAYPOINTFLAG_PERSONAL && self.goalcurrent.owner==self)
2013                 {
2014                         self.aistatus &~= AI_STATUS_WAYPOINT_PERSONAL_GOING;
2015                         self.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_REACHED;
2016                 }
2017
2018                 navigation_poproute();
2019         }
2020 }
2021
2022 // begin a goal selection session (queries spawnfunc_waypoint network)
2023 void navigation_goalrating_start()
2024 {
2025 #ifdef BOT_JETPACK_NAVIGATION
2026         self.navigation_jetpack_goal = world;
2027 #endif
2028         navigation_bestrating = -1;
2029         self.navigation_hasgoals = FALSE;
2030         navigation_bestgoals_reset();
2031         navigation_markroutes();
2032 };
2033
2034 // ends a goal selection session (updates goal stack to the best goal)
2035 void navigation_goalrating_end()
2036 {
2037         navigation_routetogoals();
2038 //      dprint("best goal ", self.goalcurrent.classname , "\n");
2039
2040         // Hack: if it can't walk to any goal just move blindly to the first visible waypoint
2041         if not (self.navigation_hasgoals)
2042         {
2043                 dprint(self.netname, " can't walk to any goal, going to a near waypoint\n");
2044
2045                 entity head;
2046
2047                 RandomSelection_Init();
2048                 head = findradius(self.origin,1000);
2049                 while(head)
2050                 {
2051                         if(head.classname=="waypoint")
2052                         if(!(head.wpflags & WAYPOINTFLAG_GENERATED))
2053                         if(vlen(self.origin-head.origin)>100)
2054                         if(checkpvs(self.view_ofs,head))
2055                                 RandomSelection_Add(head, 0, string_null, 1 + (vlen(self.origin-head.origin)<500), 0);
2056                         head = head.chain;
2057                 }
2058                 if(RandomSelection_chosen_ent)
2059                         navigation_routetogoal(RandomSelection_chosen_ent, self.origin);
2060
2061                 self.navigation_hasgoals = FALSE; // Reset this value
2062         }
2063 };
2064
2065
2066 //////////////////////////////////////////////////////////////////////////////
2067 // general bot functions
2068 //////////////////////////////////////////////////////////////////////////////
2069
2070 .float isbot; // true if this client is actually a bot
2071
2072 float skill;
2073 entity bot_list;
2074 .entity nextbot;
2075 .string netname_freeme;
2076 .string playermodel_freeme;
2077 .string playerskin_freeme;
2078
2079 float sv_maxspeed;
2080 .float createdtime;
2081
2082 .float bot_preferredcolors;
2083
2084 .float bot_attack;
2085 .float bot_dodge;
2086 .float bot_dodgerating;
2087
2088 //.float bot_painintensity;
2089 .float bot_firetimer;
2090 //.float bot_oldhealth;
2091 .void() bot_ai;
2092
2093 .entity bot_aimtarg;
2094 .float bot_aimlatency;
2095 .vector bot_aimselforigin;
2096 .vector bot_aimselfvelocity;
2097 .vector bot_aimtargorigin;
2098 .vector bot_aimtargvelocity;
2099
2100 .float bot_pickup;
2101 .float(entity player, entity item) bot_pickupevalfunc;
2102 .float bot_pickupbasevalue;
2103 .float bot_canfire;
2104 .float bot_strategytime;
2105
2106 // used for aiming currently
2107 // FIXME: make the weapon code use these and then replace the calculations here with a call to the weapon code
2108 vector shotorg;
2109 vector shotdir;
2110
2111 .float bot_forced_team;
2112 .float bot_config_loaded;
2113
2114 void bot_setnameandstuff()
2115 {
2116         string readfile, s;
2117         float file, tokens, prio;
2118         entity p;
2119
2120         string bot_name, bot_model, bot_skin, bot_shirt, bot_pants;
2121         string name, prefix, suffix;
2122
2123         if(cvar("g_campaign"))
2124         {
2125                 prefix = "";
2126                 suffix = "";
2127         }
2128         else
2129         {
2130                 prefix = cvar_string("bot_prefix");
2131                 suffix = cvar_string("bot_suffix");
2132         }
2133
2134         file = fopen(cvar_string("bot_config_file"), FILE_READ);
2135
2136         if(file < 0)
2137                 print(strcat("Error: Can not open the bot configuration file '",cvar_string("bot_config_file"),"'\n"));
2138         else
2139         {
2140                 RandomSelection_Init();
2141                 for(;;)
2142                 {
2143                         readfile = fgets(file);
2144                         if(!readfile)
2145                                 break;
2146                         if(substring(readfile, 0, 2) == "//")
2147                                 continue;
2148                         if(substring(readfile, 0, 1) == "#")
2149                                 continue;
2150                         tokens = tokenizebyseparator(readfile, "\t");
2151                         s = argv(0);
2152                         prio = 1;
2153                         FOR_EACH_CLIENT(p)
2154                         {
2155                                 if(strcat(prefix, s, suffix) == p.netname)
2156                                 {
2157                                         prio = 0;
2158                                         break;
2159                                 }
2160                         }
2161                         RandomSelection_Add(world, 0, readfile, 1, prio);
2162                 }
2163                 readfile = RandomSelection_chosen_string;
2164                 fclose(file);
2165         }
2166
2167         tokens = tokenizebyseparator(readfile, "\t");
2168         if(argv(0) != "") bot_name = argv(0);
2169         else bot_name = "Bot";
2170
2171         if(argv(1) != "") bot_model = argv(1);
2172         else bot_model = "marine";
2173
2174         if(argv(2) != "") bot_skin = argv(2);
2175         else bot_skin = "0";
2176
2177         if(argv(3) != "" && stof(argv(3)) >= 0) bot_shirt = argv(3);
2178         else bot_shirt = ftos(floor(random() * 15));
2179
2180         if(argv(4) != "" && stof(argv(4)) >= 0) bot_pants = argv(4);
2181         else bot_pants = ftos(floor(random() * 15));
2182
2183         self.bot_forced_team = stof(argv(5));
2184         self.bot_config_loaded = TRUE;
2185
2186         // this is really only a default, JoinBestTeam is called later
2187         setcolor(self, stof(bot_shirt) * 16 + stof(bot_pants));
2188         self.bot_preferredcolors = self.clientcolors;
2189
2190         // pick the name
2191         if (cvar("bot_usemodelnames"))
2192                 name = bot_model;
2193         else
2194                 name = bot_name;
2195
2196         // pick the model and skin
2197         if(substring(bot_model, -4, 1) != ".")
2198                 bot_model = strcat(bot_model, ".zym");
2199         self.playermodel = self.playermodel_freeme = strzone(strcat("models/player/", bot_model));
2200         self.playerskin = self.playerskin_freeme = strzone(bot_skin);
2201
2202         self.netname = self.netname_freeme = strzone(strcat(prefix, name, suffix));
2203 };
2204
2205 float bot_custom_weapon;
2206 float bot_distance_far;
2207 float bot_distance_close;
2208
2209 float bot_weapons_far[WEP_LAST];
2210 float bot_weapons_mid[WEP_LAST];
2211 float bot_weapons_close[WEP_LAST];
2212
2213 void bot_custom_weapon_priority_setup()
2214 {
2215         local float tokens, i, c, w;
2216
2217         bot_custom_weapon = FALSE;
2218
2219         if(     cvar_string("bot_ai_custom_weapon_priority_far") == "" ||
2220                 cvar_string("bot_ai_custom_weapon_priority_mid") == "" ||
2221                 cvar_string("bot_ai_custom_weapon_priority_close") == "" ||
2222                 cvar_string("bot_ai_custom_weapon_priority_distances") == ""
2223         )
2224                 return;
2225
2226         // Parse distances
2227         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_distances")," ");
2228
2229         if (tokens!=2)
2230                 return;
2231
2232         bot_distance_far = stof(argv(0));
2233         bot_distance_close = stof(argv(1));
2234
2235         if(bot_distance_far < bot_distance_close){
2236                 bot_distance_far = stof(argv(1));
2237                 bot_distance_close = stof(argv(0));
2238         }
2239
2240         // Initialize list of weapons
2241         bot_weapons_far[0] = -1;
2242         bot_weapons_mid[0] = -1;
2243         bot_weapons_close[0] = -1;
2244
2245         // Parse far distance weapon priorities
2246         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_far")," ");
2247
2248         c = 0;
2249         for(i=0; i < tokens && c < WEP_COUNT; ++i){
2250                 w = stof(argv(i));
2251                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
2252                         bot_weapons_far[c] = w;
2253                         ++c;
2254                 }
2255         }
2256         if(c < WEP_COUNT)
2257                 bot_weapons_far[c] = -1;
2258
2259         // Parse mid distance weapon priorities
2260         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_mid")," ");
2261
2262         c = 0;
2263         for(i=0; i < tokens && c < WEP_COUNT; ++i){
2264                 w = stof(argv(i));
2265                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
2266                         bot_weapons_mid[c] = w;
2267                         ++c;
2268                 }
2269         }
2270         if(c < WEP_COUNT)
2271                 bot_weapons_mid[c] = -1;
2272
2273         // Parse close distance weapon priorities
2274         tokens = tokenizebyseparator(cvar_string("bot_ai_custom_weapon_priority_close")," ");
2275
2276         c = 0;
2277         for(i=0; i < tokens && i < WEP_COUNT; ++i){
2278                 w = stof(argv(i));
2279                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
2280                         bot_weapons_close[c] = w;
2281                         ++c;
2282                 }
2283         }
2284         if(c < WEP_COUNT)
2285                 bot_weapons_close[c] = -1;
2286
2287         bot_custom_weapon = TRUE;
2288 };
2289
2290
2291 void bot_endgame()
2292 {
2293         local entity e;
2294         //dprint("bot_endgame\n");
2295         e = bot_list;
2296         while (e)
2297         {
2298                 setcolor(e, e.bot_preferredcolors);
2299                 e = e.nextbot;
2300         }
2301         // if dynamic waypoints are ever implemented, save them here
2302 };
2303
2304 float bot_ignore_bots; // let bots not attack other bots (only works in non-teamplay)
2305 float bot_shouldattack(entity e)
2306 {
2307         if (e.team == self.team)
2308         {
2309                 if (e == self)
2310                         return FALSE;
2311                 if (teams_matter)
2312                 if (e.team != 0)
2313                         return FALSE;
2314         }
2315         if(!teams_matter)
2316                 if(bot_ignore_bots)
2317                         if(clienttype(e) == CLIENTTYPE_BOT)
2318                                 return FALSE;
2319         if (!e.takedamage)
2320                 return FALSE;
2321         if (e.deadflag)
2322                 return FALSE;
2323         if (e.BUTTON_CHAT)
2324                 return FALSE;
2325         if(g_minstagib)
2326         if(e.items & IT_STRENGTH)
2327                 return FALSE;
2328         if(e.flags & FL_NOTARGET)
2329                 return FALSE;
2330         return TRUE;
2331 };
2332
2333 void bot_lagfunc(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4)
2334 {
2335         if(self.flags & FL_INWATER)
2336         {
2337                 self.bot_aimtarg = world;
2338                 return;
2339         }
2340         self.bot_aimtarg = e1;
2341         self.bot_aimlatency = self.ping; // FIXME?  Shouldn't this be in the lag item?
2342         self.bot_aimselforigin = v1;
2343         self.bot_aimselfvelocity = v2;
2344         self.bot_aimtargorigin = v3;
2345         self.bot_aimtargvelocity = v4;
2346         if(skill <= 0)
2347                 self.bot_canfire = (random() < 0.8);
2348         else if(skill <= 1)
2349                 self.bot_canfire = (random() < 0.9);
2350         else if(skill <= 2)
2351                 self.bot_canfire = (random() < 0.95);
2352         else
2353                 self.bot_canfire = 1;
2354 };
2355
2356 .float bot_nextthink;
2357 .float bot_badaimtime;
2358 .float bot_aimthinktime;
2359 .float bot_prevaimtime;
2360 .vector bot_mouseaim;
2361 .vector bot_badaimoffset;
2362 .vector bot_1st_order_aimfilter;
2363 .vector bot_2nd_order_aimfilter;
2364 .vector bot_3th_order_aimfilter;
2365 .vector bot_4th_order_aimfilter;
2366 .vector bot_5th_order_aimfilter;
2367 .vector bot_olddesiredang;
2368 float bot_aimdir(vector v, float maxfiredeviation)
2369 {
2370         local float dist, delta_t, blend;
2371         local vector desiredang, diffang;
2372
2373         //dprint("aim ", self.netname, ": old:", vtos(self.v_angle));
2374         // make sure v_angle is sane first
2375         self.v_angle_y = self.v_angle_y - floor(self.v_angle_y / 360) * 360;
2376         self.v_angle_z = 0;
2377
2378         // get the desired angles to aim at
2379         //dprint(" at:", vtos(v));
2380         v = normalize(v);
2381         //te_lightning2(world, self.origin + self.view_ofs, self.origin + self.view_ofs + v * 200);
2382         if (time >= self.bot_badaimtime)
2383         {
2384                 self.bot_badaimtime = max(self.bot_badaimtime + 0.3, time);
2385                 self.bot_badaimoffset = randomvec() * bound(0, 5 - 0.5 * (skill+self.bot_offsetskill), 5) * cvar("bot_ai_aimskill_offset");
2386         }
2387         desiredang = vectoangles(v) + self.bot_badaimoffset;
2388         //dprint(" desired:", vtos(desiredang));
2389         if (desiredang_x >= 180)
2390                 desiredang_x = desiredang_x - 360;
2391         desiredang_x = bound(-90, 0 - desiredang_x, 90);
2392         desiredang_z = self.v_angle_z;
2393         //dprint(" / ", vtos(desiredang));
2394
2395         //// pain throws off aim
2396         //if (self.bot_painintensity)
2397         //{
2398         //      // shake from pain
2399         //      desiredang = desiredang + randomvec() * self.bot_painintensity * 0.2;
2400         //}
2401
2402         // calculate turn angles
2403         diffang = (desiredang - self.bot_olddesiredang);
2404         // wrap yaw turn
2405         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2406         if (diffang_y >= 180)
2407                 diffang_y = diffang_y - 360;
2408         self.bot_olddesiredang = desiredang;
2409         //dprint(" diff:", vtos(diffang));
2410
2411         delta_t = time-self.bot_prevaimtime;
2412         self.bot_prevaimtime = time;
2413         // Here we will try to anticipate the comming aiming direction
2414         self.bot_1st_order_aimfilter= self.bot_1st_order_aimfilter
2415                 + (diffang * (1 / delta_t)    - self.bot_1st_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_1st"),1);
2416         self.bot_2nd_order_aimfilter= self.bot_2nd_order_aimfilter
2417                 + (self.bot_1st_order_aimfilter - self.bot_2nd_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_2nd"),1);
2418         self.bot_3th_order_aimfilter= self.bot_3th_order_aimfilter
2419                 + (self.bot_2nd_order_aimfilter - self.bot_3th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_3th"),1);
2420         self.bot_4th_order_aimfilter= self.bot_4th_order_aimfilter
2421                 + (self.bot_3th_order_aimfilter - self.bot_4th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_4th"),1);
2422         self.bot_5th_order_aimfilter= self.bot_5th_order_aimfilter
2423                 + (self.bot_4th_order_aimfilter - self.bot_5th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_5th"),1);
2424
2425         //blend = (bound(0,skill,10)*0.1)*pow(1-bound(0,skill,10)*0.05,2.5)*5.656854249; //Plot formule before changing !
2426         blend = bound(0,skill,10)*0.1;
2427         desiredang = desiredang + blend *
2428         (
2429                   self.bot_1st_order_aimfilter * cvar("bot_ai_aimskill_order_mix_1st")
2430                 + self.bot_2nd_order_aimfilter * cvar("bot_ai_aimskill_order_mix_2nd")
2431                 + self.bot_3th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_3th")
2432                 + self.bot_4th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_4th")
2433                 + self.bot_5th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_5th")
2434         );
2435
2436         // calculate turn angles
2437         diffang = desiredang - self.bot_mouseaim;
2438         // wrap yaw turn
2439         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2440         if (diffang_y >= 180)
2441                 diffang_y = diffang_y - 360;
2442         //dprint(" diff:", vtos(diffang));
2443
2444         if (time >= self.bot_aimthinktime)
2445         {
2446                 self.bot_aimthinktime = max(self.bot_aimthinktime + 0.5 - 0.05*(skill+self.bot_thinkskill), time);
2447                 self.bot_mouseaim = self.bot_mouseaim + diffang * (1-random()*0.1*bound(1,10-skill,10));
2448         }
2449
2450         //self.v_angle = self.v_angle + diffang * bound(0, r * frametime * (skill * 0.5 + 2), 1);
2451
2452         diffang = self.bot_mouseaim - desiredang;
2453         // wrap yaw turn
2454         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2455         if (diffang_y >= 180)
2456                 diffang_y = diffang_y - 360;
2457         desiredang = desiredang + diffang * bound(0,cvar("bot_ai_aimskill_think"),1);
2458
2459         // calculate turn angles
2460         diffang = desiredang - self.v_angle;
2461         // wrap yaw turn
2462         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2463         if (diffang_y >= 180)
2464                 diffang_y = diffang_y - 360;
2465         //dprint(" diff:", vtos(diffang));
2466
2467         // jitter tracking
2468         dist = vlen(diffang);
2469         //diffang = diffang + randomvec() * (dist * 0.05 * (3.5 - bound(0, skill, 3)));
2470
2471         // turn
2472         local float r, fixedrate, blendrate;
2473         fixedrate = cvar("bot_ai_aimskill_fixedrate") / bound(1,dist,1000);
2474         blendrate = cvar("bot_ai_aimskill_blendrate");
2475         r = max(fixedrate, blendrate);
2476         //self.v_angle = self.v_angle + diffang * bound(frametime, r * frametime * (2+skill*skill*0.05-random()*0.05*(10-skill)), 1);
2477         self.v_angle = self.v_angle + diffang * bound(delta_t, r * delta_t * (2+pow(skill+self.bot_mouseskill,3)*0.005-random()), 1);
2478         self.v_angle = self.v_angle * bound(0,cvar("bot_ai_aimskill_mouse"),1) + desiredang * bound(0,(1-cvar("bot_ai_aimskill_mouse")),1);
2479         //self.v_angle = self.v_angle + diffang * bound(0, r * frametime * (skill * 0.5 + 2), 1);
2480         //self.v_angle = self.v_angle + diffang * (1/ blendrate);
2481         self.v_angle_z = 0;
2482         self.v_angle_y = self.v_angle_y - floor(self.v_angle_y / 360) * 360;
2483         //dprint(" turn:", vtos(self.v_angle));
2484
2485         makevectors(self.v_angle);
2486         shotorg = self.origin + self.view_ofs;
2487         shotdir = v_forward;
2488
2489         //dprint(" dir:", vtos(v_forward));
2490         //te_lightning2(world, shotorg, shotorg + shotdir * 100);
2491
2492         // calculate turn angles again
2493         //diffang = desiredang - self.v_angle;
2494         //diffang_y = diffang_y - floor(diffang_y / 360) * 360;
2495         //if (diffang_y >= 180)
2496         //      diffang_y = diffang_y - 360;
2497
2498         //dprint("e ", vtos(diffang), " < ", ftos(maxfiredeviation), "\n");
2499
2500         // decide whether to fire this time
2501         // note the maxfiredeviation is in degrees so this has to convert to radians first
2502         //if ((normalize(v) * shotdir) >= cos(maxfiredeviation * (3.14159265358979323846 / 180)))
2503         if ((normalize(v) * shotdir) >= cos(maxfiredeviation * (3.14159265358979323846 / 180)))
2504         if (vlen(trace_endpos-shotorg) < 500+500*bound(0, skill, 10) || random()*random()>bound(0,skill*0.05,1))
2505                 self.bot_firetimer = time + bound(0.1, 0.5-skill*0.05, 0.5);
2506         //traceline(shotorg,shotorg+shotdir*1000,FALSE,world);
2507         //dprint(ftos(maxfiredeviation),"\n");
2508         //dprint(" diff:", vtos(diffang), "\n");
2509
2510         return self.bot_canfire && (time < self.bot_firetimer);
2511 };
2512
2513 vector bot_shotlead(vector targorigin, vector targvelocity, float shotspeed, float shotdelay)
2514 {
2515         // Try to add code here that predicts gravity effect here, no clue HOW to though ... well not yet atleast...
2516         return targorigin + targvelocity * (shotdelay + vlen(targorigin - shotorg) / shotspeed);
2517 };
2518
2519 float bot_aim(float shotspeed, float shotspeedupward, float maxshottime, float applygravity)
2520 {
2521         local float f, r;
2522         local vector v;
2523         /*
2524         eprint(self);
2525         dprint("bot_aim(", ftos(shotspeed));
2526         dprint(", ", ftos(shotspeedupward));
2527         dprint(", ", ftos(maxshottime));
2528         dprint(", ", ftos(applygravity));
2529         dprint(");\n");
2530         */
2531         shotspeed *= g_weaponspeedfactor;
2532         shotspeedupward *= g_weaponspeedfactor;
2533         if (!shotspeed)
2534         {
2535                 dprint("bot_aim: WARNING: weapon ", W_Name(self.weapon), " shotspeed is zero!\n");
2536                 shotspeed = 1000000;
2537         }
2538         if (!maxshottime)
2539         {
2540                 dprint("bot_aim: WARNING: weapon ", W_Name(self.weapon), " maxshottime is zero!\n");
2541                 maxshottime = 1;
2542         }
2543         makevectors(self.v_angle);
2544         shotorg = self.origin + self.view_ofs;
2545         shotdir = v_forward;
2546         v = bot_shotlead(self.bot_aimtargorigin, self.bot_aimtargvelocity, shotspeed, self.bot_aimlatency);
2547         local float distanceratio;
2548         distanceratio =sqrt(bound(0,skill,10000))*0.3*(vlen(v-shotorg)-100)/cvar("bot_ai_aimskill_firetolerance_distdegrees");
2549         distanceratio = bound(0,distanceratio,1);
2550         r =  (cvar("bot_ai_aimskill_firetolerance_maxdegrees")-cvar("bot_ai_aimskill_firetolerance_mindegrees"))
2551                 * (1-distanceratio) + cvar("bot_ai_aimskill_firetolerance_mindegrees");
2552         if (applygravity && self.bot_aimtarg)
2553         {
2554                 if (!findtrajectorywithleading(shotorg, '0 0 0', '0 0 0', self.bot_aimtarg, shotspeed, shotspeedupward, maxshottime, 0, self))
2555                         return FALSE;
2556                 f = bot_aimdir(findtrajectory_velocity - shotspeedupward * '0 0 1', r);
2557         }
2558         else
2559         {
2560                 f = bot_aimdir(v - shotorg, r);
2561                 //dprint("AIM: ");dprint(vtos(self.bot_aimtargorigin));dprint(" + ");dprint(vtos(self.bot_aimtargvelocity));dprint(" * ");dprint(ftos(self.bot_aimlatency + vlen(self.bot_aimtargorigin - shotorg) / shotspeed));dprint(" = ");dprint(vtos(v));dprint(" : aimdir = ");dprint(vtos(normalize(v - shotorg)));dprint(" : ");dprint(vtos(shotdir));dprint("\n");
2562                 traceline(shotorg, shotorg + shotdir * 10000, FALSE, self);
2563                 if (trace_ent.takedamage)
2564                 if (trace_fraction < 1)
2565                 if (!bot_shouldattack(trace_ent))
2566                         return FALSE;
2567                 traceline(shotorg, self.bot_aimtargorigin, FALSE, self);
2568                 if (trace_fraction < 1)
2569                 if (trace_ent != self.enemy)
2570                 if (!bot_shouldattack(trace_ent))
2571                         return FALSE;
2572         }
2573         if (r > maxshottime * shotspeed)
2574                 return FALSE;
2575         return f;
2576 };
2577
2578 // TODO: move this painintensity code to the player damage code
2579 void bot_think()
2580 {
2581         if (self.bot_nextthink > time)
2582                 return;
2583
2584         self.flags &~= FL_GODMODE;
2585         if(cvar("bot_god"))
2586                 self.flags |= FL_GODMODE;
2587
2588         self.bot_nextthink = self.bot_nextthink + cvar("bot_ai_thinkinterval");
2589         //if (self.bot_painintensity > 0)
2590         //      self.bot_painintensity = self.bot_painintensity - (skill + 1) * 40 * frametime;
2591
2592         //self.bot_painintensity = self.bot_painintensity + self.bot_oldhealth - self.health;
2593         //self.bot_painintensity = bound(0, self.bot_painintensity, 100);
2594
2595         if(time < game_starttime || ((cvar("g_campaign") && !campaign_bots_may_start)))
2596         {
2597                 self.nextthink = time + 0.5;
2598                 return;
2599         }
2600
2601         if (self.fixangle)
2602         {
2603                 self.v_angle = self.angles;
2604                 self.v_angle_z = 0;
2605                 self.fixangle = FALSE;
2606         }
2607
2608         self.dmg_take = 0;
2609         self.dmg_save = 0;
2610         self.dmg_inflictor = world;
2611
2612         // calculate an aiming latency based on the skill setting
2613         // (simulated network latency + naturally delayed reflexes)
2614         //self.ping = 0.7 - bound(0, 0.05 * skill, 0.5); // moved the reflexes to bot_aimdir (under the name 'think')
2615         // minimum ping 20+10 random
2616         self.ping = bound(0,0.07 - bound(0, skill * 0.005,0.05)+random()*0.01,0.65); // Now holds real lag to server, and higer skill players take a less laggy server
2617         // skill 10 = ping 0.2 (adrenaline)
2618         // skill 0 = ping 0.7 (slightly drunk)
2619
2620         // clear buttons
2621         self.BUTTON_ATCK = 0;
2622         self.button1 = 0;
2623         self.BUTTON_JUMP = 0;
2624         self.BUTTON_ATCK2 = 0;
2625         self.BUTTON_ZOOM = 0;
2626         self.BUTTON_CROUCH = 0;
2627         self.BUTTON_HOOK = 0;
2628         self.BUTTON_INFO = 0;
2629         self.button8 = 0;
2630         self.BUTTON_CHAT = 0;
2631         self.BUTTON_USE = 0;
2632
2633         // if dead, just wait until we can respawn
2634         if (self.deadflag)
2635         {
2636                 if (self.deadflag == DEAD_DEAD)
2637                 {
2638                         self.BUTTON_JUMP = 1; // press jump to respawn
2639                         self.bot_strategytime = 0;
2640                 }
2641         }
2642
2643         // now call the current bot AI (havocbot for example)
2644         self.bot_ai();
2645 };
2646
2647 entity bot_strategytoken;
2648 float bot_strategytoken_taken;
2649 entity player_list;
2650 .entity nextplayer;
2651 void bot_relinkplayerlist()
2652 {
2653         local entity e;
2654         local entity prevbot;
2655         player_count = 0;
2656         currentbots = 0;
2657         player_list = e = findchainflags(flags, FL_CLIENT);
2658         bot_list = world;
2659         prevbot = world;
2660         while (e)
2661         {
2662                 player_count = player_count + 1;
2663                 e.nextplayer = e.chain;
2664                 if (clienttype(e) == CLIENTTYPE_BOT)
2665                 {
2666                         if (prevbot)
2667                                 prevbot.nextbot = e;
2668                         else
2669                         {
2670                                 bot_list = e;
2671                                 bot_list.nextbot = world;
2672                         }
2673                         prevbot = e;
2674                         currentbots = currentbots + 1;
2675                 }
2676                 e = e.chain;
2677         }
2678         dprint(strcat("relink: ", ftos(currentbots), " bots seen.\n"));
2679         bot_strategytoken = bot_list;
2680         bot_strategytoken_taken = TRUE;
2681 };
2682
2683 void() havocbot_setupbot;
2684 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam);
2685
2686 void bot_clientdisconnect()
2687 {
2688         if (clienttype(self) != CLIENTTYPE_BOT)
2689                 return;
2690         if(self.netname_freeme)
2691                 strunzone(self.netname_freeme);
2692         if(self.playermodel_freeme)
2693                 strunzone(self.playermodel_freeme);
2694         if(self.playerskin_freeme)
2695                 strunzone(self.playerskin_freeme);
2696         self.netname_freeme = string_null;
2697         self.playermodel_freeme = string_null;
2698         self.playerskin_freeme = string_null;
2699 }
2700
2701 void bot_clientconnect()
2702 {
2703         if (clienttype(self) != CLIENTTYPE_BOT)
2704                 return;
2705         self.bot_preferredcolors = self.clientcolors;
2706         self.bot_nextthink = time - random();
2707         self.lag_func = bot_lagfunc;
2708         self.isbot = TRUE;
2709         self.createdtime = self.nextthink;
2710
2711         if(!self.bot_config_loaded) // This is needed so team overrider doesn't break between matches
2712                 bot_setnameandstuff();
2713
2714         if(self.bot_forced_team==1)
2715                 self.team = COLOR_TEAM1;
2716         else if(self.bot_forced_team==2)
2717                 self.team = COLOR_TEAM2;
2718         else if(self.bot_forced_team==3)
2719                 self.team = COLOR_TEAM3;
2720         else if(self.bot_forced_team==4)
2721                 self.team = COLOR_TEAM4;
2722         else
2723                 JoinBestTeam(self, FALSE, TRUE);
2724
2725         havocbot_setupbot();
2726         self.bot_mouseskill=random()-0.5;
2727         self.bot_thinkskill=random()-0.5;
2728         self.bot_predictionskill=random()-0.5;
2729         self.bot_offsetskill=random()-0.5;
2730 };
2731
2732 entity bot_spawn()
2733 {
2734         local entity oldself, bot;
2735         bot = spawnclient();
2736         if (bot)
2737         {
2738                 currentbots = currentbots + 1;
2739                 oldself = self;
2740                 self = bot;
2741                 bot_setnameandstuff();
2742                 ClientConnect();
2743                 PutClientInServer();
2744                 self = oldself;
2745         }
2746         return bot;
2747 };
2748
2749 void CheckAllowedTeams(entity for_whom); void GetTeamCounts(entity other); float c1, c2, c3, c4;
2750 void bot_removefromlargestteam()
2751 {
2752         local float besttime, bestcount, thiscount;
2753         local entity best, head;
2754         CheckAllowedTeams(world);
2755         GetTeamCounts(world);
2756         head = findchainfloat(isbot, TRUE);
2757         if (!head)
2758                 return;
2759         best = head;
2760         besttime = head.createdtime;
2761         bestcount = 0;
2762         while (head)
2763         {
2764                 if(head.team == COLOR_TEAM1)
2765                         thiscount = c1;
2766                 else if(head.team == COLOR_TEAM2)
2767                         thiscount = c2;
2768                 else if(head.team == COLOR_TEAM3)
2769                         thiscount = c3;
2770                 else if(head.team == COLOR_TEAM4)
2771                         thiscount = c4;
2772                 else
2773                         thiscount = 0;
2774                 if (thiscount > bestcount)
2775                 {
2776                         bestcount = thiscount;
2777                         besttime = head.createdtime;
2778                         best = head;
2779                 }
2780                 else if (thiscount == bestcount && besttime < head.createdtime)
2781                 {
2782                         besttime = head.createdtime;
2783                         best = head;
2784                 }
2785                 head = head.chain;
2786         }
2787         currentbots = currentbots - 1;
2788         dropclient(best);
2789 };
2790
2791 void bot_removenewest()
2792 {
2793         local float besttime;
2794         local entity best, head;
2795
2796         if(teams_matter)
2797         {
2798                 bot_removefromlargestteam();
2799                 return;
2800         }
2801
2802         head = findchainfloat(isbot, TRUE);
2803         if (!head)
2804                 return;
2805         best = head;
2806         besttime = head.createdtime;
2807         while (head)
2808         {
2809                 if (besttime < head.createdtime)
2810                 {
2811                         besttime = head.createdtime;
2812                         best = head;
2813                 }
2814                 head = head.chain;
2815         }
2816         currentbots = currentbots - 1;
2817         dropclient(best);
2818 };
2819
2820 float botframe_waypointeditorlightningtime;
2821 void botframe_showwaypointlinks()
2822 {
2823         local entity player, head, w;
2824         if (time < botframe_waypointeditorlightningtime)
2825                 return;
2826         botframe_waypointeditorlightningtime = time + 0.5;
2827         player = find(world, classname, "player");
2828         while (player)
2829         {
2830                 if (!player.isbot)
2831                 if (player.flags & FL_ONGROUND || player.waterlevel > WATERLEVEL_NONE)
2832                 {
2833                         //navigation_testtracewalk = TRUE;
2834                         head = navigation_findnearestwaypoint(player, FALSE);
2835                 //      print("currently selected WP is ", etos(head), "\n");
2836                         //navigation_testtracewalk = FALSE;
2837                         if (head)
2838                         {
2839                                 w = head     ;if (w) te_lightning2(world, w.origin, player.origin);
2840                                 w = head.wp00;if (w) te_lightning2(world, w.origin, head.origin);
2841                                 w = head.wp01;if (w) te_lightning2(world, w.origin, head.origin);
2842                                 w = head.wp02;if (w) te_lightning2(world, w.origin, head.origin);
2843                                 w = head.wp03;if (w) te_lightning2(world, w.origin, head.origin);
2844                                 w = head.wp04;if (w) te_lightning2(world, w.origin, head.origin);
2845                                 w = head.wp05;if (w) te_lightning2(world, w.origin, head.origin);
2846                                 w = head.wp06;if (w) te_lightning2(world, w.origin, head.origin);
2847                                 w = head.wp07;if (w) te_lightning2(world, w.origin, head.origin);
2848                                 w = head.wp08;if (w) te_lightning2(world, w.origin, head.origin);
2849                                 w = head.wp09;if (w) te_lightning2(world, w.origin, head.origin);
2850                                 w = head.wp10;if (w) te_lightning2(world, w.origin, head.origin);
2851                                 w = head.wp11;if (w) te_lightning2(world, w.origin, head.origin);
2852                                 w = head.wp12;if (w) te_lightning2(world, w.origin, head.origin);
2853                                 w = head.wp13;if (w) te_lightning2(world, w.origin, head.origin);
2854                                 w = head.wp14;if (w) te_lightning2(world, w.origin, head.origin);
2855                                 w = head.wp15;if (w) te_lightning2(world, w.origin, head.origin);
2856                                 w = head.wp16;if (w) te_lightning2(world, w.origin, head.origin);
2857                                 w = head.wp17;if (w) te_lightning2(world, w.origin, head.origin);
2858                                 w = head.wp18;if (w) te_lightning2(world, w.origin, head.origin);
2859                                 w = head.wp19;if (w) te_lightning2(world, w.origin, head.origin);
2860                                 w = head.wp20;if (w) te_lightning2(world, w.origin, head.origin);
2861                                 w = head.wp21;if (w) te_lightning2(world, w.origin, head.origin);
2862                                 w = head.wp22;if (w) te_lightning2(world, w.origin, head.origin);
2863                                 w = head.wp23;if (w) te_lightning2(world, w.origin, head.origin);
2864                                 w = head.wp24;if (w) te_lightning2(world, w.origin, head.origin);
2865                                 w = head.wp25;if (w) te_lightning2(world, w.origin, head.origin);
2866                                 w = head.wp26;if (w) te_lightning2(world, w.origin, head.origin);
2867                                 w = head.wp27;if (w) te_lightning2(world, w.origin, head.origin);
2868                                 w = head.wp28;if (w) te_lightning2(world, w.origin, head.origin);
2869                                 w = head.wp29;if (w) te_lightning2(world, w.origin, head.origin);
2870                                 w = head.wp30;if (w) te_lightning2(world, w.origin, head.origin);
2871                                 w = head.wp31;if (w) te_lightning2(world, w.origin, head.origin);
2872                         }
2873                 }
2874                 player = find(player, classname, "player");
2875         }
2876 };
2877
2878 entity botframe_dangerwaypoint;
2879 void botframe_updatedangerousobjects(float maxupdate)
2880 {
2881         local entity head, bot_dodgelist;
2882         local vector m1, m2, v;
2883         local float c, d, danger;
2884         c = 0;
2885         bot_dodgelist = findchainfloat(bot_dodge, TRUE);
2886         botframe_dangerwaypoint = find(botframe_dangerwaypoint, classname, "waypoint");
2887         while (botframe_dangerwaypoint != world)
2888         {
2889                 danger = 0;
2890                 m1 = botframe_dangerwaypoint.mins;
2891                 m2 = botframe_dangerwaypoint.maxs;
2892                 head = bot_dodgelist;
2893                 while (head)
2894                 {
2895                         v = head.origin;
2896                         v_x = bound(m1_x, v_x, m2_x);
2897                         v_y = bound(m1_y, v_y, m2_y);
2898                         v_z = bound(m1_z, v_z, m2_z);
2899                         d = head.bot_dodgerating - vlen(head.origin - v);
2900                         if (d > 0)
2901                         {
2902                                 traceline(head.origin, v, TRUE, world);
2903                                 if (trace_fraction == 1)
2904                                         danger = danger + d;
2905                         }
2906                         head = head.chain;
2907                 }
2908                 botframe_dangerwaypoint.dmg = danger;
2909                 c = c + 1;
2910                 if (c >= maxupdate)
2911                         break;
2912                 botframe_dangerwaypoint = find(botframe_dangerwaypoint, classname, "waypoint");
2913         }
2914 };
2915
2916
2917 float botframe_spawnedwaypoints;
2918 float botframe_nextthink;
2919 float botframe_nextdangertime;
2920
2921 float autoskill_nextthink;
2922 .float totalfrags_lastcheck;
2923 void autoskill(float factor)
2924 {
2925         float bestbot;
2926         float bestplayer;
2927         entity head;
2928
2929         bestbot = -1;
2930         bestplayer = -1;
2931         FOR_EACH_PLAYER(head)
2932         {
2933                 if(clienttype(head) == CLIENTTYPE_REAL)
2934                         bestplayer = max(bestplayer, head.totalfrags - head.totalfrags_lastcheck);
2935                 else
2936                         bestbot = max(bestbot, head.totalfrags - head.totalfrags_lastcheck);
2937         }
2938
2939         dprint("autoskill: best player got ", ftos(bestplayer), ", ");
2940         dprint("best bot got ", ftos(bestbot), "; ");
2941         if(bestbot < 0 || bestplayer < 0)
2942         {
2943                 dprint("not doing anything\n");
2944                 // don't return, let it reset all counters below
2945         }
2946         else if(bestbot <= bestplayer * factor - 2)
2947         {
2948                 if(cvar("skill") < 17)
2949                 {
2950                         dprint("2 frags difference, increasing skill\n");
2951                         cvar_set("skill", ftos(cvar("skill") + 1));
2952                         bprint("^2SKILL UP!^7 Now at level ", ftos(cvar("skill")), "\n");
2953                 }
2954         }
2955         else if(bestbot >= bestplayer * factor + 2)
2956         {
2957                 if(cvar("skill") > 0)
2958                 {
2959                         dprint("2 frags difference, decreasing skill\n");
2960                         cvar_set("skill", ftos(cvar("skill") - 1));
2961                         bprint("^1SKILL DOWN!^7 Now at level ", ftos(cvar("skill")), "\n");
2962                 }
2963         }
2964         else
2965         {
2966                 dprint("not doing anything\n");
2967                 return;
2968                 // don't reset counters, wait for them to accumulate
2969         }
2970
2971         FOR_EACH_PLAYER(head)
2972                 head.totalfrags_lastcheck = head.totalfrags;
2973 }
2974
2975 float bot_cvar_nextthink;
2976 void bot_serverframe()
2977 {
2978         float realplayers, bots, activerealplayers;
2979         entity head;
2980
2981         if (intermission_running)
2982                 return;
2983
2984         if (time < 2)
2985                 return;
2986
2987         stepheightvec = cvar("sv_stepheight") * '0 0 1';
2988         bot_navigation_movemode = ((cvar("bot_navigation_ignoreplayers")) ? MOVE_NOMONSTERS : MOVE_NORMAL);
2989
2990         if(time > autoskill_nextthink)
2991         {
2992                 float a;
2993                 a = cvar("skill_auto");
2994                 if(a)
2995                         autoskill(a);
2996                 autoskill_nextthink = time + 5;
2997         }
2998
2999         activerealplayers = 0;
3000         realplayers = 0;
3001
3002         FOR_EACH_REALCLIENT(head)
3003         {
3004                 if(head.classname == "player" || g_lms || g_arena)
3005                         ++activerealplayers;
3006                 ++realplayers;
3007         }
3008
3009         // add/remove bots if needed to make sure there are at least
3010         // minplayers+bot_number, or remove all bots if no one is playing
3011         // But don't remove bots immediately on level change, as the real players
3012         // usually haven't rejoined yet
3013         bots_would_leave = FALSE;
3014         if ((realplayers || cvar("bot_join_empty") || (currentbots > 0 && time < 5)))
3015         {
3016                 float realminplayers, minplayers;
3017                 realminplayers = cvar("minplayers");
3018                 minplayers = max(0, floor(realminplayers));
3019
3020                 float realminbots, minbots;
3021                 if(cvar("bot_vs_human"))
3022                         realminbots = ceil(fabs(cvar("bot_vs_human")) * activerealplayers);
3023                 else
3024                         realminbots = cvar("bot_number");
3025                 minbots = max(0, floor(realminbots));
3026
3027                 bots = min(max(minbots, minplayers - activerealplayers), maxclients - realplayers);
3028                 if(bots > minbots)
3029                         bots_would_leave = TRUE;
3030         }
3031         else
3032         {
3033                 // if there are no players, remove bots
3034                 bots = 0;
3035         }
3036
3037         bot_ignore_bots = cvar("bot_ignore_bots");
3038
3039         // only add one bot per frame to avoid utter chaos
3040         if(time > botframe_nextthink)
3041         {
3042                 //dprint(ftos(bots), " ? ", ftos(currentbots), "\n");
3043                 while (currentbots < bots)
3044                 {
3045                         if (bot_spawn() == world)
3046                         {
3047                                 bprint("Can not add bot, server full.\n");
3048                                 botframe_nextthink = time + 10;
3049                                 break;
3050                         }
3051                 }
3052                 while (currentbots > bots)
3053                         bot_removenewest();
3054         }
3055
3056         if(botframe_spawnedwaypoints)
3057         {
3058                 if(cvar("waypoint_benchmark"))
3059                         localcmd("quit\n");
3060         }
3061
3062         if (currentbots > 0 || cvar("g_waypointeditor"))
3063         if (botframe_spawnedwaypoints)
3064         {
3065                 if(botframe_cachedwaypointlinks)
3066                 {
3067                         if(!botframe_loadedforcedlinks)
3068                                 waypoint_load_links_hardwired();
3069                 }
3070                 else
3071                 {
3072                         // TODO: Make this check cleaner
3073                         local entity wp = findchain(classname, "waypoint");
3074                         if(time - wp.nextthink > 10)
3075                                 waypoint_save_links();
3076                 }
3077         }
3078         else
3079         {
3080                 botframe_spawnedwaypoints = TRUE;
3081                 waypoint_loadall();
3082                 if(!waypoint_load_links())
3083                         waypoint_schedulerelinkall();
3084         }
3085
3086         if (bot_list)
3087         {
3088                 // cycle the goal token from one bot to the next each frame
3089                 // (this prevents them from all doing spawnfunc_waypoint searches on the same
3090                 //  frame, which causes choppy framerates)
3091                 if (bot_strategytoken_taken)
3092                 {
3093                         bot_strategytoken_taken = FALSE;
3094                         if (bot_strategytoken)
3095                                 bot_strategytoken = bot_strategytoken.nextbot;
3096                         if (!bot_strategytoken)
3097                                 bot_strategytoken = bot_list;
3098                 }
3099
3100                 if (botframe_nextdangertime < time)
3101                 {
3102                         local float interval;
3103                         interval = cvar("bot_ai_dangerdetectioninterval");
3104                         if (botframe_nextdangertime < time - interval * 1.5)
3105                                 botframe_nextdangertime = time;
3106                         botframe_nextdangertime = botframe_nextdangertime + interval;
3107                         botframe_updatedangerousobjects(cvar("bot_ai_dangerdetectionupdates"));
3108                 }
3109         }
3110
3111         if (cvar("g_waypointeditor"))
3112                 botframe_showwaypointlinks();
3113
3114         if(time > bot_cvar_nextthink)
3115         {
3116                 if(currentbots>1)
3117                         bot_custom_weapon_priority_setup();
3118                 bot_cvar_nextthink = time + 5;
3119         }
3120 };