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