change all function declarations (except builtins and data types) to ANSI C-like...
[divverent/nexuiz.git] / data / qcsrc / server / bots.qc
1 // rough simulation of walking from one point to another to test if a path
2 // can be traveled, used by havocbot
3
4
5 vector stepheightvec;
6 float navigation_testtracewalk;
7 float tracewalk(entity e, vector start, vector m1, vector m2, vector end, float movemode)
8 {
9         local vector org;
10         local vector move;
11         local vector dir;
12         local float dist;
13         local float totaldist;
14         local float stepdist;
15         local float yaw;
16         local float ignorehazards;
17         if (navigation_testtracewalk)
18         {
19                 if (navigation_testtracewalk > 1)
20                         dprint("tracewalk: ");
21                 //te_wizspike(start);
22                 //te_knightspike(end);
23                 //te_lightning2(world, start, end);
24         }
25         move = end - start;
26         move_z = 0;
27         org = start;
28         dist = totaldist = vlen(move);
29         dir = normalize(move);
30         stepdist = 32;
31         ignorehazards = FALSE;
32         //self.angles = vectoangles(dir);
33         traceline(start, start, MOVE_NORMAL, e);
34         if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
35                 ignorehazards = TRUE;
36         tracebox(start, m1, m2, start, MOVE_NOMONSTERS, e);
37         if (trace_startsolid)
38         {
39                 // failed - bad start
40                 if (navigation_testtracewalk)
41                 {
42                         if (navigation_testtracewalk > 1)
43                                 dprint("bad-start\n");
44                         te_knightspike(start);
45                 }
46                 return 0;
47         }
48         yaw = vectoyaw(move);
49         move = end - org;
50         while (1)
51         {
52                 if (boxesoverlap(end, end, org + m1 + '-1 -1 -1', org + m2 + '1 1 1'))
53                 {
54                         if (navigation_testtracewalk)
55                         {
56                                 if (navigation_testtracewalk > 1)
57                                         dprint("success\n");
58                                 te_wizspike(org);
59                         }
60                         // succeeded
61                         return 1;
62                 }
63                 if (dist <= 0)
64                         break;
65                 if (navigation_testtracewalk)
66                 {
67                         //dprint("trying ");
68                         //te_gunshot(org);
69                         particle(org, '0 0 0', 104, 8);
70                 }
71                 if (stepdist > dist)
72                         stepdist = dist;
73                 dist = dist - stepdist;
74                 traceline(org, org, MOVE_NORMAL, e);
75                 if (!ignorehazards)
76                 {
77                         if (trace_dpstartcontents & (DPCONTENTS_SLIME | DPCONTENTS_LAVA))
78                         {
79                                 if (navigation_testtracewalk)
80                                 {
81                                         if (navigation_testtracewalk > 1)
82                                                 dprint("hazard\n");
83                                         te_gunshot(org);
84                                 }
85                                 // hazards blocking path
86                                 return 0;
87                         }
88                 }
89                 if (trace_dpstartcontents & DPCONTENTS_LIQUIDSMASK)
90                 {
91                         move = normalize(end - org);
92                         tracebox(org, m1, m2, org + move * stepdist, movemode, e);
93                         if (trace_fraction < 1)
94                         {
95                                 if (navigation_testtracewalk)
96                                 {
97                                         if (navigation_testtracewalk > 1)
98                                                 dprint("swimming-hit-something\n");
99                                         //particle(org, move * 64, 104, 4);
100                                         te_gunshot(org);
101                                 }
102                                 // failed
103                                 return 0;
104                         }
105                         org = trace_endpos;
106                 }
107                 else
108                 {
109                         move = dir * stepdist + org;
110                         tracebox(org, m1, m2, move, movemode, e);
111                         if (trace_fraction < 1)
112                         {
113                                 tracebox(org + stepheightvec, m1, m2, move + stepheightvec, movemode, e);
114                                 if (trace_fraction < 1 || trace_startsolid)
115                                 {
116                                         if (navigation_testtracewalk)
117                                         {
118                                                 if (navigation_testtracewalk > 1)
119                                                         dprint("hit-something\n");
120                                                 //move = normalize(end - org);
121                                                 //particle(org, move * 64, 104, 4);
122                                                 te_gunshot(org);
123                                         }
124                                         // failed
125                                         return 0;
126                                 }
127                         }
128                         move = trace_endpos;
129                         // trace down from stepheight as far as possible and move there,
130                         // if this starts in solid we try again without the stepup, and
131                         // if that also fails we assume it is a wall
132                         // (this is the same logic as the Quake walkmove function used)
133                         tracebox(move, m1, m2, move + '0 0 -65536', movemode, e);
134                         /*
135                         if (trace_startsolid)
136                         {
137                                 tracebox(move, m1, m2, move + '0 0 -65536', FALSE, e);
138                                 if (trace_startsolid)
139                                 {
140                                         if (navigation_testtracewalk)
141                                         {
142                                                 if (navigation_testtracewalk > 1)
143                                                         dprint("hit-something\n");
144                                                 //move = normalize(end - org);
145                                                 //particle(org, move * 64, 104, 4);
146                                                 te_knightspike(org);
147                                         }
148                                         // failed
149                                         return 0;
150                                 }
151                         }
152                         */
153                         // moved successfully
154                         if (navigation_testtracewalk > 1)
155                                 dprint("moved ");
156                         org = trace_endpos;
157                 }
158         }
159         if (navigation_testtracewalk)
160         {
161                 if (navigation_testtracewalk > 1)
162                         dprint("wrong-place\n");
163                 te_knightspike(org);
164                 //te_gunshot(end);
165         }
166         // moved but didn't arrive at the intended destination
167         return 0;
168 };
169
170
171 // grenade tracing to decide the best pitch to fire at
172
173 entity tracetossent;
174 entity tracetossfaketarget;
175
176 // traces multiple trajectories to find one that will impact the target
177 // 'end' vector is the place it aims for,
178 // returns TRUE only if it hit targ (don't target non-solid entities)
179 vector findtrajectory_velocity;
180 float findtrajectorywithleading(vector org, vector m1, vector m2, entity targ, float shotspeed, float shotspeedupward, float maxtime, float shotdelay, entity ignore)
181 {
182         local float c, savesolid, shottime;
183         local vector dir, end, v;
184         if (shotspeed < 1)
185                 return FALSE; // could cause division by zero if calculated
186         if (targ.solid < SOLID_BBOX) // SOLID_NOT and SOLID_TRIGGER
187                 return FALSE; // could never hit it
188         if (!tracetossent)
189                 tracetossent = spawn();
190         tracetossent.owner = ignore;
191         setsize(tracetossent, m1, m2);
192         savesolid = targ.solid;
193         targ.solid = SOLID_NOT;
194         shottime = ((vlen(targ.origin - org) / shotspeed) + shotdelay);
195         v = targ.velocity * shottime + targ.origin;
196         tracebox(targ.origin, targ.mins, targ.maxs, v, FALSE, targ);
197         v = trace_endpos;
198         end = v + (targ.mins + targ.maxs) * 0.5;
199         if ((vlen(end - org) / shotspeed + 0.2) > maxtime)
200         {
201                 // out of range
202                 targ.solid = savesolid;
203                 return FALSE;
204         }
205
206         if (!tracetossfaketarget)
207                 tracetossfaketarget = spawn();
208         tracetossfaketarget.solid = savesolid;
209         tracetossfaketarget.movetype = targ.movetype;
210         setmodel(tracetossfaketarget, targ.model); // no low precision
211         tracetossfaketarget.model = targ.model;
212         tracetossfaketarget.modelindex = targ.modelindex;
213         setsize(tracetossfaketarget, targ.mins, targ.maxs);
214         setorigin(tracetossfaketarget, v);
215
216         c = 0;
217         dir = normalize(end - org);
218         while (c < 10) // 10 traces
219         {
220                 setorigin(tracetossent, org); // reset
221                 tracetossent.velocity = findtrajectory_velocity = normalize(dir) * shotspeed + shotspeedupward * '0 0 1';
222                 tracetoss(tracetossent, ignore); // love builtin functions...
223                 if (trace_ent == tracetossfaketarget) // done
224                 {
225                         targ.solid = savesolid;
226
227                         // make it disappear
228                         tracetossfaketarget.solid = SOLID_NOT;
229                         tracetossfaketarget.movetype = MOVETYPE_NONE;
230                         tracetossfaketarget.model = "";
231                         tracetossfaketarget.modelindex = 0;
232                         // relink to remove it from physics considerations
233                         setorigin(tracetossfaketarget, v);
234
235                         return TRUE;
236                 }
237                 dir_z = dir_z + 0.1; // aim up a little more
238                 c = c + 1;
239         }
240         targ.solid = savesolid;
241
242         // make it disappear
243         tracetossfaketarget.solid = SOLID_NOT;
244         tracetossfaketarget.movetype = MOVETYPE_NONE;
245         tracetossfaketarget.model = "";
246         tracetossfaketarget.modelindex = 0;
247         // relink to remove it from physics considerations
248         setorigin(tracetossfaketarget, v);
249
250         // leave a valid one even if it won't reach
251         findtrajectory_velocity = normalize(end - org) * shotspeed + shotspeedupward * '0 0 1';
252         return FALSE;
253 };
254
255
256
257 // lag simulation
258
259 .void(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4) lag_func;
260
261 // upto 5 queued messages
262 .float lag1_time;
263 .float lag1_float1;
264 .float lag1_float2;
265 .entity lag1_entity1;
266 .vector lag1_vec1;
267 .vector lag1_vec2;
268 .vector lag1_vec3;
269 .vector lag1_vec4;
270
271 .float lag2_time;
272 .float lag2_float1;
273 .float lag2_float2;
274 .entity lag2_entity1;
275 .vector lag2_vec1;
276 .vector lag2_vec2;
277 .vector lag2_vec3;
278 .vector lag2_vec4;
279
280 .float lag3_time;
281 .float lag3_float1;
282 .float lag3_float2;
283 .entity lag3_entity1;
284 .vector lag3_vec1;
285 .vector lag3_vec2;
286 .vector lag3_vec3;
287 .vector lag3_vec4;
288
289 .float lag4_time;
290 .float lag4_float1;
291 .float lag4_float2;
292 .entity lag4_entity1;
293 .vector lag4_vec1;
294 .vector lag4_vec2;
295 .vector lag4_vec3;
296 .vector lag4_vec4;
297
298 .float lag5_time;
299 .float lag5_float1;
300 .float lag5_float2;
301 .entity lag5_entity1;
302 .vector lag5_vec1;
303 .vector lag5_vec2;
304 .vector lag5_vec3;
305 .vector lag5_vec4;
306
307 void lag_update()
308 {
309         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;}
310         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;}
311         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;}
312         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;}
313         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;}
314 };
315
316 float lag_additem(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4)
317 {
318         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;}
319         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;}
320         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;}
321         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;}
322         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;}
323         // no room for it (what is the best thing to do here??)
324         return FALSE;
325 };
326
327
328 // Random skill system
329 .float bot_thinkskill;
330 .float bot_mouseskill;
331 .float bot_predictionskill;
332 .float bot_offsetskill;
333
334
335 // spawnfunc_waypoint navigation system
336
337 // itemscore = (howmuchmoreIwant / howmuchIcanwant) / itemdistance
338 // waypointscore = 0.7 / waypointdistance
339
340 .entity wp00, wp01, wp02, wp03, wp04, wp05, wp06, wp07;
341 .entity wp08, wp09, wp10, wp11, wp12, wp13, wp14, wp15;
342 .entity wp16, wp17, wp18, wp19, wp20, wp21, wp22, wp23, wp24, wp25, wp26, wp27, wp28, wp29, wp30, wp31;
343 .float wp00mincost, wp01mincost, wp02mincost, wp03mincost, wp04mincost, wp05mincost, wp06mincost, wp07mincost;
344 .float wp08mincost, wp09mincost, wp10mincost, wp11mincost, wp12mincost, wp13mincost, wp14mincost, wp15mincost;
345 .float wp16mincost, wp17mincost, wp18mincost, wp19mincost, wp20mincost, wp21mincost, wp22mincost, wp23mincost, wp24mincost, wp25mincost, wp26mincost, wp27mincost, wp28mincost, wp29mincost, wp30mincost, wp31mincost;
346 .float wpfire, wpcost, wpconsidered;
347 .float wpisbox;
348 .float wpflags;
349 .vector wpnearestpoint;
350
351 // stack of current goals (the last one of which may be an item or other
352 // desirable object, the rest are typically waypoints to reach it)
353 .entity goalcurrent, goalstack01, goalstack02, goalstack03;
354 .entity goalstack04, goalstack05, goalstack06, goalstack07;
355 .entity goalstack08, goalstack09, goalstack10, goalstack11;
356 .entity goalstack12, goalstack13, goalstack14, goalstack15;
357 .entity goalstack16, goalstack17, goalstack18, goalstack19;
358 .entity goalstack20, goalstack21, goalstack22, goalstack23;
359 .entity goalstack24, goalstack25, goalstack26, goalstack27;
360 .entity goalstack28, goalstack29, goalstack30, goalstack31;
361
362 .entity nearestwaypoint;
363 .float nearestwaypointtimeout;
364
365 // used during navigation_goalrating_begin/end sessions
366 float navigation_bestrating;
367 entity navigation_bestgoal;
368
369
370
371
372
373 /////////////////////////////////////////////////////////////////////////////
374 // spawnfunc_waypoint management
375 /////////////////////////////////////////////////////////////////////////////
376
377 // waypoints with this flag are not saved, they are automatically generated
378 // waypoints like jump pads, teleporters, and items
379 float WAYPOINTFLAG_GENERATED = 8388608;
380 float WAYPOINTFLAG_ITEM = 4194304;
381 float WAYPOINTFLAG_TELEPORT = 2097152;
382 float WAYPOINTFLAG_NORELINK = 1048576;
383
384 // add a new link to the spawnfunc_waypoint, replacing the furthest link it already has
385 void waypoint_addlink(entity from, entity to)
386 {
387         local float c;
388
389         if (from == to)
390                 return;
391         if (from.wpflags & WAYPOINTFLAG_NORELINK)
392                 return;
393
394         if (from.wp00 == to) return;if (from.wp01 == to) return;if (from.wp02 == to) return;if (from.wp03 == to) return;
395         if (from.wp04 == to) return;if (from.wp05 == to) return;if (from.wp06 == to) return;if (from.wp07 == to) return;
396         if (from.wp08 == to) return;if (from.wp09 == to) return;if (from.wp10 == to) return;if (from.wp11 == to) return;
397         if (from.wp12 == to) return;if (from.wp13 == to) return;if (from.wp14 == to) return;if (from.wp15 == to) return;
398         if (from.wp16 == to) return;if (from.wp17 == to) return;if (from.wp18 == to) return;if (from.wp19 == to) return;
399         if (from.wp20 == to) return;if (from.wp21 == to) return;if (from.wp22 == to) return;if (from.wp23 == to) return;
400         if (from.wp24 == to) return;if (from.wp25 == to) return;if (from.wp26 == to) return;if (from.wp27 == to) return;
401         if (from.wp28 == to) return;if (from.wp29 == to) return;if (from.wp30 == to) return;if (from.wp31 == to) return;
402
403         if (to.wpisbox || from.wpisbox)
404         {
405                 // if either is a box we have to find the nearest points on them to
406                 // calculate the distance properly
407                 local vector v1, v2, m1, m2;
408                 v1 = from.origin;
409                 m1 = to.absmin;
410                 m2 = to.absmax;
411                 v1_x = bound(m1_x, v1_x, m2_x);
412                 v1_y = bound(m1_y, v1_y, m2_y);
413                 v1_z = bound(m1_z, v1_z, m2_z);
414                 v2 = to.origin;
415                 m1 = from.absmin;
416                 m2 = from.absmax;
417                 v2_x = bound(m1_x, v2_x, m2_x);
418                 v2_y = bound(m1_y, v2_y, m2_y);
419                 v2_z = bound(m1_z, v2_z, m2_z);
420                 v2 = to.origin;
421                 c = vlen(v2 - v1);
422         }
423         else
424                 c = vlen(to.origin - from.origin);
425
426         if (from.wp31mincost < c) return;
427         if (from.wp30mincost < c) {from.wp31 = to;from.wp31mincost = c;return;} from.wp31 = from.wp30;from.wp31mincost = from.wp30mincost;
428         if (from.wp29mincost < c) {from.wp30 = to;from.wp30mincost = c;return;} from.wp30 = from.wp29;from.wp30mincost = from.wp29mincost;
429         if (from.wp28mincost < c) {from.wp29 = to;from.wp29mincost = c;return;} from.wp29 = from.wp28;from.wp29mincost = from.wp28mincost;
430         if (from.wp27mincost < c) {from.wp28 = to;from.wp28mincost = c;return;} from.wp28 = from.wp27;from.wp28mincost = from.wp27mincost;
431         if (from.wp26mincost < c) {from.wp27 = to;from.wp27mincost = c;return;} from.wp27 = from.wp26;from.wp27mincost = from.wp26mincost;
432         if (from.wp25mincost < c) {from.wp26 = to;from.wp26mincost = c;return;} from.wp26 = from.wp25;from.wp26mincost = from.wp25mincost;
433         if (from.wp24mincost < c) {from.wp25 = to;from.wp25mincost = c;return;} from.wp25 = from.wp24;from.wp25mincost = from.wp24mincost;
434         if (from.wp23mincost < c) {from.wp24 = to;from.wp24mincost = c;return;} from.wp24 = from.wp23;from.wp24mincost = from.wp23mincost;
435         if (from.wp22mincost < c) {from.wp23 = to;from.wp23mincost = c;return;} from.wp23 = from.wp22;from.wp23mincost = from.wp22mincost;
436         if (from.wp21mincost < c) {from.wp22 = to;from.wp22mincost = c;return;} from.wp22 = from.wp21;from.wp22mincost = from.wp21mincost;
437         if (from.wp20mincost < c) {from.wp21 = to;from.wp21mincost = c;return;} from.wp21 = from.wp20;from.wp21mincost = from.wp20mincost;
438         if (from.wp19mincost < c) {from.wp20 = to;from.wp20mincost = c;return;} from.wp20 = from.wp19;from.wp20mincost = from.wp19mincost;
439         if (from.wp18mincost < c) {from.wp19 = to;from.wp19mincost = c;return;} from.wp19 = from.wp18;from.wp19mincost = from.wp18mincost;
440         if (from.wp17mincost < c) {from.wp18 = to;from.wp18mincost = c;return;} from.wp18 = from.wp17;from.wp18mincost = from.wp17mincost;
441         if (from.wp16mincost < c) {from.wp17 = to;from.wp17mincost = c;return;} from.wp17 = from.wp16;from.wp17mincost = from.wp16mincost;
442         if (from.wp15mincost < c) {from.wp16 = to;from.wp16mincost = c;return;} from.wp16 = from.wp15;from.wp16mincost = from.wp15mincost;
443         if (from.wp14mincost < c) {from.wp15 = to;from.wp15mincost = c;return;} from.wp15 = from.wp14;from.wp15mincost = from.wp14mincost;
444         if (from.wp13mincost < c) {from.wp14 = to;from.wp14mincost = c;return;} from.wp14 = from.wp13;from.wp14mincost = from.wp13mincost;
445         if (from.wp12mincost < c) {from.wp13 = to;from.wp13mincost = c;return;} from.wp13 = from.wp12;from.wp13mincost = from.wp12mincost;
446         if (from.wp11mincost < c) {from.wp12 = to;from.wp12mincost = c;return;} from.wp12 = from.wp11;from.wp12mincost = from.wp11mincost;
447         if (from.wp10mincost < c) {from.wp11 = to;from.wp11mincost = c;return;} from.wp11 = from.wp10;from.wp11mincost = from.wp10mincost;
448         if (from.wp09mincost < c) {from.wp10 = to;from.wp10mincost = c;return;} from.wp10 = from.wp09;from.wp10mincost = from.wp09mincost;
449         if (from.wp08mincost < c) {from.wp09 = to;from.wp09mincost = c;return;} from.wp09 = from.wp08;from.wp09mincost = from.wp08mincost;
450         if (from.wp07mincost < c) {from.wp08 = to;from.wp08mincost = c;return;} from.wp08 = from.wp07;from.wp08mincost = from.wp07mincost;
451         if (from.wp06mincost < c) {from.wp07 = to;from.wp07mincost = c;return;} from.wp07 = from.wp06;from.wp07mincost = from.wp06mincost;
452         if (from.wp05mincost < c) {from.wp06 = to;from.wp06mincost = c;return;} from.wp06 = from.wp05;from.wp06mincost = from.wp05mincost;
453         if (from.wp04mincost < c) {from.wp05 = to;from.wp05mincost = c;return;} from.wp05 = from.wp04;from.wp05mincost = from.wp04mincost;
454         if (from.wp03mincost < c) {from.wp04 = to;from.wp04mincost = c;return;} from.wp04 = from.wp03;from.wp04mincost = from.wp03mincost;
455         if (from.wp02mincost < c) {from.wp03 = to;from.wp03mincost = c;return;} from.wp03 = from.wp02;from.wp03mincost = from.wp02mincost;
456         if (from.wp01mincost < c) {from.wp02 = to;from.wp02mincost = c;return;} from.wp02 = from.wp01;from.wp02mincost = from.wp01mincost;
457         if (from.wp00mincost < c) {from.wp01 = to;from.wp01mincost = c;return;} from.wp01 = from.wp00;from.wp01mincost = from.wp00mincost;
458         from.wp00 = to;from.wp00mincost = c;return;
459 };
460
461 // relink this spawnfunc_waypoint
462 // (precompile a list of all reachable waypoints from this spawnfunc_waypoint)
463 // (SLOW!)
464 void waypoint_think()
465 {
466         local entity e;
467         local vector sv, sm1, sm2, ev, em1, em2, dv;
468         //dprint("waypoint_think wpisbox = ", ftos(self.wpisbox), "\n");
469         sm1 = self.origin + self.mins;
470         sm2 = self.origin + self.maxs;
471         e = find(world, classname, "waypoint");
472         stepheightvec = cvar("sv_stepheight") * '0 0 1';
473         while (e)
474         {
475                 if (boxesoverlap(self.absmin, self.absmax, e.absmin, e.absmax))
476                 {
477                         waypoint_addlink(self, e);
478                         waypoint_addlink(e, self);
479                 }
480                 else
481                 {
482                         sv = e.origin;
483                         sv_x = bound(sm1_x, sv_x, sm2_x);
484                         sv_y = bound(sm1_y, sv_y, sm2_y);
485                         sv_z = bound(sm1_z, sv_z, sm2_z);
486                         ev = self.origin;
487                         em1 = e.origin + e.mins;
488                         em2 = e.origin + e.maxs;
489                         ev_x = bound(em1_x, ev_x, em2_x);
490                         ev_y = bound(em1_y, ev_y, em2_y);
491                         ev_z = bound(em1_z, ev_z, em2_z);
492                         dv = ev - sv;
493                         dv_z = 0;
494                         if (vlen(dv) < 1050) // max search distance in XY
495                         {
496                                 navigation_testtracewalk = 0;
497                                 if (!self.wpisbox)
498                                 {
499                                         tracebox(sv - PL_MIN_z * '0 0 1', PL_MIN, PL_MAX, sv, FALSE, self);
500                                         if (!trace_startsolid)
501                                         {
502                                                 //dprint("sv deviation", vtos(trace_endpos - sv), "\n");
503                                                 sv = trace_endpos + '0 0 1';
504                                         }
505                                 }
506                                 if (!e.wpisbox)
507                                 {
508                                         tracebox(ev - PL_MIN_z * '0 0 1', PL_MIN, PL_MAX, ev, FALSE, e);
509                                         if (!trace_startsolid)
510                                         {
511                                                 //dprint("ev deviation", vtos(trace_endpos - ev), "\n");
512                                                 ev = trace_endpos + '0 0 1';
513                                         }
514                                 }
515                                 //traceline(self.origin, e.origin, FALSE, world);
516                                 //if (trace_fraction == 1)
517                                 if (!self.wpisbox)
518                                 if (tracewalk(self, sv, PL_MIN, PL_MAX, ev, MOVE_NOMONSTERS))
519                                         waypoint_addlink(self, e);
520                                 if (!e.wpisbox)
521                                 if (tracewalk(e, ev, PL_MIN, PL_MAX, sv, MOVE_NOMONSTERS))
522                                         waypoint_addlink(e, self);
523                         }
524                 }
525                 e = find(e, classname, "waypoint");
526         }
527         navigation_testtracewalk = 0;
528 };
529
530 void waypoint_clearlinks(entity wp)
531 {
532         // clear links to other waypoints
533         local float f;
534         f = 10000000;
535         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;
536         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;
537         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;
538         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;
539 };
540
541 // tell a spawnfunc_waypoint to relink
542 void waypoint_schedulerelink(entity wp)
543 {
544         if (wp == world)
545                 return;
546         // TODO: add some sort of visible box in edit mode for box waypoints
547         if (cvar("g_waypointeditor"))
548         {
549                 local vector m1, m2;
550                 m1 = wp.mins;
551                 m2 = wp.maxs;
552                 setmodel(wp, "models/runematch/rune.mdl"); wp.effects = EF_LOWPRECISION;
553                 setsize(wp, m1, m2);
554                 if (wp.wpflags & WAYPOINTFLAG_ITEM)
555                         wp.colormod = '1 0 0';
556                 else if (wp.wpflags & WAYPOINTFLAG_GENERATED)
557                         wp.colormod = '1 1 0';
558                 else
559                         wp.colormod = '1 1 1';
560         }
561         else
562                 wp.model = "";
563         wp.wpisbox = vlen(wp.size) > 0;
564         wp.enemy = world;
565         wp.owner = world;
566         if (!(wp.wpflags & WAYPOINTFLAG_NORELINK))
567                 waypoint_clearlinks(wp);
568         // schedule an actual relink on next frame
569         wp.think = waypoint_think;
570         wp.nextthink = time;
571         wp.effects = EF_LOWPRECISION;
572 }
573
574 // create a new spawnfunc_waypoint and automatically link it to other waypoints, and link
575 // them back to it as well
576 // (suitable for spawnfunc_waypoint editor)
577 entity waypoint_spawn(vector m1, vector m2, float f)
578 {
579         local entity w;
580         local vector org;
581         w = find(world, classname, "waypoint");
582         while (w)
583         {
584                 // if a matching spawnfunc_waypoint already exists, don't add a duplicate
585                 if (boxesoverlap(m1, m2, w.absmin, w.absmax))
586                         return w;
587                 w = find(w, classname, "waypoint");
588         }
589         w = spawn();
590         w.classname = "waypoint";
591         w.wpflags = f;
592         setorigin(w, (m1 + m2) * 0.5);
593         setsize(w, m1 - w.origin, m2 - w.origin);
594         if (vlen(w.size) > 0)
595                 w.wpisbox = TRUE;
596
597         if(!(f & WAYPOINTFLAG_GENERATED))
598         if(!w.wpisbox)
599         {
600                 traceline(w.origin + '0 0 1', w.origin + PL_MIN_z * '0 0 1' - '0 0 1', MOVE_NOMONSTERS, w);
601                 if (trace_fraction < 1)
602                         setorigin(w, trace_endpos - PL_MIN_z * '0 0 1');
603
604                 // check if the start position is stuck
605                 tracebox(w.origin, PL_MIN + '-1 -1 -1', PL_MAX + '1 1 1', w.origin, MOVE_NOMONSTERS, w);
606                 if (trace_startsolid)
607                 {
608                         org = w.origin + '0 0 26';
609                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
610                         if(trace_startsolid)
611                         {
612                                 org = w.origin + '2 2 2';
613                                 tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
614                                 if(trace_startsolid)
615                                 {
616                                         org = w.origin + '-2 -2 2';
617                                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
618                                         if(trace_startsolid)
619                                         {
620                                                 org = w.origin + '-2 2 2';
621                                                 tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
622                                                 if(trace_startsolid)
623                                                 {
624                                                         org = w.origin + '2 -2 2';
625                                                         tracebox(org, PL_MIN, PL_MAX, w.origin, MOVE_WORLDONLY, w);
626                                                         if(trace_startsolid)
627                                                         {
628                                                                 // this WP is in solid, refuse it
629                                                                 dprint("Killed a waypoint that was stuck in solid at ", vtos(org), "\n");
630                                                                 remove(w);
631                                                                 return world;
632                                                         }
633                                                 }
634                                         }
635                                 }
636                         }
637                         setorigin(w, org * 0.05 + trace_endpos * 0.95); // don't trust the trace fully
638                 }
639
640                 tracebox(w.origin, PL_MIN, PL_MAX, w.origin - '0 0 128', MOVE_WORLDONLY, w);
641                 if(trace_startsolid)
642                 {
643                         dprint("Killed a waypoint that was stuck in solid ", vtos(w.origin), "\n");
644                         remove(w);
645                         return world;
646                 }
647                 if (!trace_inwater)
648                 {
649                         if(trace_fraction == 1)
650                         {
651                                 dprint("Killed a waypoint that was stuck in air at ", vtos(w.origin), "\n");
652                                 remove(w);
653                                 return world;
654                         }
655                         trace_endpos_z += 0.1; // don't trust the trace fully
656 //                      dprint("Moved waypoint at ", vtos(w.origin), " by ", ftos(vlen(w.origin - trace_endpos)));
657 //                      dprint(" direction: ", vtos((trace_endpos - w.origin)), "\n");
658                         setorigin(w, trace_endpos);
659                 }
660         }
661
662         waypoint_clearlinks(w);
663         //waypoint_schedulerelink(w);
664         return w;
665 };
666
667 // spawnfunc_waypoint map entity
668 void spawnfunc_waypoint()
669 {
670         setorigin(self, self.origin);
671         // schedule a relink after other waypoints have had a chance to spawn
672         waypoint_clearlinks(self);
673         //waypoint_schedulerelink(self);
674 };
675
676 // remove a spawnfunc_waypoint, and schedule all neighbors to relink
677 void waypoint_remove(entity e)
678 {
679         // tell all linked waypoints that they need to relink
680         waypoint_schedulerelink(e.wp00);
681         waypoint_schedulerelink(e.wp01);
682         waypoint_schedulerelink(e.wp02);
683         waypoint_schedulerelink(e.wp03);
684         waypoint_schedulerelink(e.wp04);
685         waypoint_schedulerelink(e.wp05);
686         waypoint_schedulerelink(e.wp06);
687         waypoint_schedulerelink(e.wp07);
688         waypoint_schedulerelink(e.wp08);
689         waypoint_schedulerelink(e.wp09);
690         waypoint_schedulerelink(e.wp10);
691         waypoint_schedulerelink(e.wp11);
692         waypoint_schedulerelink(e.wp12);
693         waypoint_schedulerelink(e.wp13);
694         waypoint_schedulerelink(e.wp14);
695         waypoint_schedulerelink(e.wp15);
696         waypoint_schedulerelink(e.wp16);
697         waypoint_schedulerelink(e.wp17);
698         waypoint_schedulerelink(e.wp18);
699         waypoint_schedulerelink(e.wp19);
700         waypoint_schedulerelink(e.wp20);
701         waypoint_schedulerelink(e.wp21);
702         waypoint_schedulerelink(e.wp22);
703         waypoint_schedulerelink(e.wp23);
704         waypoint_schedulerelink(e.wp24);
705         waypoint_schedulerelink(e.wp25);
706         waypoint_schedulerelink(e.wp26);
707         waypoint_schedulerelink(e.wp27);
708         waypoint_schedulerelink(e.wp28);
709         waypoint_schedulerelink(e.wp29);
710         waypoint_schedulerelink(e.wp30);
711         waypoint_schedulerelink(e.wp31);
712         // and now remove the spawnfunc_waypoint
713         remove(e);
714 };
715
716 // empties the map of waypoints
717 void waypoint_removeall()
718 {
719         local entity head, next;
720         head = findchain(classname, "waypoint");
721         while (head)
722         {
723                 next = head.chain;
724                 remove(head);
725                 head = next;
726         }
727 };
728
729 // tell all waypoints to relink
730 // (is this useful at all?)
731 void waypoint_schedulerelinkall()
732 {
733         local entity head;
734         head = findchain(classname, "waypoint");
735         while (head)
736         {
737                 waypoint_schedulerelink(head);
738                 head = head.chain;
739         }
740 };
741
742 // save waypoints to gamedir/data/maps/mapname.waypoints
743 // TODO: support saving wayboxes
744 void waypoint_saveall()
745 {
746         local string filename, s;
747         local float file, c;
748         local entity w;
749         filename = strcat("maps/", mapname);
750         filename = strcat(filename, ".waypoints");
751         file = fopen(filename, FILE_WRITE);
752         if (file >= 0)
753         {
754                 c = 0;
755                 w = findchain(classname, "waypoint");
756                 while (w)
757                 {
758                         if (!(w.wpflags & WAYPOINTFLAG_GENERATED))
759                         {
760                                 s = strcat(vtos(w.origin + w.mins), "\n");
761                                 s = strcat(s, vtos(w.origin + w.maxs));
762                                 s = strcat(s, "\n");
763                                 s = strcat(s, ftos(w.wpflags));
764                                 s = strcat(s, "\n");
765                                 fputs(file, s);
766                                 c = c + 1;
767                         }
768                         w = w.chain;
769                 }
770                 fclose(file);
771                 bprint("saved ");
772                 bprint(ftos(c));
773                 bprint(" waypoints to maps/");
774                 bprint(mapname);
775                 bprint(".waypoints\n");
776         }
777         else
778         {
779                 bprint("waypoint save to ");
780                 bprint(filename);
781                 bprint(" failed\n");
782         }
783 };
784
785 // load waypoints from file
786 float waypoint_loadall()
787 {
788         local string filename, s;
789         local float file, cwp, cwb, fl;
790         local vector m1, m2;
791         cwp = 0;
792         cwb = 0;
793         filename = strcat("maps/", mapname);
794         filename = strcat(filename, ".waypoints");
795         file = fopen(filename, FILE_READ);
796         if (file >= 0)
797         {
798                 while (1)
799                 {
800                         s = fgets(file);
801                         if (!s)
802                                 break;
803                         m1 = stov(s);
804                         s = fgets(file);
805                         if (!s)
806                                 break;
807                         m2 = stov(s);
808                         s = fgets(file);
809                         if (!s)
810                                 break;
811                         fl = stof(s);
812                         waypoint_spawn(m1, m2, fl);
813                         if (m1 == m2)
814                                 cwp = cwp + 1;
815                         else
816                                 cwb = cwb + 1;
817                 }
818                 fclose(file);
819                 dprint("loaded ");
820                 dprint(ftos(cwp));
821                 dprint(" waypoints and ");
822                 dprint(ftos(cwb));
823                 dprint(" wayboxes from maps/");
824                 dprint(mapname);
825                 dprint(".waypoints\n");
826         }
827         else
828         {
829                 dprint("waypoint load from ");
830                 dprint(filename);
831                 dprint(" failed\n");
832         }
833         return cwp + cwb;
834 };
835
836 void waypoint_spawnforitem(entity e)
837 {
838         local entity w;
839         local vector org;
840
841         if(!bot_waypoints_for_items)
842                 return;
843
844         org = e.origin + (e.mins + e.maxs) * 0.5;
845         org_z = e.origin_z + e.mins_z - PL_MIN_z + 1;
846         e.nearestwaypointtimeout = time + 1000000000;
847         // don't spawn an item spawnfunc_waypoint if it already exists
848         w = findchain(classname, "waypoint");
849         while (w)
850         {
851                 if (w.wpisbox)
852                 {
853                         if (boxesoverlap(org, org, w.absmin, w.absmax))
854                         {
855                                 e.nearestwaypoint = w;
856                                 return;
857                         }
858                 }
859                 else
860                 {
861                         if (vlen(w.origin - org) < 16)
862                         {
863                                 e.nearestwaypoint = w;
864                                 return;
865                         }
866                 }
867                 w = w.chain;
868         }
869         e.nearestwaypoint = waypoint_spawn(org, org, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_ITEM);
870 };
871
872 void waypoint_spawnforteleporter(entity e, vector destination, float timetaken)
873 {
874         local entity w;
875         local entity dw;
876         w = waypoint_spawn(e.absmin, e.absmax, WAYPOINTFLAG_GENERATED | WAYPOINTFLAG_TELEPORT | WAYPOINTFLAG_NORELINK);
877         dw = waypoint_spawn(destination, destination, WAYPOINTFLAG_GENERATED);
878         // one way link to the destination
879         w.wp00 = dw;
880         w.wp00mincost = timetaken; // this is just for jump pads
881         // the teleporter's nearest spawnfunc_waypoint is this one
882         // (teleporters are not goals, so this is probably useless)
883         e.nearestwaypoint = w;
884         e.nearestwaypointtimeout = time + 1000000000;
885 };
886
887
888
889
890
891 /////////////////////////////////////////////////////////////////////////////
892 // goal stack
893 /////////////////////////////////////////////////////////////////////////////
894
895 // completely empty the goal stack, used when deciding where to go
896 void navigation_clearroute()
897 {
898         self.goalcurrent = world;
899         self.goalstack01 = world;
900         self.goalstack02 = world;
901         self.goalstack03 = world;
902         self.goalstack04 = world;
903         self.goalstack05 = world;
904         self.goalstack06 = world;
905         self.goalstack07 = world;
906         self.goalstack08 = world;
907         self.goalstack09 = world;
908         self.goalstack10 = world;
909         self.goalstack11 = world;
910         self.goalstack12 = world;
911         self.goalstack13 = world;
912         self.goalstack14 = world;
913         self.goalstack15 = world;
914         self.goalstack16 = world;
915         self.goalstack17 = world;
916         self.goalstack18 = world;
917         self.goalstack19 = world;
918         self.goalstack20 = world;
919         self.goalstack21 = world;
920         self.goalstack22 = world;
921         self.goalstack23 = world;
922         self.goalstack24 = world;
923         self.goalstack25 = world;
924         self.goalstack26 = world;
925         self.goalstack27 = world;
926         self.goalstack28 = world;
927         self.goalstack29 = world;
928         self.goalstack30 = world;
929         self.goalstack31 = world;
930 };
931
932 // add a new goal at the beginning of the stack
933 // (in other words: add a new prerequisite before going to the later goals)
934 void navigation_pushroute(entity e)
935 {
936         self.goalstack31 = self.goalstack30;
937         self.goalstack30 = self.goalstack29;
938         self.goalstack29 = self.goalstack28;
939         self.goalstack28 = self.goalstack27;
940         self.goalstack27 = self.goalstack26;
941         self.goalstack26 = self.goalstack25;
942         self.goalstack25 = self.goalstack24;
943         self.goalstack24 = self.goalstack23;
944         self.goalstack23 = self.goalstack22;
945         self.goalstack22 = self.goalstack21;
946         self.goalstack21 = self.goalstack20;
947         self.goalstack20 = self.goalstack19;
948         self.goalstack19 = self.goalstack18;
949         self.goalstack18 = self.goalstack17;
950         self.goalstack17 = self.goalstack16;
951         self.goalstack16 = self.goalstack15;
952         self.goalstack15 = self.goalstack14;
953         self.goalstack14 = self.goalstack13;
954         self.goalstack13 = self.goalstack12;
955         self.goalstack12 = self.goalstack11;
956         self.goalstack11 = self.goalstack10;
957         self.goalstack10 = self.goalstack09;
958         self.goalstack09 = self.goalstack08;
959         self.goalstack08 = self.goalstack07;
960         self.goalstack07 = self.goalstack06;
961         self.goalstack06 = self.goalstack05;
962         self.goalstack05 = self.goalstack04;
963         self.goalstack04 = self.goalstack03;
964         self.goalstack03 = self.goalstack02;
965         self.goalstack02 = self.goalstack01;
966         self.goalstack01 = self.goalcurrent;
967         self.goalcurrent = e;
968 };
969
970 // remove first goal from stack
971 // (in other words: remove a prerequisite for reaching the later goals)
972 // (used when a spawnfunc_waypoint is reached)
973 void navigation_poproute()
974 {
975         self.goalcurrent = self.goalstack01;
976         self.goalstack01 = self.goalstack02;
977         self.goalstack02 = self.goalstack03;
978         self.goalstack03 = self.goalstack04;
979         self.goalstack04 = self.goalstack05;
980         self.goalstack05 = self.goalstack06;
981         self.goalstack06 = self.goalstack07;
982         self.goalstack07 = self.goalstack08;
983         self.goalstack08 = self.goalstack09;
984         self.goalstack09 = self.goalstack10;
985         self.goalstack10 = self.goalstack11;
986         self.goalstack11 = self.goalstack12;
987         self.goalstack12 = self.goalstack13;
988         self.goalstack13 = self.goalstack14;
989         self.goalstack14 = self.goalstack15;
990         self.goalstack15 = self.goalstack16;
991         self.goalstack16 = self.goalstack17;
992         self.goalstack17 = self.goalstack18;
993         self.goalstack18 = self.goalstack19;
994         self.goalstack19 = self.goalstack20;
995         self.goalstack20 = self.goalstack21;
996         self.goalstack21 = self.goalstack22;
997         self.goalstack22 = self.goalstack23;
998         self.goalstack23 = self.goalstack24;
999         self.goalstack24 = self.goalstack25;
1000         self.goalstack25 = self.goalstack26;
1001         self.goalstack26 = self.goalstack27;
1002         self.goalstack27 = self.goalstack28;
1003         self.goalstack28 = self.goalstack29;
1004         self.goalstack29 = self.goalstack30;
1005         self.goalstack30 = self.goalstack31;
1006         self.goalstack31 = world;
1007 };
1008
1009 // find the spawnfunc_waypoint near a dynamic goal such as a dropped weapon
1010 entity navigation_findnearestwaypoint(entity player, float walkfromwp)
1011 {
1012         local entity waylist, w, best;
1013         local float dist, bestdist;
1014         local vector v, org, pm1, pm2;
1015         pm1 = player.origin + PL_MIN;
1016         pm2 = player.origin + PL_MAX;
1017         waylist = findchain(classname, "waypoint");
1018         // do two scans, because box test is cheaper
1019         w = waylist;
1020         while (w)
1021         {
1022                 // if object is touching spawnfunc_waypoint
1023                 if (boxesoverlap(pm1, pm2, w.absmin, w.absmax))
1024                         return w;
1025                 w = w.chain;
1026         }
1027
1028         org = player.origin + (player.mins_z - PL_MIN_z) * '0 0 1';
1029         if(player.tag_entity)
1030                 org = org + player.tag_entity.origin;
1031         if (navigation_testtracewalk)
1032                 te_plasmaburn(org);
1033         best = world;
1034         bestdist = 1050;
1035
1036         // box check failed, try walk
1037         w = waylist;
1038         while (w)
1039         {
1040                 // if object can walk from spawnfunc_waypoint
1041                 if (w.wpisbox)
1042                 {
1043                         local vector wm1, wm2;
1044                         wm1 = w.origin + w.mins;
1045                         wm2 = w.origin + w.maxs;
1046                         v_x = bound(wm1_x, org_x, wm2_x);
1047                         v_y = bound(wm1_y, org_y, wm2_y);
1048                         v_z = bound(wm1_z, org_z, wm2_z);
1049                 }
1050                 else
1051                         v = w.origin;
1052                 dist = vlen(v - org);
1053                 if (bestdist > dist)
1054                 {
1055                         if (walkfromwp)
1056                         {
1057                                 traceline(v, org, TRUE, player);
1058                                 if (trace_fraction == 1)
1059                                 if (tracewalk(player, v, PL_MIN, PL_MAX, org, MOVE_NORMAL))
1060                                 {
1061                                         bestdist = dist;
1062                                         best = w;
1063                                 }
1064                         }
1065                         else
1066                         {
1067                                 traceline(v, org, TRUE, player);
1068                                 if (trace_fraction == 1)
1069                                 if (tracewalk(player, org, PL_MIN, PL_MAX, v, MOVE_NORMAL))
1070                                 {
1071                                         bestdist = dist;
1072                                         best = w;
1073                                 }
1074                         }
1075                 }
1076                 w = w.chain;
1077         }
1078         return best;
1079 }
1080
1081 // finds the waypoints near the bot initiating a navigation query
1082 float navigation_markroutes_nearestwaypoints(entity waylist, float maxdist)
1083 {
1084         local entity head;
1085         local vector v, m1, m2, diff;
1086         local float c;
1087         //navigation_testtracewalk = TRUE;
1088         c = 0;
1089         head = waylist;
1090         while (head)
1091         {
1092                 if (!head.wpconsidered)
1093                 {
1094                         if (head.wpisbox)
1095                         {
1096                                 m1 = head.origin + head.mins;
1097                                 m2 = head.origin + head.maxs;
1098                                 v = self.origin;
1099                                 v_x = bound(m1_x, v_x, m2_x);
1100                                 v_y = bound(m1_y, v_y, m2_y);
1101                                 v_z = bound(m1_z, v_z, m2_z);
1102                         }
1103                         else
1104                                 v = head.origin;
1105                         diff = v - self.origin;
1106                         diff_z = max(0, diff_z);
1107                         if (vlen(diff) < maxdist)
1108                         {
1109                                 head.wpconsidered = TRUE;
1110                                 if (tracewalk(self, self.origin, self.mins, self.maxs, v, MOVE_NORMAL))
1111                                 {
1112                                         head.wpnearestpoint = v;
1113                                         head.wpcost = vlen(v - self.origin) + head.dmg;
1114                                         head.wpfire = 1;
1115                                         head.enemy = world;
1116                                         c = c + 1;
1117                                 }
1118                         }
1119                 }
1120                 head = head.chain;
1121         }
1122         //navigation_testtracewalk = FALSE;
1123         return c;
1124 }
1125
1126 // updates a path link if a spawnfunc_waypoint link is better than the current one
1127 void navigation_markroutes_checkwaypoint(entity w, entity wp, float cost2, vector p)
1128 {
1129         local vector m1;
1130         local vector m2;
1131         local vector v;
1132         if (wp.wpisbox)
1133         {
1134                 m1 = wp.absmin;
1135                 m2 = wp.absmax;
1136                 v_x = bound(m1_x, p_x, m2_x);
1137                 v_y = bound(m1_y, p_y, m2_y);
1138                 v_z = bound(m1_z, p_z, m2_z);
1139         }
1140         else
1141                 v = wp.origin;
1142         cost2 = cost2 + vlen(v);
1143         if (wp.wpcost > cost2)
1144         {
1145                 wp.wpcost = cost2;
1146                 wp.enemy = w;
1147                 wp.wpfire = 1;
1148                 wp.wpnearestpoint = v;
1149         }
1150 };
1151
1152 // queries the entire spawnfunc_waypoint network for pathes leading away from the bot
1153 void navigation_markroutes()
1154 {
1155         local entity w, wp, waylist;
1156         local float searching, cost, cost2;
1157         local vector p;
1158         w = waylist = findchain(classname, "waypoint");
1159         while (w)
1160         {
1161                 w.wpconsidered = FALSE;
1162                 w.wpnearestpoint = '0 0 0';
1163                 w.wpcost = 10000000;
1164                 w.wpfire = 0;
1165                 w.enemy = world;
1166                 w = w.chain;
1167         }
1168         // try a short range search for the nearest waypoints, and expand the
1169         // search repeatedly if none are found
1170         if (!navigation_markroutes_nearestwaypoints(waylist, 250))
1171                 if (!navigation_markroutes_nearestwaypoints(waylist, 1000))
1172                         navigation_markroutes_nearestwaypoints(waylist, 1000000);
1173         searching = TRUE;
1174         while (searching)
1175         {
1176                 searching = FALSE;
1177                 w = waylist;
1178                 while (w)
1179                 {
1180                         if (w.wpfire)
1181                         {
1182                                 searching = TRUE;
1183                                 w.wpfire = 0;
1184                                 cost = w.wpcost;
1185                                 p = w.wpnearestpoint;
1186                                 wp = w.wp00;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp00mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1187                                 wp = w.wp01;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp01mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1188                                 wp = w.wp02;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp02mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1189                                 wp = w.wp03;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp03mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1190                                 wp = w.wp04;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp04mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1191                                 wp = w.wp05;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp05mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1192                                 wp = w.wp06;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp06mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1193                                 wp = w.wp07;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp07mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1194                                 wp = w.wp08;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp08mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1195                                 wp = w.wp09;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp09mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1196                                 wp = w.wp10;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp10mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1197                                 wp = w.wp11;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp11mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1198                                 wp = w.wp12;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp12mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1199                                 wp = w.wp13;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp13mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1200                                 wp = w.wp14;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp14mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1201                                 wp = w.wp15;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp15mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1202                                 wp = w.wp16;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp16mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1203                                 wp = w.wp17;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp17mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1204                                 wp = w.wp18;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp18mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1205                                 wp = w.wp19;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp19mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1206                                 wp = w.wp20;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp20mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1207                                 wp = w.wp21;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp21mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1208                                 wp = w.wp22;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp22mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1209                                 wp = w.wp23;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp23mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1210                                 wp = w.wp24;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp24mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1211                                 wp = w.wp25;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp25mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1212                                 wp = w.wp26;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp26mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1213                                 wp = w.wp27;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp27mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1214                                 wp = w.wp28;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp28mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1215                                 wp = w.wp29;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp29mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1216                                 wp = w.wp30;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp30mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1217                                 wp = w.wp31;if (wp){cost2 = cost + wp.dmg;if (wp.wpcost > cost2 + wp.wp31mincost) navigation_markroutes_checkwaypoint(w, wp, cost2, p);
1218                                 }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
1219                         }
1220                         w = w.chain;
1221                 }
1222         }
1223 };
1224
1225 // updates the best goal according to a weighted calculation of travel cost and item value of a new proposed item
1226 .void() havocbot_role;
1227 void() havocbot_role_ctf_offense;
1228 void navigation_routerating(entity e, float f, float rangebias)
1229 {
1230         if (!e)
1231                 return;
1232         //te_wizspike(e.origin);
1233         //bprint(etos(e));
1234         //bprint("\n");
1235         // update the cached spawnfunc_waypoint link on a dynamic item entity
1236         if (time > e.nearestwaypointtimeout)
1237         {
1238                 e.nearestwaypoint = navigation_findnearestwaypoint(e, TRUE);
1239                 e.nearestwaypointtimeout = time + random() * 3 + 5;
1240         }
1241         //dprint(e.classname, " ", ftos(f));
1242         if (e.nearestwaypoint)
1243         if (e.nearestwaypoint.wpcost < 10000000)
1244         {
1245                 //te_wizspike(e.nearestwaypoint.wpnearestpoint);
1246                 //dprint(e.classname, " ", ftos(f), "/(1+", ftos((e.nearestwaypoint.wpcost + vlen(e.origin - e.nearestwaypoint.wpnearestpoint))), "/", ftos(rangebias), ") = ");
1247                 f = f * rangebias / (rangebias + (e.nearestwaypoint.wpcost + vlen(e.origin - e.nearestwaypoint.wpnearestpoint)));
1248                 //if (self.havocbot_role == havocbot_role_ctf_offense)
1249                 //      dprint("-- considering ", e.classname, " (with rating ", ftos(f), ")\n");
1250                 //dprint(ftos(f));
1251                 if (navigation_bestrating < f)
1252                 {
1253                         navigation_bestrating = f;
1254                         navigation_bestgoal = e;
1255                 }
1256         }
1257         //dprint("\n");
1258 };
1259
1260 // replaces the goal stack with the path to a given item
1261 void navigation_routetogoal(entity e)
1262 {
1263         // if already going to this goal, don't stop
1264         //if (self.goalentity == e)
1265         //      return;
1266         // clear the route and add the new one
1267         navigation_clearroute();
1268         self.goalentity = e;
1269         // if there is no goal, just exit
1270         if (!e)
1271                 return;
1272         // put the entity on the goal stack as the only item
1273         navigation_pushroute(e);
1274         //te_smallflash((e.absmin + e.absmax) * 0.5);
1275         //bprint("navigation_routetogoal(");
1276         //bprint(etos(e));
1277         //bprint(") : ");
1278         //bprint(etos(e));
1279         //tracebox(self.origin, '-16 -16 0', '16 16 0', e.origin, TRUE, self);
1280         //if (trace_fraction == 1)
1281         if (tracewalk(self, self.origin, PL_MIN, PL_MAX, e.origin, MOVE_NORMAL))
1282                 return;
1283         // see if there are waypoints describing a path to the item
1284         e = e.nearestwaypoint;
1285         while (e != world)
1286         {
1287                 //bprint(" ");
1288                 //bprint(etos(e));
1289                 //te_smallflash((e.absmin + e.absmax) * 0.5);
1290                 //tracebox(self.origin, '-16 -16 0', '16 16 0', e.origin, TRUE, self);
1291                 //if (trace_fraction == 1)
1292                 //if (tracewalk(self, self.origin, PL_MIN, PL_MAX, e.origin, MOVE_NORMAL))
1293                 //      break;
1294                 // add the spawnfunc_waypoint to the path
1295                 navigation_pushroute(e);
1296                 e = e.enemy;
1297         }
1298         //bprint("\n");
1299 };
1300
1301 // removes any currently touching waypoints from the goal stack
1302 // (this is how bots detect if they have reached a goal)
1303 void navigation_poptouchedgoals()
1304 {
1305         local vector org, m1, m2;
1306         org = self.origin;// + self.velocity * 0.1;
1307         m1 = org + self.mins;
1308         m2 = org + self.maxs;
1309         while (self.goalcurrent && boxesoverlap(m1, m2, self.goalcurrent.absmin, self.goalcurrent.absmax))
1310                 navigation_poproute();
1311 }
1312
1313 // begin a goal selection session (queries spawnfunc_waypoint network)
1314 void navigation_goalrating_start()
1315 {
1316         navigation_bestrating = -1;
1317         navigation_bestgoal = world;
1318         navigation_markroutes();
1319 };
1320
1321 // ends a goal selection session (updates goal stack to the best goal)
1322 void navigation_goalrating_end()
1323 {
1324         if (self.havocbot_role == havocbot_role_ctf_offense)
1325                 dprint(navigation_bestgoal.classname, " (with rating ", ftos(navigation_bestrating), ")\n");
1326         navigation_routetogoal(navigation_bestgoal);
1327 };
1328
1329
1330
1331
1332
1333 //////////////////////////////////////////////////////////////////////////////
1334 // general bot functions
1335 //////////////////////////////////////////////////////////////////////////////
1336
1337 .float isbot; // true if this client is actually a bot
1338
1339 float skill;
1340 entity bot_list;
1341 .entity nextbot;
1342
1343 float sv_maxspeed;
1344 .float createdtime;
1345
1346 .float bot_preferredcolors;
1347
1348 .float bot_attack;
1349 .float bot_dodge;
1350 .float bot_dodgerating;
1351
1352 //.float bot_painintensity;
1353 .float bot_firetimer;
1354 //.float bot_oldhealth;
1355 .void() bot_ai;
1356
1357 .entity bot_aimtarg;
1358 .float bot_aimlatency;
1359 .vector bot_aimselforigin;
1360 .vector bot_aimselfvelocity;
1361 .vector bot_aimtargorigin;
1362 .vector bot_aimtargvelocity;
1363
1364 .float bot_pickup;
1365 .float(entity player, entity item) bot_pickupevalfunc;
1366 .float bot_pickupbasevalue;
1367 .float bot_canfire;
1368
1369 // used for aiming currently
1370 // FIXME: make the weapon code use these and then replace the calculations here with a call to the weapon code
1371 vector shotorg;
1372 vector shotdir;
1373
1374 const float BOTSKINS = 19;
1375 const float BOTNAMES = 32;
1376 string bot_namefornumber(float r)
1377 {
1378         if (r <  1) return "Thunderstorm";
1379         if (r <  2) return "Darkness";
1380         if (r <  3) return "Scorcher";
1381         if (r <  4) return "Paranoia";
1382         if (r <  5) return "Eureka";
1383         if (r <  6) return "Mystery";
1384         if (r <  7) return "Toxic";
1385         if (r <  8) return "Dominion";
1386         if (r <  9) return "Pegasus";
1387         if (r < 10) return "Sensible";
1388         if (r < 11) return "Gator";
1389         if (r < 12) return "Kangaroo";
1390         if (r < 13) return "Deadline";
1391         if (r < 14) return "Frosty";
1392         if (r < 15) return "Roadkill";
1393         if (r < 16) return "Death";
1394         if (r < 17) return "Panic";
1395         if (r < 18) return "Discovery";
1396         if (r < 19) return "Shadow";
1397         if (r < 20) return "Acidic";
1398         if (r < 21) return "Dominator";
1399         if (r < 22) return "Hellfire";
1400         if (r < 23) return "Necrotic";
1401         if (r < 24) return "Newbie";
1402         if (r < 25) return "Spellbinder";
1403         if (r < 26) return "Lion";
1404         if (r < 27) return "Controlled";
1405         if (r < 28) return "Airhead";
1406         if (r < 29) return "Delirium";
1407         if (r < 30) return "Resurrection";
1408         if (r < 31) return "Danger";
1409         return "Flatline";
1410 };
1411
1412 string bot_skinfornumber(float r)
1413 {
1414              if (r <  1) {self.playermodel = "models/player/carni.zym"          ;self.playerskin = "0";return "Carni"          ;}
1415         else if (r <  2) {self.playermodel = "models/player/carni.zym"          ;self.playerskin = "1";return "Armored Carni"  ;}
1416         else if (r <  3) {self.playermodel = "models/player/crash.zym"          ;self.playerskin = "0";return "Quark"          ;}
1417         else if (r <  4) {self.playermodel = "models/player/grunt.zym"          ;self.playerskin = "0";return "Grunt"          ;}
1418         else if (r <  5) {self.playermodel = "models/player/headhunter.zym"     ;self.playerskin = "0";return "HeadHunter"     ;}
1419         else if (r <  6) {self.playermodel = "models/player/insurrectionist.zym";self.playerskin = "0";return "Insurrectionist";}
1420         else if (r <  7) {self.playermodel = "models/player/lurk.zym"           ;self.playerskin = "0";return "Lurk"           ;}
1421         else if (r <  8) {self.playermodel = "models/player/lurk.zym"           ;self.playerskin = "1";return "Reptile"        ;}
1422         else if (r <  9) {self.playermodel = "models/player/lycanthrope.zym"    ;self.playerskin = "0";return "Lycanthrope"    ;}
1423         else if (r < 10) {self.playermodel = "models/player/marine.zym"         ;self.playerskin = "0";return "Marine"         ;}
1424         else if (r < 11) {self.playermodel = "models/player/nexus.zym"          ;self.playerskin = "0";return "Nexus"          ;}
1425         else if (r < 12) {self.playermodel = "models/player/nexus.zym"          ;self.playerskin = "1";return "Mulder"         ;}
1426         else if (r < 13) {self.playermodel = "models/player/nexus.zym"          ;self.playerskin = "2";return "Xolar"          ;}
1427         else if (r < 14) {self.playermodel = "models/player/pyria.zym"          ;self.playerskin = "0";return "Pyria"          ;}
1428         else if (r < 15) {self.playermodel = "models/player/shock.zym"          ;self.playerskin = "0";return "Shock"          ;}
1429         else if (r < 16) {self.playermodel = "models/player/skadi.zym"          ;self.playerskin = "0";return "Skadi"          ;}
1430         else if (r < 17) {self.playermodel = "models/player/specop.zym"         ;self.playerskin = "0";return "Specop"         ;}
1431         else             {self.playermodel = "models/player/visitant.zym"       ;self.playerskin = "0";return "Fricka"         ;}
1432 };
1433
1434 void bot_setnameandstuff()
1435 {
1436         local string name, prefix, suffix;
1437         local float r, b, shirt, pants;
1438
1439         prefix = cvar_string("bot_prefix");
1440         suffix = cvar_string("bot_suffix");
1441
1442         // this is really only a default, JoinBestTeam is called later
1443         pants = bound(0, floor(random() * 13), 13);
1444         //shirt = bound(0, floor(random() * 16), 15);
1445         shirt = pants;
1446         setcolor(self, shirt * 16 + pants);
1447         self.bot_preferredcolors = self.clientcolors;
1448
1449         // now pick a name...
1450
1451         if (cvar("bot_usemodelnames"))
1452         {
1453                 // first see if all skins are taken
1454                 b = 0;
1455                 do
1456                 {
1457                         name = bot_skinfornumber(b);
1458                         b = b + 1;
1459                 }
1460                 while (b < BOTSKINS && find(world, netname, name));
1461
1462                 // randomly pick a skin, if it's taken either repeat until we find one,
1463                 // or give up if we already know all skins are taken
1464                 do
1465                 {
1466                         r = floor(random() * BOTSKINS);
1467                         name = bot_skinfornumber(r);
1468                 }
1469                 while (b < BOTSKINS && find(world, netname, name));
1470         }
1471         else
1472         {
1473                 // first see if all names are taken
1474                 b = 0;
1475                 do
1476                 {
1477                         name = bot_namefornumber(b);
1478                         b = b + 1;
1479                 }
1480                 while (b < BOTNAMES && find(world, netname, name));
1481
1482                 // randomly pick a name, if it's taken either repeat until we find one,
1483                 // or give up if we already know all names are taken
1484                 do
1485                 {
1486                         r = floor(random() * BOTNAMES);
1487                         name = bot_namefornumber(r);
1488                 }
1489                 while (b < BOTNAMES && find(world, netname, name));
1490
1491                 // randomly pick a skin
1492                 bot_skinfornumber(floor(random() * BOTSKINS));
1493         }
1494         if(!cvar("g_campaign"))
1495                 self.netname = strzone(strcat(prefix, name, suffix));
1496         else
1497                 self.netname = name;
1498 };
1499
1500 void bot_endgame()
1501 {
1502         local entity e;
1503         //dprint("bot_endgame\n");
1504         e = bot_list;
1505         while (e)
1506         {
1507                 setcolor(e, e.bot_preferredcolors);
1508                 e = e.nextbot;
1509         }
1510         // if dynamic waypoints are ever implemented, save them here
1511 };
1512
1513 float bot_ignore_bots; // let bots not attack other bots (only works in non-teamplay)
1514 float bot_shouldattack(entity e)
1515 {
1516         if (e.team == self.team)
1517         {
1518                 if (e == self)
1519                         return FALSE;
1520                 if (teamplay)
1521                 if (e.team != 0)
1522                         return FALSE;
1523         }
1524         if(!teamplay)
1525                 if(bot_ignore_bots)
1526                         if(clienttype(e) == CLIENTTYPE_BOT)
1527                                 return FALSE;
1528         if (!e.takedamage)
1529                 return FALSE;
1530         if (e.deadflag)
1531                 return FALSE;
1532         if (e.BUTTON_CHAT)
1533                 return FALSE;
1534         return TRUE;
1535 };
1536
1537 void bot_lagfunc(float t, float f1, float f2, entity e1, vector v1, vector v2, vector v3, vector v4)
1538 {
1539         self.bot_aimtarg = e1;
1540         self.bot_aimlatency = self.ping; // FIXME?  Shouldn't this be in the lag item?
1541         self.bot_aimselforigin = v1;
1542         self.bot_aimselfvelocity = v2;
1543         self.bot_aimtargorigin = v3;
1544         self.bot_aimtargvelocity = v4;
1545         if(skill <= 0)
1546                 self.bot_canfire = (random() < 0.8);
1547         else if(skill <= 1)
1548                 self.bot_canfire = (random() < 0.9);
1549         else if(skill <= 2)
1550                 self.bot_canfire = (random() < 0.95);
1551         else
1552                 self.bot_canfire = 1;
1553 };
1554
1555 .float bot_nextthink;
1556 .float bot_badaimtime;
1557 .float bot_aimthinktime;
1558 .vector bot_mouseaim;
1559 .vector bot_badaimoffset;
1560 .vector bot_1st_order_aimfilter;
1561 .vector bot_2nd_order_aimfilter;
1562 .vector bot_3th_order_aimfilter;
1563 .vector bot_4th_order_aimfilter;
1564 .vector bot_5th_order_aimfilter;
1565 .vector bot_olddesiredang;
1566 float bot_aimdir(vector v, float maxfiredeviation)
1567 {
1568 /*
1569         local float snapcos;
1570         local vector olddir, newdir, desireddir;
1571
1572         makevectors(self.v_angle);
1573         olddir = newdir = v_forward;
1574         desireddir = normalize(v);
1575         snapcos = cos(cvar("bot_ai_aimskill_snapangle") * frametime * (skill + 1) * 0.5);
1576         if (desireddir * olddir < v_forward_x)
1577                 newdir = desireddir;
1578         else
1579         {
1580                 local float blendrate;
1581                 blendrate = cvar("bot_ai_aimskill_blendrate") * frametime * (skill + 1) * 0.5;
1582                 newdir = olddir + (desireddir - olddir) * bound(0, blendrate, 1);
1583         }
1584
1585         // decide whether to fire this time
1586         if ((desireddir * newdir) >= cos(maxfiredeviation))
1587                 self.bot_firetimer = time + 0.3;
1588
1589         self.v_angle = vectoangles(newdir);
1590         self.v_angle_x = self.v_angle_x * -1;
1591
1592         makevectors(self.v_angle);
1593         shotorg = self.origin + self.view_ofs;
1594         shotdir = newdir;
1595
1596         return time < self.bot_firetimer;
1597 */
1598
1599         local float dist;
1600         local vector desiredang, diffang;
1601
1602         //dprint("aim ", self.netname, ": old:", vtos(self.v_angle));
1603         // make sure v_angle is sane first
1604         self.v_angle_y = self.v_angle_y - floor(self.v_angle_y / 360) * 360;
1605         self.v_angle_z = 0;
1606
1607         // get the desired angles to aim at
1608         //dprint(" at:", vtos(v));
1609         v = normalize(v);
1610         //te_lightning2(world, self.origin + self.view_ofs, self.origin + self.view_ofs + v * 200);
1611         if (time >= self.bot_badaimtime)
1612         {
1613                 self.bot_badaimtime = max(self.bot_badaimtime + 0.3, time);
1614                 self.bot_badaimoffset = randomvec() * bound(0, 5 - 0.5 * (skill+self.bot_offsetskill), 5) * cvar("bot_ai_aimskill_offset");
1615         }
1616         desiredang = vectoangles(v) + self.bot_badaimoffset;
1617         //dprint(" desired:", vtos(desiredang));
1618         if (desiredang_x >= 180)
1619                 desiredang_x = desiredang_x - 360;
1620         desiredang_x = bound(-90, 0 - desiredang_x, 90);
1621         desiredang_z = self.v_angle_z;
1622         //dprint(" / ", vtos(desiredang));
1623
1624         //// pain throws off aim
1625         //if (self.bot_painintensity)
1626         //{
1627         //      // shake from pain
1628         //      desiredang = desiredang + randomvec() * self.bot_painintensity * 0.2;
1629         //}
1630
1631         // calculate turn angles
1632         diffang = (desiredang - self.bot_olddesiredang);
1633         // wrap yaw turn
1634         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
1635         if (diffang_y >= 180)
1636                 diffang_y = diffang_y - 360;
1637         self.bot_olddesiredang = desiredang;
1638         //dprint(" diff:", vtos(diffang));
1639
1640         // Here we will try to anticipate the comming aiming direction
1641         self.bot_1st_order_aimfilter= self.bot_1st_order_aimfilter
1642                 + (diffang * (1 / frametime)    - self.bot_1st_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_1st"),1);
1643         self.bot_2nd_order_aimfilter= self.bot_2nd_order_aimfilter
1644                 + (self.bot_1st_order_aimfilter - self.bot_2nd_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_2nd"),1);
1645         self.bot_3th_order_aimfilter= self.bot_3th_order_aimfilter
1646                 + (self.bot_2nd_order_aimfilter - self.bot_3th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_3th"),1);
1647         self.bot_4th_order_aimfilter= self.bot_4th_order_aimfilter
1648                 + (self.bot_3th_order_aimfilter - self.bot_4th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_4th"),1);
1649         self.bot_5th_order_aimfilter= self.bot_5th_order_aimfilter
1650                 + (self.bot_4th_order_aimfilter - self.bot_5th_order_aimfilter) * bound(0, cvar("bot_ai_aimskill_order_filter_5th"),1);
1651
1652         local float blend;
1653         //blend = (bound(0,skill,10)*0.1)*pow(1-bound(0,skill,10)*0.05,2.5)*5.656854249; //Plot formule before changing !
1654         blend = bound(0,skill,10)*0.1;
1655         desiredang = desiredang + blend *
1656         (
1657                   self.bot_1st_order_aimfilter * cvar("bot_ai_aimskill_order_mix_1st")
1658                 + self.bot_2nd_order_aimfilter * cvar("bot_ai_aimskill_order_mix_2nd")
1659                 + self.bot_3th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_3th")
1660                 + self.bot_4th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_4th")
1661                 + self.bot_5th_order_aimfilter * cvar("bot_ai_aimskill_order_mix_5th")
1662         );
1663
1664         // calculate turn angles
1665         diffang = desiredang - self.bot_mouseaim;
1666         // wrap yaw turn
1667         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
1668         if (diffang_y >= 180)
1669                 diffang_y = diffang_y - 360;
1670         //dprint(" diff:", vtos(diffang));
1671
1672         if (time >= self.bot_aimthinktime)
1673         {
1674                 self.bot_aimthinktime = max(self.bot_aimthinktime + 0.5 - 0.05*(skill+self.bot_thinkskill), time);
1675                 self.bot_mouseaim = self.bot_mouseaim + diffang * (1-random()*0.1*bound(1,10-skill,10));
1676         }
1677
1678         //self.v_angle = self.v_angle + diffang * bound(0, r * frametime * (skill * 0.5 + 2), 1);
1679
1680         diffang = self.bot_mouseaim - desiredang;
1681         // wrap yaw turn
1682         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
1683         if (diffang_y >= 180)
1684                 diffang_y = diffang_y - 360;
1685         desiredang = desiredang + diffang * bound(0,cvar("bot_ai_aimskill_think"),1);
1686
1687         // calculate turn angles
1688         diffang = desiredang - self.v_angle;
1689         // wrap yaw turn
1690         diffang_y = diffang_y - floor(diffang_y / 360) * 360;
1691         if (diffang_y >= 180)
1692                 diffang_y = diffang_y - 360;
1693         //dprint(" diff:", vtos(diffang));
1694
1695         // jitter tracking
1696         dist = vlen(diffang);
1697         //diffang = diffang + randomvec() * (dist * 0.05 * (3.5 - bound(0, skill, 3)));
1698
1699         // turn
1700         local float r, fixedrate, blendrate;
1701         fixedrate = cvar("bot_ai_aimskill_fixedrate") / bound(1,dist,1000);
1702         blendrate = cvar("bot_ai_aimskill_blendrate");
1703         r = max(fixedrate, blendrate);
1704         //self.v_angle = self.v_angle + diffang * bound(frametime, r * frametime * (2+skill*skill*0.05-random()*0.05*(10-skill)), 1);
1705         self.v_angle = self.v_angle + diffang * bound(frametime, r * frametime * (2+pow(skill+self.bot_mouseskill,3)*0.005-random()), 1);
1706         self.v_angle = self.v_angle * bound(0,cvar("bot_ai_aimskill_mouse"),1) + desiredang * bound(0,(1-cvar("bot_ai_aimskill_mouse")),1);
1707         //self.v_angle = self.v_angle + diffang * bound(0, r * frametime * (skill * 0.5 + 2), 1);
1708         //self.v_angle = self.v_angle + diffang * (1/ blendrate);
1709         self.v_angle_z = 0;
1710         self.v_angle_y = self.v_angle_y - floor(self.v_angle_y / 360) * 360;
1711         //dprint(" turn:", vtos(self.v_angle));
1712
1713         makevectors(self.v_angle);
1714         shotorg = self.origin + self.view_ofs;
1715         shotdir = v_forward;
1716
1717         //dprint(" dir:", vtos(v_forward));
1718         //te_lightning2(world, shotorg, shotorg + shotdir * 100);
1719
1720         // calculate turn angles again
1721         //diffang = desiredang - self.v_angle;
1722         //diffang_y = diffang_y - floor(diffang_y / 360) * 360;
1723         //if (diffang_y >= 180)
1724         //      diffang_y = diffang_y - 360;
1725
1726         //dprint("e ", vtos(diffang), " < ", ftos(maxfiredeviation), "\n");
1727
1728         // decide whether to fire this time
1729         // note the maxfiredeviation is in degrees so this has to convert to radians first
1730         //if ((normalize(v) * shotdir) >= cos(maxfiredeviation * (3.14159265358979323846 / 180)))
1731         if ((normalize(v) * shotdir) >= cos(maxfiredeviation * (3.14159265358979323846 / 180)))
1732         if (vlen(trace_endpos-shotorg) < 500+500*bound(0, skill, 10) || random()*random()>bound(0,skill*0.05,1))
1733                 self.bot_firetimer = time + bound(0.1, 0.5-skill*0.05, 0.5);
1734         //traceline(shotorg,shotorg+shotdir*1000,FALSE,world);
1735         //dprint(ftos(maxfiredeviation),"\n");
1736         //dprint(" diff:", vtos(diffang), "\n");
1737
1738         return self.bot_canfire && (time < self.bot_firetimer);
1739 };
1740
1741 vector bot_shotlead(vector targorigin, vector targvelocity, float shotspeed, float shotdelay)
1742 {
1743         // Try to add code here that predicts gravity effect here, no clue HOW to though ... well not yet atleast...
1744         return targorigin + targvelocity * (shotdelay + vlen(targorigin - shotorg) / shotspeed);
1745 };
1746
1747 float bot_aim(float shotspeed, float shotspeedupward, float maxshottime, float applygravity)
1748 {
1749         local float f, r;
1750         local vector v;
1751         /*
1752         eprint(self);
1753         dprint("bot_aim(", ftos(shotspeed));
1754         dprint(", ", ftos(shotspeedupward));
1755         dprint(", ", ftos(maxshottime));
1756         dprint(", ", ftos(applygravity));
1757         dprint(");\n");
1758         */
1759         if (!shotspeed)
1760         {
1761                 dprint("bot_aim: WARNING: weapon ", W_Name(self.weapon), " shotspeed is zero!\n");
1762                 shotspeed = 1000000;
1763         }
1764         if (!maxshottime)
1765         {
1766                 dprint("bot_aim: WARNING: weapon ", W_Name(self.weapon), " maxshottime is zero!\n");
1767                 maxshottime = 1;
1768         }
1769         makevectors(self.v_angle);
1770         shotorg = self.origin + self.view_ofs;
1771         shotdir = v_forward;
1772         v = bot_shotlead(self.bot_aimtargorigin, self.bot_aimtargvelocity, shotspeed, self.bot_aimlatency);
1773         local float distanceratio;
1774         distanceratio =sqrt(bound(0,skill,10000))*0.3*(vlen(v-shotorg)-100)/cvar("bot_ai_aimskill_firetolerance_distdegrees");
1775         distanceratio = bound(0,distanceratio,1);
1776         r =  (cvar("bot_ai_aimskill_firetolerance_maxdegrees")-cvar("bot_ai_aimskill_firetolerance_mindegrees"))
1777                 * (1-distanceratio) + cvar("bot_ai_aimskill_firetolerance_mindegrees");
1778         if (applygravity && self.bot_aimtarg)
1779         {
1780                 if (!findtrajectorywithleading(shotorg, '0 0 0', '0 0 0', self.bot_aimtarg, shotspeed, shotspeedupward, maxshottime, 0, self))
1781                         return FALSE;
1782                 f = bot_aimdir(findtrajectory_velocity - shotspeedupward * '0 0 1', r);
1783         }
1784         else
1785         {
1786                 f = bot_aimdir(v - shotorg, r);
1787                 //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");
1788                 traceline(shotorg, shotorg + shotdir * 10000, FALSE, self);
1789                 if (trace_ent.takedamage)
1790                 if (trace_fraction < 1)
1791                 if (!bot_shouldattack(trace_ent))
1792                         return FALSE;
1793                 traceline(shotorg, self.bot_aimtargorigin, FALSE, self);
1794                 if (trace_fraction < 1)
1795                 if (trace_ent != self.enemy)
1796                 if (!bot_shouldattack(trace_ent))
1797                         return FALSE;
1798         }
1799         if (r > maxshottime * shotspeed)
1800                 return FALSE;
1801         return f;
1802 };
1803
1804 // TODO: move this painintensity code to the player damage code
1805 void bot_think()
1806 {
1807         if (self.bot_nextthink > time)
1808                 return;
1809         self.bot_nextthink = self.bot_nextthink + cvar("bot_ai_thinkinterval");
1810         //if (self.bot_painintensity > 0)
1811         //      self.bot_painintensity = self.bot_painintensity - (skill + 1) * 40 * frametime;
1812
1813         //self.bot_painintensity = self.bot_painintensity + self.bot_oldhealth - self.health;
1814         //self.bot_painintensity = bound(0, self.bot_painintensity, 100);
1815
1816         if(time < restart_countdown || ((cvar("g_campaign") && !campaign_bots_may_start)))
1817         {
1818                 self.nextthink = time + 0.5;
1819                 return;
1820         }
1821
1822         if (self.fixangle)
1823         {
1824                 self.v_angle = self.angles;
1825                 self.v_angle_z = 0;
1826                 self.fixangle = FALSE;
1827         }
1828
1829         self.dmg_take = 0;
1830         self.dmg_save = 0;
1831         self.dmg_inflictor = world;
1832
1833         // calculate an aiming latency based on the skill setting
1834         // (simulated network latency + naturally delayed reflexes)
1835         //self.ping = 0.7 - bound(0, 0.05 * skill, 0.5); // moved the reflexes to bot_aimdir (under the name 'think')
1836         // minimum ping 20+10 random
1837         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
1838         // skill 10 = ping 0.2 (adrenaline)
1839         // skill 0 = ping 0.7 (slightly drunk)
1840
1841         // clear buttons
1842         self.BUTTON_ATCK = 0;
1843         self.button1 = 0;
1844         self.BUTTON_JUMP = 0;
1845         self.BUTTON_ATCK2 = 0;
1846         self.BUTTON_ZOOM = 0;
1847         self.BUTTON_CROUCH = 0;
1848         self.BUTTON_HOOK = 0;
1849         self.BUTTON_INFO = 0;
1850         self.button8 = 0;
1851         self.BUTTON_CHAT = 0;
1852         self.BUTTON_USE = 0;
1853
1854         // if dead, just wait until we can respawn
1855         if (self.deadflag)
1856         {
1857                 if (self.deadflag == DEAD_DEAD)
1858                         self.BUTTON_JUMP = 1; // press jump to respawn
1859                 return;
1860         }
1861
1862         // now call the current bot AI (havocbot for example)
1863         self.bot_ai();
1864 };
1865
1866 entity bot_strategytoken;
1867 float bot_strategytoken_taken;
1868 entity player_list;
1869 .entity nextplayer;
1870 void bot_relinkplayerlist()
1871 {
1872         local entity e;
1873         local entity prevbot;
1874         player_count = 0;
1875         currentbots = 0;
1876         player_list = e = findchainflags(flags, FL_CLIENT);
1877         bot_list = world;
1878         prevbot = world;
1879         while (e)
1880         {
1881                 player_count = player_count + 1;
1882                 e.nextplayer = e.chain;
1883                 if (clienttype(e) == CLIENTTYPE_BOT)
1884                 {
1885                         if (prevbot)
1886                                 prevbot.nextbot = e;
1887                         else
1888                                 bot_list = e;
1889                         prevbot = e;
1890                         currentbots = currentbots + 1;
1891                 }
1892                 e = e.chain;
1893         }
1894         dprint(strcat("relink: ", ftos(currentbots), " bots seen.\n"));
1895         bot_strategytoken = bot_list;
1896         bot_strategytoken_taken = TRUE;
1897 };
1898
1899 void() havocbot_setupbot;
1900 float JoinBestTeam(entity pl, float only_return_best, float forcebestteam);
1901
1902 void bot_clientconnect()
1903 {
1904         if (clienttype(self) != CLIENTTYPE_BOT)
1905                 return;
1906         self.bot_preferredcolors = self.clientcolors;
1907         self.bot_nextthink = time - random();
1908         self.lag_func = bot_lagfunc;
1909         self.isbot = TRUE;
1910         self.createdtime = self.nextthink;
1911         JoinBestTeam(self, FALSE, TRUE);
1912         havocbot_setupbot();
1913         self.bot_mouseskill=random()-0.5;
1914         self.bot_thinkskill=random()-0.5;
1915         self.bot_predictionskill=random()-0.5;
1916         self.bot_offsetskill=random()-0.5;
1917 };
1918
1919 entity bot_spawn()
1920 {
1921         local entity oldself, bot;
1922         bot = spawnclient();
1923         if (bot)
1924         {
1925                 currentbots = currentbots + 1;
1926                 oldself = self;
1927                 self = bot;
1928                 bot_setnameandstuff();
1929                 ClientConnect();
1930                 PutClientInServer();
1931                 self = oldself;
1932         }
1933         return bot;
1934 };
1935
1936 void CheckAllowedTeams(entity for_whom); void GetTeamCounts(entity other); float c1, c2, c3, c4;
1937 void bot_removefromlargestteam()
1938 {
1939         local float besttime, bestcount, thiscount;
1940         local entity best, head;
1941         CheckAllowedTeams(world);
1942         GetTeamCounts(world);
1943         head = findchainfloat(isbot, TRUE);
1944         if (!head)
1945                 return;
1946         best = head;
1947         besttime = head.createdtime;
1948         bestcount = 0;
1949         while (head)
1950         {
1951                 if(head.team == COLOR_TEAM1)
1952                         thiscount = c1;
1953                 else if(head.team == COLOR_TEAM2)
1954                         thiscount = c2;
1955                 else if(head.team == COLOR_TEAM3)
1956                         thiscount = c3;
1957                 else if(head.team == COLOR_TEAM4)
1958                         thiscount = c4;
1959                 else
1960                         thiscount = 0;
1961                 if (thiscount > bestcount)
1962                 {
1963                         bestcount = thiscount;
1964                         besttime = head.createdtime;
1965                         best = head;
1966                 }
1967                 else if (thiscount == bestcount && besttime < head.createdtime)
1968                 {
1969                         besttime = head.createdtime;
1970                         best = head;
1971                 }
1972                 head = head.chain;
1973         }
1974         currentbots = currentbots - 1;
1975         dropclient(best);
1976 };
1977
1978 void bot_removenewest()
1979 {
1980         local float besttime;
1981         local entity best, head;
1982
1983         if(teams_matter)
1984         {
1985                 bot_removefromlargestteam();
1986                 return;
1987         }
1988
1989         head = findchainfloat(isbot, TRUE);
1990         if (!head)
1991                 return;
1992         best = head;
1993         besttime = head.createdtime;
1994         while (head)
1995         {
1996                 if (besttime < head.createdtime)
1997                 {
1998                         besttime = head.createdtime;
1999                         best = head;
2000                 }
2001                 head = head.chain;
2002         }
2003         currentbots = currentbots - 1;
2004         dropclient(best);
2005 };
2006
2007 float botframe_waypointeditorlightningtime;
2008 void botframe_showwaypointlinks()
2009 {
2010         local entity player, head, w;
2011         if (time < botframe_waypointeditorlightningtime)
2012                 return;
2013         botframe_waypointeditorlightningtime = time + 0.5;
2014         player = find(world, classname, "player");
2015         while (player)
2016         {
2017                 if (!player.isbot)
2018                 if (player.flags & FL_ONGROUND)
2019                 {
2020                         //navigation_testtracewalk = TRUE;
2021                         head = navigation_findnearestwaypoint(player, FALSE);
2022                         //navigation_testtracewalk = FALSE;
2023                         if (head)
2024                         {
2025                                 w = head     ;if (w) te_lightning2(world, w.origin, player.origin);
2026                                 w = head.wp00;if (w) te_lightning2(world, w.origin, head.origin);
2027                                 w = head.wp01;if (w) te_lightning2(world, w.origin, head.origin);
2028                                 w = head.wp02;if (w) te_lightning2(world, w.origin, head.origin);
2029                                 w = head.wp03;if (w) te_lightning2(world, w.origin, head.origin);
2030                                 w = head.wp04;if (w) te_lightning2(world, w.origin, head.origin);
2031                                 w = head.wp05;if (w) te_lightning2(world, w.origin, head.origin);
2032                                 w = head.wp06;if (w) te_lightning2(world, w.origin, head.origin);
2033                                 w = head.wp07;if (w) te_lightning2(world, w.origin, head.origin);
2034                                 w = head.wp08;if (w) te_lightning2(world, w.origin, head.origin);
2035                                 w = head.wp09;if (w) te_lightning2(world, w.origin, head.origin);
2036                                 w = head.wp10;if (w) te_lightning2(world, w.origin, head.origin);
2037                                 w = head.wp11;if (w) te_lightning2(world, w.origin, head.origin);
2038                                 w = head.wp12;if (w) te_lightning2(world, w.origin, head.origin);
2039                                 w = head.wp13;if (w) te_lightning2(world, w.origin, head.origin);
2040                                 w = head.wp14;if (w) te_lightning2(world, w.origin, head.origin);
2041                                 w = head.wp15;if (w) te_lightning2(world, w.origin, head.origin);
2042                                 w = head.wp16;if (w) te_lightning2(world, w.origin, head.origin);
2043                                 w = head.wp17;if (w) te_lightning2(world, w.origin, head.origin);
2044                                 w = head.wp18;if (w) te_lightning2(world, w.origin, head.origin);
2045                                 w = head.wp19;if (w) te_lightning2(world, w.origin, head.origin);
2046                                 w = head.wp20;if (w) te_lightning2(world, w.origin, head.origin);
2047                                 w = head.wp21;if (w) te_lightning2(world, w.origin, head.origin);
2048                                 w = head.wp22;if (w) te_lightning2(world, w.origin, head.origin);
2049                                 w = head.wp23;if (w) te_lightning2(world, w.origin, head.origin);
2050                                 w = head.wp24;if (w) te_lightning2(world, w.origin, head.origin);
2051                                 w = head.wp25;if (w) te_lightning2(world, w.origin, head.origin);
2052                                 w = head.wp26;if (w) te_lightning2(world, w.origin, head.origin);
2053                                 w = head.wp27;if (w) te_lightning2(world, w.origin, head.origin);
2054                                 w = head.wp28;if (w) te_lightning2(world, w.origin, head.origin);
2055                                 w = head.wp29;if (w) te_lightning2(world, w.origin, head.origin);
2056                                 w = head.wp30;if (w) te_lightning2(world, w.origin, head.origin);
2057                                 w = head.wp31;if (w) te_lightning2(world, w.origin, head.origin);
2058                         }
2059                 }
2060                 player = find(player, classname, "player");
2061         }
2062 };
2063
2064 entity botframe_dangerwaypoint;
2065 void botframe_updatedangerousobjects(float maxupdate)
2066 {
2067         local entity head, bot_dodgelist;
2068         local vector m1, m2, v;
2069         local float c, d, danger;
2070         c = 0;
2071         bot_dodgelist = findchainfloat(bot_dodge, TRUE);
2072         botframe_dangerwaypoint = find(botframe_dangerwaypoint, classname, "waypoint");
2073         while (botframe_dangerwaypoint != world)
2074         {
2075                 danger = 0;
2076                 m1 = botframe_dangerwaypoint.mins;
2077                 m2 = botframe_dangerwaypoint.maxs;
2078                 head = bot_dodgelist;
2079                 while (head)
2080                 {
2081                         v = head.origin;
2082                         v_x = bound(m1_x, v_x, m2_x);
2083                         v_y = bound(m1_y, v_y, m2_y);
2084                         v_z = bound(m1_z, v_z, m2_z);
2085                         d = head.bot_dodgerating - vlen(head.origin - v);
2086                         if (d > 0)
2087                         {
2088                                 traceline(head.origin, v, TRUE, world);
2089                                 if (trace_fraction == 1)
2090                                         danger = danger + d;
2091                         }
2092                         head = head.chain;
2093                 }
2094                 botframe_dangerwaypoint.dmg = danger;
2095                 c = c + 1;
2096                 if (c >= maxupdate)
2097                         break;
2098                 botframe_dangerwaypoint = find(botframe_dangerwaypoint, classname, "waypoint");
2099         }
2100 };
2101
2102
2103 float botframe_spawnedwaypoints;
2104 float botframe_nextthink;
2105 float botframe_nextdangertime;
2106
2107 float autoskill_nextthink;
2108 .float totalfrags_lastcheck;
2109 void autoskill(float factor)
2110 {
2111         float bestbot;
2112         float bestplayer;
2113         entity head;
2114
2115         bestbot = -1;
2116         bestplayer = -1;
2117         FOR_EACH_PLAYER(head)
2118         {
2119                 if(clienttype(head) == CLIENTTYPE_REAL)
2120                         bestplayer = max(bestplayer, head.totalfrags - head.totalfrags_lastcheck);
2121                 else
2122                         bestbot = max(bestbot, head.totalfrags - head.totalfrags_lastcheck);
2123         }
2124
2125         dprint("autoskill: best player got ", ftos(bestplayer), ", ");
2126         dprint("best bot got ", ftos(bestbot), "; ");
2127         if(bestbot < 0 || bestplayer < 0)
2128         {
2129                 dprint("not doing anything\n");
2130                 // don't return, let it reset all counters below
2131         }
2132         else if(bestbot <= bestplayer * factor - 2)
2133         {
2134                 if(cvar("skill") < 17)
2135                 {
2136                         dprint("2 frags difference, increasing skill\n");
2137                         cvar_set("skill", ftos(cvar("skill") + 1));
2138                         bprint("^2SKILL UP!^7 Now at level ", ftos(cvar("skill")), "\n");
2139                 }
2140         }
2141         else if(bestbot >= bestplayer * factor + 2)
2142         {
2143                 if(cvar("skill") > 0)
2144                 {
2145                         dprint("2 frags difference, decreasing skill\n");
2146                         cvar_set("skill", ftos(cvar("skill") - 1));
2147                         bprint("^1SKILL DOWN!^7 Now at level ", ftos(cvar("skill")), "\n");
2148                 }
2149         }
2150         else
2151         {
2152                 dprint("not doing anything\n");
2153                 return;
2154                 // don't reset counters, wait for them to accumulate
2155         }
2156
2157         FOR_EACH_PLAYER(head)
2158                 head.totalfrags_lastcheck = head.totalfrags;
2159 }
2160
2161 void bot_serverframe()
2162 {
2163         float realplayers, bots, activerealplayers;
2164         entity head;
2165
2166         if (intermission_running)
2167                 return;
2168
2169         if (time < 2)
2170                 return;
2171
2172         if(time > autoskill_nextthink)
2173         {
2174                 float a;
2175                 a = cvar("skill_auto");
2176                 if(!cvar("g_campaign"))
2177                         if(a)
2178                                 autoskill(a);
2179                 autoskill_nextthink = time + 5;
2180         }
2181
2182         activerealplayers = 0;
2183         realplayers = 0;
2184
2185         FOR_EACH_REALCLIENT(head)
2186         {
2187                 if(head.classname == "player" || g_lms || g_arena)
2188                         ++activerealplayers;
2189                 ++realplayers;
2190         }
2191
2192         // add/remove bots if needed to make sure there are at least
2193         // minplayers+bot_number, or remove all bots if no one is playing
2194         // But don't remove bots immediately on level change, as the real players
2195         // usually haven't rejoined yet
2196         bots_would_leave = FALSE;
2197         if (realplayers || cvar("bot_join_empty") || (currentbots > 0 && time < 5))
2198         {
2199                 float realminplayers, minplayers;
2200                 realminplayers = cvar("minplayers");
2201                 minplayers = max(0, floor(realminplayers));
2202
2203                 float realminbots, minbots;
2204                 if(cvar("bot_vs_human"))
2205                         realminbots = ceil(fabs(cvar("bot_vs_human")) * activerealplayers);
2206                 else
2207                         realminbots = cvar("bot_number");
2208                 minbots = max(0, floor(realminbots));
2209
2210                 bots = min(max(minbots, minplayers - activerealplayers), maxclients - realplayers);
2211                 if(bots > minbots)
2212                         bots_would_leave = TRUE;
2213         }
2214         else
2215         {
2216                 // if there are no players, remove bots
2217                 bots = 0;
2218         }
2219
2220         bot_ignore_bots = cvar("bot_ignore_bots");
2221
2222         // only add one bot per frame to avoid utter chaos
2223         if(time > botframe_nextthink)
2224         {
2225                 //dprint(ftos(bots), " ? ", ftos(currentbots), "\n");
2226                 while (currentbots < bots)
2227                 {
2228                         if (bot_spawn() == world)
2229                         {
2230                                 bprint("Can not add bot, server full.\n");
2231                                 botframe_nextthink = time + 10;
2232                                 break;
2233                         }
2234                 }
2235                 while (currentbots > bots)
2236                         bot_removenewest();
2237         }
2238
2239         if(botframe_spawnedwaypoints)
2240         {
2241                 if(cvar("waypoint_benchmark"))
2242                         localcmd("quit\n");
2243         }
2244
2245         if (currentbots > 0 || cvar("g_waypointeditor"))
2246         if (!botframe_spawnedwaypoints)
2247         {
2248                 botframe_spawnedwaypoints = TRUE;
2249                 waypoint_loadall();
2250                 waypoint_schedulerelinkall();
2251         }
2252
2253         if (bot_list)
2254         {
2255                 // cycle the goal token from one bot to the next each frame
2256                 // (this prevents them from all doing spawnfunc_waypoint searches on the same
2257                 //  frame, which causes choppy framerates)
2258                 if (bot_strategytoken_taken)
2259                 {
2260                         bot_strategytoken_taken = FALSE;
2261                         if (bot_strategytoken)
2262                                 bot_strategytoken = bot_strategytoken.nextbot;
2263                         if (!bot_strategytoken)
2264                                 bot_strategytoken = bot_list;
2265                 }
2266
2267                 if (botframe_nextdangertime < time)
2268                 {
2269                         local float interval;
2270                         interval = cvar("bot_ai_dangerdetectioninterval");
2271                         if (botframe_nextdangertime < time - interval * 1.5)
2272                                 botframe_nextdangertime = time;
2273                         botframe_nextdangertime = botframe_nextdangertime + interval;
2274                         botframe_updatedangerousobjects(cvar("bot_ai_dangerdetectionupdates"));
2275                 }
2276         }
2277
2278         if (cvar("g_waypointeditor"))
2279                 botframe_showwaypointlinks();
2280 };