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