Debian Codegraph @

code/game/ai_main.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22 //
23
24 /*****************************************************************************
25 * name: ai_main.c
26 *
27 * desc: Quake3 bot AI
28 *
29 * $Archive: /MissionPack/code/game/ai_main.c $
30 *
31 *****************************************************************************/
32
33
34 #include "g_local.h"
35 #include "../qcommon/q_shared.h"
36 #include "../botlib/botlib.h" //bot lib interface
37 #include "../botlib/be_aas.h"
38 #include "../botlib/be_ea.h"
39 #include "../botlib/be_ai_char.h"
40 #include "../botlib/be_ai_chat.h"
41 #include "../botlib/be_ai_gen.h"
42 #include "../botlib/be_ai_goal.h"
43 #include "../botlib/be_ai_move.h"
44 #include "../botlib/be_ai_weap.h"
45 //
46 #include "ai_main.h"
47 #include "ai_dmq3.h"
48 #include "ai_chat.h"
49 #include "ai_cmd.h"
50 #include "ai_dmnet.h"
51 #include "ai_vcmd.h"
52
53 //
54 #include "chars.h"
55 #include "inv.h"
56 #include "syn.h"
57
58
59 //bot states
60 bot_state_t *botstates[MAX_CLIENTS];
61 //number of bots
62 int numbots;
63 //floating point time
64 float floattime;
65 //time to do a regular update
66 float regularupdate_time;
67 //
68 int bot_interbreed;
69 int bot_interbreedmatchcount;
70 //
71 vmCvar_t bot_thinktime;
72 vmCvar_t bot_memorydump;
73 vmCvar_t bot_saveroutingcache;
74 vmCvar_t bot_pause;
75 vmCvar_t bot_report;
76 vmCvar_t bot_testsolid;
77 vmCvar_t bot_testclusters;
78 vmCvar_t bot_developer;
79 vmCvar_t bot_interbreedchar;
80 vmCvar_t bot_interbreedbots;
81 vmCvar_t bot_interbreedcycle;
82 vmCvar_t bot_interbreedwrite;
83
84
85 void ExitLevel( void );
86
87
88 /*
89 ==================
90 BotAI_Print
91 ==================
92 */
93 void QDECL BotAI_Print(int type, char *fmt, ...) {
94 char str[2048];
95 va_list ap;
96
97 va_start(ap, fmt);
98 Q_vsnprintf(str, sizeof(str), fmt, ap);
99 va_end(ap);
100
101 switch(type) {
102 case PRT_MESSAGE: {
103 G_Printf("%s", str);
104 break;
105 }
106 case PRT_WARNING: {
107 G_Printf( S_COLOR_YELLOW "Warning: %s", str );
108 break;
109 }
110 case PRT_ERROR: {
111 G_Printf( S_COLOR_RED "Error: %s", str );
112 break;
113 }
114 case PRT_FATAL: {
115 G_Printf( S_COLOR_RED "Fatal: %s", str );
116 break;
117 }
118 case PRT_EXIT: {
119 G_Error( S_COLOR_RED "Exit: %s", str );
120 break;
121 }
122 default: {
123 G_Printf( "unknown print type\n" );
124 break;
125 }
126 }
127 }
128
129
130 /*
131 ==================
132 BotAI_Trace
133 ==================
134 */
135 void BotAI_Trace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask) {
136 trace_t trace;
137
138 trap_Trace(&trace, start, mins, maxs, end, passent, contentmask);
139 //copy the trace information
140 bsptrace->allsolid = trace.allsolid;
141 bsptrace->startsolid = trace.startsolid;
142 bsptrace->fraction = trace.fraction;
143 VectorCopy(trace.endpos, bsptrace->endpos);
144 bsptrace->plane.dist = trace.plane.dist;
145 VectorCopy(trace.plane.normal, bsptrace->plane.normal);
146 bsptrace->plane.signbits = trace.plane.signbits;
147 bsptrace->plane.type = trace.plane.type;
148 bsptrace->surface.value = 0;
149 bsptrace->surface.flags = trace.surfaceFlags;
150 bsptrace->ent = trace.entityNum;
151 bsptrace->exp_dist = 0;
152 bsptrace->sidenum = 0;
153 bsptrace->contents = 0;
154 }
155
156 /*
157 ==================
158 BotAI_GetClientState
159 ==================
160 */
161 int BotAI_GetClientState( int clientNum, playerState_t *state ) {
162 gentity_t *ent;
163
164 ent = &g_entities[clientNum];
165 if ( !ent->inuse ) {
166 return qfalse;
167 }
168 if ( !ent->client ) {
169 return qfalse;
170 }
171
172 memcpy( state, &ent->client->ps, sizeof(playerState_t) );
173 return qtrue;
174 }
175
176 /*
177 ==================
178 BotAI_GetEntityState
179 ==================
180 */
181 int BotAI_GetEntityState( int entityNum, entityState_t *state ) {
182 gentity_t *ent;
183
184 ent = &g_entities[entityNum];
185 memset( state, 0, sizeof(entityState_t) );
186 if (!ent->inuse) return qfalse;
187 if (!ent->r.linked) return qfalse;
188 if (ent->r.svFlags & SVF_NOCLIENT) return qfalse;
189 memcpy( state, &ent->s, sizeof(entityState_t) );
190 return qtrue;
191 }
192
193 /*
194 ==================
195 BotAI_GetSnapshotEntity
196 ==================
197 */
198 int BotAI_GetSnapshotEntity( int clientNum, int sequence, entityState_t *state ) {
199 int entNum;
200
201 entNum = trap_BotGetSnapshotEntity( clientNum, sequence );
202 if ( entNum == -1 ) {
203 memset(state, 0, sizeof(entityState_t));
204 return -1;
205 }
206
207 BotAI_GetEntityState( entNum, state );
208
209 return sequence + 1;
210 }
211
212 /*
213 ==================
214 BotAI_BotInitialChat
215 ==================
216 */
217 void QDECL BotAI_BotInitialChat( bot_state_t *bs, char *type, ... ) {
218 int i, mcontext;
219 va_list ap;
220 char *p;
221 char *vars[MAX_MATCHVARIABLES];
222
223 memset(vars, 0, sizeof(vars));
224 va_start(ap, type);
225 p = va_arg(ap, char *);
226 for (i = 0; i < MAX_MATCHVARIABLES; i++) {
227 if( !p ) {
228 break;
229 }
230 vars[i] = p;
231 p = va_arg(ap, char *);
232 }
233 va_end(ap);
234
235 mcontext = BotSynonymContext(bs);
236
237 trap_BotInitialChat( bs->cs, type, mcontext, vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7] );
238 }
239
240
241 /*
242 ==================
243 BotTestAAS
244 ==================
245 */
246 void BotTestAAS(vec3_t origin) {
247 int areanum;
248 aas_areainfo_t info;
249
250 trap_Cvar_Update(&bot_testsolid);
251 trap_Cvar_Update(&bot_testclusters);
252 if (bot_testsolid.integer) {
253 if (!trap_AAS_Initialized()) return;
254 areanum = BotPointAreaNum(origin);
255 if (areanum) BotAI_Print(PRT_MESSAGE, "\rempty area");
256 else BotAI_Print(PRT_MESSAGE, "\r^1SOLID area");
257 }
258 else if (bot_testclusters.integer) {
259 if (!trap_AAS_Initialized()) return;
260 areanum = BotPointAreaNum(origin);
261 if (!areanum)
262 BotAI_Print(PRT_MESSAGE, "\r^1Solid! ");
263 else {
264 trap_AAS_AreaInfo(areanum, &info);
265 BotAI_Print(PRT_MESSAGE, "\rarea %d, cluster %d ", areanum, info.cluster);
266 }
267 }
268 }
269
270 /*
271 ==================
272 BotReportStatus
273 ==================
274 */
275 void BotReportStatus(bot_state_t *bs) {
276 char goalname[MAX_MESSAGE_SIZE];
277 char netname[MAX_MESSAGE_SIZE];
278 char *leader, flagstatus[32];
279 //
280 ClientName(bs->client, netname, sizeof(netname));
281 if (Q_stricmp(netname, bs->teamleader) == 0) leader = "L";
282 else leader = " ";
283
284 strcpy(flagstatus, " ");
285 if (gametype == GT_CTF) {
286 if (BotCTFCarryingFlag(bs)) {
287 if (BotTeam(bs) == TEAM_RED) strcpy(flagstatus, S_COLOR_RED"F ");
288 else strcpy(flagstatus, S_COLOR_BLUE"F ");
289 }
290 }
291 #ifdef MISSIONPACK
292 else if (gametype == GT_1FCTF) {
293 if (Bot1FCTFCarryingFlag(bs)) {
294 if (BotTeam(bs) == TEAM_RED) strcpy(flagstatus, S_COLOR_RED"F ");
295 else strcpy(flagstatus, S_COLOR_BLUE"F ");
296 }
297 }
298 else if (gametype == GT_HARVESTER) {
299 if (BotHarvesterCarryingCubes(bs)) {
300 if (BotTeam(bs) == TEAM_RED) Com_sprintf(flagstatus, sizeof(flagstatus), S_COLOR_RED"%2d", bs->inventory[INVENTORY_REDCUBE]);
301 else Com_sprintf(flagstatus, sizeof(flagstatus), S_COLOR_BLUE"%2d", bs->inventory[INVENTORY_BLUECUBE]);
302 }
303 }
304 #endif
305
306 switch(bs->ltgtype) {
307 case LTG_TEAMHELP:
308 {
309 EasyClientName(bs->teammate, goalname, sizeof(goalname));
310 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: helping %s\n", netname, leader, flagstatus, goalname);
311 break;
312 }
313 case LTG_TEAMACCOMPANY:
314 {
315 EasyClientName(bs->teammate, goalname, sizeof(goalname));
316 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: accompanying %s\n", netname, leader, flagstatus, goalname);
317 break;
318 }
319 case LTG_DEFENDKEYAREA:
320 {
321 trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
322 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: defending %s\n", netname, leader, flagstatus, goalname);
323 break;
324 }
325 case LTG_GETITEM:
326 {
327 trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
328 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: getting item %s\n", netname, leader, flagstatus, goalname);
329 break;
330 }
331 case LTG_KILL:
332 {
333 ClientName(bs->teamgoal.entitynum, goalname, sizeof(goalname));
334 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: killing %s\n", netname, leader, flagstatus, goalname);
335 break;
336 }
337 case LTG_CAMP:
338 case LTG_CAMPORDER:
339 {
340 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: camping\n", netname, leader, flagstatus);
341 break;
342 }
343 case LTG_PATROL:
344 {
345 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: patrolling\n", netname, leader, flagstatus);
346 break;
347 }
348 case LTG_GETFLAG:
349 {
350 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: capturing flag\n", netname, leader, flagstatus);
351 break;
352 }
353 case LTG_RUSHBASE:
354 {
355 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: rushing base\n", netname, leader, flagstatus);
356 break;
357 }
358 case LTG_RETURNFLAG:
359 {
360 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: returning flag\n", netname, leader, flagstatus);
361 break;
362 }
363 case LTG_ATTACKENEMYBASE:
364 {
365 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: attacking the enemy base\n", netname, leader, flagstatus);
366 break;
367 }
368 case LTG_HARVEST:
369 {
370 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: harvesting\n", netname, leader, flagstatus);
371 break;
372 }
373 default:
374 {
375 BotAI_Print(PRT_MESSAGE, "%-20s%s%s: roaming\n", netname, leader, flagstatus);
376 break;
377 }
378 }
379 }
380
381 /*
382 ==================
383 BotTeamplayReport
384 ==================
385 */
386 void BotTeamplayReport(void) {
387 int i;
388 char buf[MAX_INFO_STRING];
389
390 BotAI_Print(PRT_MESSAGE, S_COLOR_RED"RED\n");
391 for (i = 0; i < level.maxclients; i++) {
392 //
393 if ( !botstates[i] || !botstates[i]->inuse ) continue;
394 //
395 trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
396 //if no config string or no name
397 if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
398 //skip spectators
399 if (atoi(Info_ValueForKey(buf, "t")) == TEAM_RED) {
400 BotReportStatus(botstates[i]);
401 }
402 }
403 BotAI_Print(PRT_MESSAGE, S_COLOR_BLUE"BLUE\n");
404 for (i = 0; i < level.maxclients; i++) {
405 //
406 if ( !botstates[i] || !botstates[i]->inuse ) continue;
407 //
408 trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
409 //if no config string or no name
410 if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n"))) continue;
411 //skip spectators
412 if (atoi(Info_ValueForKey(buf, "t")) == TEAM_BLUE) {
413 BotReportStatus(botstates[i]);
414 }
415 }
416 }
417
418 /*
419 ==================
420 BotSetInfoConfigString
421 ==================
422 */
423 void BotSetInfoConfigString(bot_state_t *bs) {
424 char goalname[MAX_MESSAGE_SIZE];
425 char netname[MAX_MESSAGE_SIZE];
426 char action[MAX_MESSAGE_SIZE];
427 char *leader, carrying[32], *cs;
428 bot_goal_t goal;
429 //
430 ClientName(bs->client, netname, sizeof(netname));
431 if (Q_stricmp(netname, bs->teamleader) == 0) leader = "L";
432 else leader = " ";
433
434 strcpy(carrying, " ");
435 if (gametype == GT_CTF) {
436 if (BotCTFCarryingFlag(bs)) {
437 strcpy(carrying, "F ");
438 }
439 }
440 #ifdef MISSIONPACK
441 else if (gametype == GT_1FCTF) {
442 if (Bot1FCTFCarryingFlag(bs)) {
443 strcpy(carrying, "F ");
444 }
445 }
446 else if (gametype == GT_HARVESTER) {
447 if (BotHarvesterCarryingCubes(bs)) {
448 if (BotTeam(bs) == TEAM_RED) Com_sprintf(carrying, sizeof(carrying), "%2d", bs->inventory[INVENTORY_REDCUBE]);
449 else Com_sprintf(carrying, sizeof(carrying), "%2d", bs->inventory[INVENTORY_BLUECUBE]);
450 }
451 }
452 #endif
453
454 switch(bs->ltgtype) {
455 case LTG_TEAMHELP:
456 {
457 EasyClientName(bs->teammate, goalname, sizeof(goalname));
458 Com_sprintf(action, sizeof(action), "helping %s", goalname);
459 break;
460 }
461 case LTG_TEAMACCOMPANY:
462 {
463 EasyClientName(bs->teammate, goalname, sizeof(goalname));
464 Com_sprintf(action, sizeof(action), "accompanying %s", goalname);
465 break;
466 }
467 case LTG_DEFENDKEYAREA:
468 {
469 trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
470 Com_sprintf(action, sizeof(action), "defending %s", goalname);
471 break;
472 }
473 case LTG_GETITEM:
474 {
475 trap_BotGoalName(bs->teamgoal.number, goalname, sizeof(goalname));
476 Com_sprintf(action, sizeof(action), "getting item %s", goalname);
477 break;
478 }
479 case LTG_KILL:
480 {
481 ClientName(bs->teamgoal.entitynum, goalname, sizeof(goalname));
482 Com_sprintf(action, sizeof(action), "killing %s", goalname);
483 break;
484 }
485 case LTG_CAMP:
486 case LTG_CAMPORDER:
487 {
488 Com_sprintf(action, sizeof(action), "camping");
489 break;
490 }
491 case LTG_PATROL:
492 {
493 Com_sprintf(action, sizeof(action), "patrolling");
494 break;
495 }
496 case LTG_GETFLAG:
497 {
498 Com_sprintf(action, sizeof(action), "capturing flag");
499 break;
500 }
501 case LTG_RUSHBASE:
502 {
503 Com_sprintf(action, sizeof(action), "rushing base");
504 break;
505 }
506 case LTG_RETURNFLAG:
507 {
508 Com_sprintf(action, sizeof(action), "returning flag");
509 break;
510 }
511 case LTG_ATTACKENEMYBASE:
512 {
513 Com_sprintf(action, sizeof(action), "attacking the enemy base");
514 break;
515 }
516 case LTG_HARVEST:
517 {
518 Com_sprintf(action, sizeof(action), "harvesting");
519 break;
520 }
521 default:
522 {
523 trap_BotGetTopGoal(bs->gs, &goal);
524 trap_BotGoalName(goal.number, goalname, sizeof(goalname));
525 Com_sprintf(action, sizeof(action), "roaming %s", goalname);
526 break;
527 }
528 }
529 cs = va("l\\%s\\c\\%s\\a\\%s",
530 leader,
531 carrying,
532 action);
533 trap_SetConfigstring (CS_BOTINFO + bs->client, cs);
534 }
535
536 /*
537 ==============
538 BotUpdateInfoConfigStrings
539 ==============
540 */
541 void BotUpdateInfoConfigStrings(void) {
542 int i;
543 char buf[MAX_INFO_STRING];
544
545 for (i = 0; i < level.maxclients; i++) {
546 //
547 if ( !botstates[i] || !botstates[i]->inuse )
548 continue;
549 //
550 trap_GetConfigstring(CS_PLAYERS+i, buf, sizeof(buf));
551 //if no config string or no name
552 if (!strlen(buf) || !strlen(Info_ValueForKey(buf, "n")))
553 continue;
554 BotSetInfoConfigString(botstates[i]);
555 }
556 }
557
558 /*
559 ==============
560 BotInterbreedBots
561 ==============
562 */
563 void BotInterbreedBots(void) {
564 float ranks[MAX_CLIENTS];
565 int parent1, parent2, child;
566 int i;
567
568 // get rankings for all the bots
569 for (i = 0; i < MAX_CLIENTS; i++) {
570 if ( botstates[i] && botstates[i]->inuse ) {
571 ranks[i] = botstates[i]->num_kills * 2 - botstates[i]->num_deaths;
572 }
573 else {
574 ranks[i] = -1;
575 }
576 }
577
578 if (trap_GeneticParentsAndChildSelection(MAX_CLIENTS, ranks, &parent1, &parent2, &child)) {
579 trap_BotInterbreedGoalFuzzyLogic(botstates[parent1]->gs, botstates[parent2]->gs, botstates[child]->gs);
580 trap_BotMutateGoalFuzzyLogic(botstates[child]->gs, 1);
581 }
582 // reset the kills and deaths
583 for (i = 0; i < MAX_CLIENTS; i++) {
584 if (botstates[i] && botstates[i]->inuse) {
585 botstates[i]->num_kills = 0;
586 botstates[i]->num_deaths = 0;
587 }
588 }
589 }
590
591 /*
592 ==============
593 BotWriteInterbreeded
594 ==============
595 */
596 void BotWriteInterbreeded(char *filename) {
597 float rank, bestrank;
598 int i, bestbot;
599
600 bestrank = 0;
601 bestbot = -1;
602 // get the best bot
603 for (i = 0; i < MAX_CLIENTS; i++) {
604 if ( botstates[i] && botstates[i]->inuse ) {
605 rank = botstates[i]->num_kills * 2 - botstates[i]->num_deaths;
606 }
607 else {
608 rank = -1;
609 }
610 if (rank > bestrank) {
611 bestrank = rank;
612 bestbot = i;
613 }
614 }
615 if (bestbot >= 0) {
616 //write out the new goal fuzzy logic
617 trap_BotSaveGoalFuzzyLogic(botstates[bestbot]->gs, filename);
618 }
619 }
620
621 /*
622 ==============
623 BotInterbreedEndMatch
624
625 add link back into ExitLevel?
626 ==============
627 */
628 void BotInterbreedEndMatch(void) {
629
630 if (!bot_interbreed) return;
631 bot_interbreedmatchcount++;
632 if (bot_interbreedmatchcount >= bot_interbreedcycle.integer) {
633 bot_interbreedmatchcount = 0;
634 //
635 trap_Cvar_Update(&bot_interbreedwrite);
636 if (strlen(bot_interbreedwrite.string)) {
637 BotWriteInterbreeded(bot_interbreedwrite.string);
638 trap_Cvar_Set("bot_interbreedwrite", "");
639 }
640 BotInterbreedBots();
641 }
642 }
643
644 /*
645 ==============
646 BotInterbreeding
647 ==============
648 */
649 void BotInterbreeding(void) {
650 int i;
651
652 trap_Cvar_Update(&bot_interbreedchar);
653 if (!strlen(bot_interbreedchar.string)) return;
654 //make sure we are in tournament mode
655 if (gametype != GT_TOURNAMENT) {
656 trap_Cvar_Set("g_gametype", va("%d", GT_TOURNAMENT));
657 ExitLevel();
658 return;
659 }
660 //shutdown all the bots
661 for (i = 0; i < MAX_CLIENTS; i++) {
662 if (botstates[i] && botstates[i]->inuse) {
663 BotAIShutdownClient(botstates[i]->client, qfalse);
664 }
665 }
666 //make sure all item weight configs are reloaded and Not shared
667 trap_BotLibVarSet("bot_reloadcharacters", "1");
668 //add a number of bots using the desired bot character
669 for (i = 0; i < bot_interbreedbots.integer; i++) {
670 trap_SendConsoleCommand( EXEC_INSERT, va("addbot %s 4 free %i %s%d\n",
671 bot_interbreedchar.string, i * 50, bot_interbreedchar.string, i) );
672 }
673 //
674 trap_Cvar_Set("bot_interbreedchar", "");
675 bot_interbreed = qtrue;
676 }
677
678 /*
679 ==============
680 BotEntityInfo
681 ==============
682 */
683 void BotEntityInfo(int entnum, aas_entityinfo_t *info) {
684 trap_AAS_EntityInfo(entnum, info);
685 }
686
687 /*
688 ==============
689 NumBots
690 ==============
691 */
692 int NumBots(void) {
693 return numbots;
694 }
695
696 /*
697 ==============
698 BotTeamLeader
699 ==============
700 */
701 int BotTeamLeader(bot_state_t *bs) {
702 int leader;
703
704 leader = ClientFromName(bs->teamleader);
705 if (leader < 0) return qfalse;
706 if (!botstates[leader] || !botstates[leader]->inuse) return qfalse;
707 return qtrue;
708 }
709
710 /*
711 ==============
712 AngleDifference
713 ==============
714 */
715 float AngleDifference(float ang1, float ang2) {
716 float diff;
717
718 diff = ang1 - ang2;
719 if (ang1 > ang2) {
720 if (diff > 180.0) diff -= 360.0;
721 }
722 else {
723 if (diff < -180.0) diff += 360.0;
724 }
725 return diff;
726 }
727
728 /*
729 ==============
730 BotChangeViewAngle
731 ==============
732 */
733 float BotChangeViewAngle(float angle, float ideal_angle, float speed) {
734 float move;
735
736 angle = AngleMod(angle);
737 ideal_angle = AngleMod(ideal_angle);
738 if (angle == ideal_angle) return angle;
739 move = ideal_angle - angle;
740 if (ideal_angle > angle) {
741 if (move > 180.0) move -= 360.0;
742 }
743 else {
744 if (move < -180.0) move += 360.0;
745 }
746 if (move > 0) {
747 if (move > speed) move = speed;
748 }
749 else {
750 if (move < -speed) move = -speed;
751 }
752 return AngleMod(angle + move);
753 }
754
755 /*
756 ==============
757 BotChangeViewAngles
758 ==============
759 */
760 void BotChangeViewAngles(bot_state_t *bs, float thinktime) {
761 float diff, factor, maxchange, anglespeed, disired_speed;
762 int i;
763
764 if (bs->ideal_viewangles[PITCH] > 180) bs->ideal_viewangles[PITCH] -= 360;
765 //
766 if (bs->enemy >= 0) {
767 factor = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_VIEW_FACTOR, 0.01f, 1);
768 maxchange = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_VIEW_MAXCHANGE, 1, 1800);
769 }
770 else {
771 factor = 0.05f;
772 maxchange = 360;
773 }
774 if (maxchange < 240) maxchange = 240;
775 maxchange *= thinktime;
776 for (i = 0; i < 2; i++) {
777 //
778 if (bot_challenge.integer) {
779 //smooth slowdown view model
780 diff = fabs(AngleDifference(bs->viewangles[i], bs->ideal_viewangles[i]));
781 anglespeed = diff * factor;
782 if (anglespeed > maxchange) anglespeed = maxchange;
783 bs->viewangles[i] = BotChangeViewAngle(bs->viewangles[i],
784 bs->ideal_viewangles[i], anglespeed);
785 }
786 else {
787 //over reaction view model
788 bs->viewangles[i] = AngleMod(bs->viewangles[i]);
789 bs->ideal_viewangles[i] = AngleMod(bs->ideal_viewangles[i]);
790 diff = AngleDifference(bs->viewangles[i], bs->ideal_viewangles[i]);
791 disired_speed = diff * factor;
792 bs->viewanglespeed[i] += (bs->viewanglespeed[i] - disired_speed);
793 if (bs->viewanglespeed[i] > 180) bs->viewanglespeed[i] = maxchange;
794 if (bs->viewanglespeed[i] < -180) bs->viewanglespeed[i] = -maxchange;
795 anglespeed = bs->viewanglespeed[i];
796 if (anglespeed > maxchange) anglespeed = maxchange;
797 if (anglespeed < -maxchange) anglespeed = -maxchange;
798 bs->viewangles[i] += anglespeed;
799 bs->viewangles[i] = AngleMod(bs->viewangles[i]);
800 //demping
801 bs->viewanglespeed[i] *= 0.45 * (1 - factor);
802 }
803 //BotAI_Print(PRT_MESSAGE, "ideal_angles %f %f\n", bs->ideal_viewangles[0], bs->ideal_viewangles[1], bs->ideal_viewangles[2]);`
804 //bs->viewangles[i] = bs->ideal_viewangles[i];
805 }
806 //bs->viewangles[PITCH] = 0;
807 if (bs->viewangles[PITCH] > 180) bs->viewangles[PITCH] -= 360;
808 //elementary action: view
809 trap_EA_View(bs->client, bs->viewangles);
810 }
811
812 /*
813 ==============
814 BotInputToUserCommand
815 ==============
816 */
817 void BotInputToUserCommand(bot_input_t *bi, usercmd_t *ucmd, int delta_angles[3], int time) {
818 vec3_t angles, forward, right;
819 short temp;
820 int j;
821 float f, r, u, m;
822
823 //clear the whole structure
824 memset(ucmd, 0, sizeof(usercmd_t));
825 //the duration for the user command in milli seconds
826 ucmd->serverTime = time;
827 //
828 if (bi->actionflags & ACTION_DELAYEDJUMP) {
829 bi->actionflags |= ACTION_JUMP;
830 bi->actionflags &= ~ACTION_DELAYEDJUMP;
831 }
832 //set the buttons
833 if (bi->actionflags & ACTION_RESPAWN) ucmd->buttons = BUTTON_ATTACK;
834 if (bi->actionflags & ACTION_ATTACK) ucmd->buttons |= BUTTON_ATTACK;
835 if (bi->actionflags & ACTION_TALK) ucmd->buttons |= BUTTON_TALK;
836 if (bi->actionflags & ACTION_GESTURE) ucmd->buttons |= BUTTON_GESTURE;
837 if (bi->actionflags & ACTION_USE) ucmd->buttons |= BUTTON_USE_HOLDABLE;
838 if (bi->actionflags & ACTION_WALK) ucmd->buttons |= BUTTON_WALKING;
839 if (bi->actionflags & ACTION_AFFIRMATIVE) ucmd->buttons |= BUTTON_AFFIRMATIVE;
840 if (bi->actionflags & ACTION_NEGATIVE) ucmd->buttons |= BUTTON_NEGATIVE;
841 if (bi->actionflags & ACTION_GETFLAG) ucmd->buttons |= BUTTON_GETFLAG;
842 if (bi->actionflags & ACTION_GUARDBASE) ucmd->buttons |= BUTTON_GUARDBASE;
843 if (bi->actionflags & ACTION_PATROL) ucmd->buttons |= BUTTON_PATROL;
844 if (bi->actionflags & ACTION_FOLLOWME) ucmd->buttons |= BUTTON_FOLLOWME;
845 //
846 ucmd->weapon = bi->weapon;
847 //set the view angles
848 //NOTE: the ucmd->angles are the angles WITHOUT the delta angles
849 ucmd->angles[PITCH] = ANGLE2SHORT(bi->viewangles[PITCH]);
850 ucmd->angles[YAW] = ANGLE2SHORT(bi->viewangles[YAW]);
851 ucmd->angles[ROLL] = ANGLE2SHORT(bi->viewangles[ROLL]);
852 //subtract the delta angles
853 for (j = 0; j < 3; j++) {
854 temp = ucmd->angles[j] - delta_angles[j];
855 /*NOTE: disabled because temp should be mod first
856 if ( j == PITCH ) {
857 // don't let the player look up or down more than 90 degrees
858 if ( temp > 16000 ) temp = 16000;
859 else if ( temp < -16000 ) temp = -16000;
860 }
861 */
862 ucmd->angles[j] = temp;
863 }
864 //NOTE: movement is relative to the REAL view angles
865 //get the horizontal forward and right vector
866 //get the pitch in the range [-180, 180]
867 if (bi->dir[2]) angles[PITCH] = bi->viewangles[PITCH];
868 else angles[PITCH] = 0;
869 angles[YAW] = bi->viewangles[YAW];
870 angles[ROLL] = 0;
871 AngleVectors(angles, forward, right, NULL);
872 //bot input speed is in the range [0, 400]
873 bi->speed = bi->speed * 127 / 400;
874 //set the view independent movement
875 f = DotProduct(forward, bi->dir);
876 r = DotProduct(right, bi->dir);
877 u = fabs(forward[2]) * bi->dir[2];
878 m = fabs(f);
879
880 if (fabs(r) > m) {
881 m = fabs(r);
882 }
883
884 if (fabs(u) > m) {
885 m = fabs(u);
886 }
887
888 if (m > 0) {
889 f *= bi->speed / m;
890 r *= bi->speed / m;
891 u *= bi->speed / m;
892 }
893
894 ucmd->forwardmove = f;
895 ucmd->rightmove = r;
896 ucmd->upmove = u;
897
898 if (bi->actionflags & ACTION_MOVEFORWARD) ucmd->forwardmove = 127;
899 if (bi->actionflags & ACTION_MOVEBACK) ucmd->forwardmove = -127;
900 if (bi->actionflags & ACTION_MOVELEFT) ucmd->rightmove = -127;
901 if (bi->actionflags & ACTION_MOVERIGHT) ucmd->rightmove = 127;
902 //jump/moveup
903 if (bi->actionflags & ACTION_JUMP) ucmd->upmove = 127;
904 //crouch/movedown
905 if (bi->actionflags & ACTION_CROUCH) ucmd->upmove = -127;
906 }
907
908 /*
909 ==============
910 BotUpdateInput
911 ==============
912 */
913 void BotUpdateInput(bot_state_t *bs, int time, int elapsed_time) {
914 bot_input_t bi;
915 int j;
916
917 //add the delta angles to the bot's current view angles
918 for (j = 0; j < 3; j++) {
919 bs->viewangles[j] = AngleMod(bs->viewangles[j] + SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
920 }
921 //change the bot view angles
922 BotChangeViewAngles(bs, (float) elapsed_time / 1000);
923 //retrieve the bot input
924 trap_EA_GetInput(bs->client, (float) time / 1000, &bi);
925 //respawn hack
926 if (bi.actionflags & ACTION_RESPAWN) {
927 if (bs->lastucmd.buttons & BUTTON_ATTACK) bi.actionflags &= ~(ACTION_RESPAWN|ACTION_ATTACK);
928 }
929 //convert the bot input to a usercmd
930 BotInputToUserCommand(&bi, &bs->lastucmd, bs->cur_ps.delta_angles, time);
931 //subtract the delta angles
932 for (j = 0; j < 3; j++) {
933 bs->viewangles[j] = AngleMod(bs->viewangles[j] - SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
934 }
935 }
936
937 /*
938 ==============
939 BotAIRegularUpdate
940 ==============
941 */
942 void BotAIRegularUpdate(void) {
943 if (regularupdate_time < FloatTime()) {
944 trap_BotUpdateEntityItems();
945 regularupdate_time = FloatTime() + 0.3;
946 }
947 }
948
949 /*
950 ==============
951 RemoveColorEscapeSequences
952 ==============
953 */
954 void RemoveColorEscapeSequences( char *text ) {
955 int i, l;
956
957 l = 0;
958 for ( i = 0; text[i]; i++ ) {
959 if (Q_IsColorString(&text[i])) {
960 i++;
961 continue;
962 }
963 if (text[i] > 0x7E)
964 continue;
965 text[l++] = text[i];
966 }
967 text[l] = '\0';
968 }
969
970 /*
971 ==============
972 BotAI
973 ==============
974 */
975 int BotAI(int client, float thinktime) {
976 bot_state_t *bs;
977 char buf[1024], *args;
978 int j;
979
980 trap_EA_ResetInput(client);
981 //
982 bs = botstates[client];
983 if (!bs || !bs->inuse) {
984 BotAI_Print(PRT_FATAL, "BotAI: client %d is not setup\n", client);
985 return qfalse;
986 }
987
988 //retrieve the current client state
989 if (!BotAI_GetClientState(client, &bs->cur_ps)) {
990 BotAI_Print(PRT_FATAL, "BotAI: failed to get player state for player %d\n", client);
991 return qfalse;
992 }
993 //retrieve any waiting server commands
994 while( trap_BotGetServerCommand(client, buf, sizeof(buf)) ) {
995 //have buf point to the command and args to the command arguments
996 args = strchr( buf, ' ');
997 if (!args) continue;
998 *args++ = '\0';
999
1000 //remove color espace sequences from the arguments
1001 RemoveColorEscapeSequences( args );
1002
1003 if (!Q_stricmp(buf, "cp "))
1004 { /*CenterPrintf*/ }
1005 else if (!Q_stricmp(buf, "cs"))
1006 { /*ConfigStringModified*/ }
1007 else if (!Q_stricmp(buf, "print")) {
1008 //remove first and last quote from the chat message
1009 memmove(args, args+1, strlen(args));
1010 args[strlen(args)-1] = '\0';
1011 trap_BotQueueConsoleMessage(bs->cs, CMS_NORMAL, args);
1012 }
1013 else if (!Q_stricmp(buf, "chat")) {
1014 //remove first and last quote from the chat message
1015 memmove(args, args+1, strlen(args));
1016 args[strlen(args)-1] = '\0';
1017 trap_BotQueueConsoleMessage(bs->cs, CMS_CHAT, args);
1018 }
1019 else if (!Q_stricmp(buf, "tchat")) {
1020 //remove first and last quote from the chat message
1021 memmove(args, args+1, strlen(args));
1022 args[strlen(args)-1] = '\0';
1023 trap_BotQueueConsoleMessage(bs->cs, CMS_CHAT, args);
1024 }
1025 #ifdef MISSIONPACK
1026 else if (!Q_stricmp(buf, "vchat")) {
1027 BotVoiceChatCommand(bs, SAY_ALL, args);
1028 }
1029 else if (!Q_stricmp(buf, "vtchat")) {
1030 BotVoiceChatCommand(bs, SAY_TEAM, args);
1031 }
1032 else if (!Q_stricmp(buf, "vtell")) {
1033 BotVoiceChatCommand(bs, SAY_TELL, args);
1034 }
1035 #endif
1036 else if (!Q_stricmp(buf, "scores"))
1037 { /*FIXME: parse scores?*/ }
1038 else if (!Q_stricmp(buf, "clientLevelShot"))
1039 { /*ignore*/ }
1040 }
1041 //add the delta angles to the bot's current view angles
1042 for (j = 0; j < 3; j++) {
1043 bs->viewangles[j] = AngleMod(bs->viewangles[j] + SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
1044 }
1045 //increase the local time of the bot
1046 bs->ltime += thinktime;
1047 //
1048 bs->thinktime = thinktime;
1049 //origin of the bot
1050 VectorCopy(bs->cur_ps.origin, bs->origin);
1051 //eye coordinates of the bot
1052 VectorCopy(bs->cur_ps.origin, bs->eye);
1053 bs->eye[2] += bs->cur_ps.viewheight;
1054 //get the area the bot is in
1055 bs->areanum = BotPointAreaNum(bs->origin);
1056 //the real AI
1057 BotDeathmatchAI(bs, thinktime);
1058 //set the weapon selection every AI frame
1059 trap_EA_SelectWeapon(bs->client, bs->weaponnum);
1060 //subtract the delta angles
1061 for (j = 0; j < 3; j++) {
1062 bs->viewangles[j] = AngleMod(bs->viewangles[j] - SHORT2ANGLE(bs->cur_ps.delta_angles[j]));
1063 }
1064 //everything was ok
1065 return qtrue;
1066 }
1067
1068 /*
1069 ==================
1070 BotScheduleBotThink
1071 ==================
1072 */
1073 void BotScheduleBotThink(void) {
1074 int i, botnum;
1075
1076 botnum = 0;
1077
1078 for( i = 0; i < MAX_CLIENTS; i++ ) {
1079 if( !botstates[i] || !botstates[i]->inuse ) {
1080 continue;
1081 }
1082 //initialize the bot think residual time
1083 botstates[i]->botthink_residual = bot_thinktime.integer * botnum / numbots;
1084 botnum++;
1085 }
1086 }
1087
1088 /*
1089 ==============
1090 BotWriteSessionData
1091 ==============
1092 */
1093 void BotWriteSessionData(bot_state_t *bs) {
1094 const char *s;
1095 const char *var;
1096
1097 s = va(
1098 "%i %i %i %i %i %i %i %i"
1099 " %f %f %f"
1100 " %f %f %f"
1101 " %f %f %f"
1102 " %f",
1103 bs->lastgoal_decisionmaker,
1104 bs->lastgoal_ltgtype,
1105 bs->lastgoal_teammate,
1106 bs->lastgoal_teamgoal.areanum,
1107 bs->lastgoal_teamgoal.entitynum,
1108 bs->lastgoal_teamgoal.flags,
1109 bs->lastgoal_teamgoal.iteminfo,
1110 bs->lastgoal_teamgoal.number,
1111 bs->lastgoal_teamgoal.origin[0],
1112 bs->lastgoal_teamgoal.origin[1],
1113 bs->lastgoal_teamgoal.origin[2],
1114 bs->lastgoal_teamgoal.mins[0],
1115 bs->lastgoal_teamgoal.mins[1],
1116 bs->lastgoal_teamgoal.mins[2],
1117 bs->lastgoal_teamgoal.maxs[0],
1118 bs->lastgoal_teamgoal.maxs[1],
1119 bs->lastgoal_teamgoal.maxs[2],
1120 bs->formation_dist
1121 );
1122
1123 var = va( "botsession%i", bs->client );
1124
1125 trap_Cvar_Set( var, s );
1126 }
1127
1128 /*
1129 ==============
1130 BotReadSessionData
1131 ==============
1132 */
1133 void BotReadSessionData(bot_state_t *bs) {
1134 char s[MAX_STRING_CHARS];
1135 const char *var;
1136
1137 var = va( "botsession%i", bs->client );
1138 trap_Cvar_VariableStringBuffer( var, s, sizeof(s) );
1139
1140 sscanf(s,
1141 "%i %i %i %i %i %i %i %i"
1142 " %f %f %f"
1143 " %f %f %f"
1144 " %f %f %f"
1145 " %f",
1146 &bs->lastgoal_decisionmaker,
1147 &bs->lastgoal_ltgtype,
1148 &bs->lastgoal_teammate,
1149 &bs->lastgoal_teamgoal.areanum,
1150 &bs->lastgoal_teamgoal.entitynum,
1151 &bs->lastgoal_teamgoal.flags,
1152 &bs->lastgoal_teamgoal.iteminfo,
1153 &bs->lastgoal_teamgoal.number,
1154 &bs->lastgoal_teamgoal.origin[0],
1155 &bs->lastgoal_teamgoal.origin[1],
1156 &bs->lastgoal_teamgoal.origin[2],
1157 &bs->lastgoal_teamgoal.mins[0],
1158 &bs->lastgoal_teamgoal.mins[1],
1159 &bs->lastgoal_teamgoal.mins[2],
1160 &bs->lastgoal_teamgoal.maxs[0],
1161 &bs->lastgoal_teamgoal.maxs[1],
1162 &bs->lastgoal_teamgoal.maxs[2],
1163 &bs->formation_dist
1164 );
1165 }
1166
1167 /*
1168 ==============
1169 BotAISetupClient
1170 ==============
1171 */
1172 int BotAISetupClient(int client, struct bot_settings_s *settings, qboolean restart) {
1173 char filename[144], name[144], gender[144];
1174 bot_state_t *bs;
1175 int errnum;
1176
1177 if (!botstates[client]) botstates[client] = G_Alloc(sizeof(bot_state_t));
1178 bs = botstates[client];
1179
1180 if (!bs) {
1181 return qfalse;
1182 }
1183
1184 if (bs && bs->inuse) {
1185 BotAI_Print(PRT_FATAL, "BotAISetupClient: client %d already setup\n", client);
1186 return qfalse;
1187 }
1188
1189 if (!trap_AAS_Initialized()) {
1190 BotAI_Print(PRT_FATAL, "AAS not initialized\n");
1191 return qfalse;
1192 }
1193
1194 //load the bot character
1195 bs->character = trap_BotLoadCharacter(settings->characterfile, settings->skill);
1196 if (!bs->character) {
1197 BotAI_Print(PRT_FATAL, "couldn't load skill %f from %s\n", settings->skill, settings->characterfile);
1198 return qfalse;
1199 }
1200 //copy the settings
1201 memcpy(&bs->settings, settings, sizeof(bot_settings_t));
1202 //allocate a goal state
1203 bs->gs = trap_BotAllocGoalState(client);
1204 //load the item weights
1205 trap_Characteristic_String(bs->character, CHARACTERISTIC_ITEMWEIGHTS, filename, sizeof(filename));
1206 errnum = trap_BotLoadItemWeights(bs->gs, filename);
1207 if (errnum != BLERR_NOERROR) {
1208 trap_BotFreeGoalState(bs->gs);
1209 return qfalse;
1210 }
1211 //allocate a weapon state
1212 bs->ws = trap_BotAllocWeaponState();
1213 //load the weapon weights
1214 trap_Characteristic_String(bs->character, CHARACTERISTIC_WEAPONWEIGHTS, filename, sizeof(filename));
1215 errnum = trap_BotLoadWeaponWeights(bs->ws, filename);
1216 if (errnum != BLERR_NOERROR) {
1217 trap_BotFreeGoalState(bs->gs);
1218 trap_BotFreeWeaponState(bs->ws);
1219 return qfalse;
1220 }
1221 //allocate a chat state
1222 bs->cs = trap_BotAllocChatState();
1223 //load the chat file
1224 trap_Characteristic_String(bs->character, CHARACTERISTIC_CHAT_FILE, filename, sizeof(filename));
1225 trap_Characteristic_String(bs->character, CHARACTERISTIC_CHAT_NAME, name, sizeof(name));
1226 errnum = trap_BotLoadChatFile(bs->cs, filename, name);
1227 if (errnum != BLERR_NOERROR) {
1228 trap_BotFreeChatState(bs->cs);
1229 trap_BotFreeGoalState(bs->gs);
1230 trap_BotFreeWeaponState(bs->ws);
1231 return qfalse;
1232 }
1233 //get the gender characteristic
1234 trap_Characteristic_String(bs->character, CHARACTERISTIC_GENDER, gender, sizeof(gender));
1235 //set the chat gender
1236 if (*gender == 'f' || *gender == 'F') trap_BotSetChatGender(bs->cs, CHAT_GENDERFEMALE);
1237 else if (*gender == 'm' || *gender == 'M') trap_BotSetChatGender(bs->cs, CHAT_GENDERMALE);
1238 else trap_BotSetChatGender(bs->cs, CHAT_GENDERLESS);
1239
1240 bs->inuse = qtrue;
1241 bs->client = client;
1242 bs->entitynum = client;
1243 bs->setupcount = 4;
1244 bs->entergame_time = FloatTime();
1245 bs->ms = trap_BotAllocMoveState();
1246 bs->walker = trap_Characteristic_BFloat(bs->character, CHARACTERISTIC_WALKER, 0, 1);
1247 numbots++;
1248
1249 if (trap_Cvar_VariableIntegerValue("bot_testichat")) {
1250 trap_BotLibVarSet("bot_testichat", "1");
1251 BotChatTest(bs);
1252 }
1253 //NOTE: reschedule the bot thinking
1254 BotScheduleBotThink();
1255 //if interbreeding start with a mutation
1256 if (bot_interbreed) {
1257 trap_BotMutateGoalFuzzyLogic(bs->gs, 1);
1258 }
1259 // if we kept the bot client
1260 if (restart) {
1261 BotReadSessionData(bs);
1262 }
1263 //bot has been setup successfully
1264 return qtrue;
1265 }
1266
1267 /*
1268 ==============
1269 BotAIShutdownClient
1270 ==============
1271 */
1272 int BotAIShutdownClient(int client, qboolean restart) {
1273 bot_state_t *bs;
1274
1275 bs = botstates[client];
1276 if (!bs || !bs->inuse) {
1277 //BotAI_Print(PRT_ERROR, "BotAIShutdownClient: client %d already shutdown\n", client);
1278 return qfalse;
1279 }
1280
1281 if (restart) {
1282 BotWriteSessionData(bs);
1283 }
1284
1285 if (BotChat_ExitGame(bs)) {
1286 trap_BotEnterChat(bs->cs, bs->client, CHAT_ALL);
1287 }
1288
1289 trap_BotFreeMoveState(bs->ms);
1290 //free the goal state
1291 trap_BotFreeGoalState(bs->gs);
1292 //free the chat file
1293 trap_BotFreeChatState(bs->cs);
1294 //free the weapon weights
1295 trap_BotFreeWeaponState(bs->ws);
1296 //free the bot character
1297 trap_BotFreeCharacter(bs->character);
1298 //
1299 BotFreeWaypoints(bs->checkpoints);
1300 BotFreeWaypoints(bs->patrolpoints);
1301 //clear activate goal stack
1302 BotClearActivateGoalStack(bs);
1303 //clear the bot state
1304 memset(bs, 0, sizeof(bot_state_t));
1305 //set the inuse flag to qfalse
1306 bs->inuse = qfalse;
1307 //there's one bot less
1308 numbots--;
1309 //everything went ok
1310 return qtrue;
1311 }
1312
1313 /*
1314 ==============
1315 BotResetState
1316
1317 called when a bot enters the intermission or observer mode and
1318 when the level is changed
1319 ==============
1320 */
1321 void BotResetState(bot_state_t *bs) {
1322 int client, entitynum, inuse;
1323 int movestate, goalstate, chatstate, weaponstate;
1324 bot_settings_t settings;
1325 int character;
1326 playerState_t ps; //current player state
1327 float entergame_time;
1328
1329 //save some things that should not be reset here
1330 memcpy(&settings, &bs->settings, sizeof(bot_settings_t));
1331 memcpy(&ps, &bs->cur_ps, sizeof(playerState_t));
1332 inuse = bs->inuse;
1333 client = bs->client;
1334 entitynum = bs->entitynum;
1335 character = bs->character;
1336 movestate = bs->ms;
1337 goalstate = bs->gs;
1338 chatstate = bs->cs;
1339 weaponstate = bs->ws;
1340 entergame_time = bs->entergame_time;
1341 //free checkpoints and patrol points
1342 BotFreeWaypoints(bs->checkpoints);
1343 BotFreeWaypoints(bs->patrolpoints);
1344 //reset the whole state
1345 memset(bs, 0, sizeof(bot_state_t));
1346 //copy back some state stuff that should not be reset
1347 bs->ms = movestate;
1348 bs->gs = goalstate;
1349 bs->cs = chatstate;
1350 bs->ws = weaponstate;
1351 memcpy(&bs->cur_ps, &ps, sizeof(playerState_t));
1352 memcpy(&bs->settings, &settings, sizeof(bot_settings_t));
1353 bs->inuse = inuse;
1354 bs->client = client;
1355 bs->entitynum = entitynum;
1356 bs->character = character;
1357 bs->entergame_time = entergame_time;
1358 //reset several states
1359 if (bs->ms) trap_BotResetMoveState(bs->ms);
1360 if (bs->gs) trap_BotResetGoalState(bs->gs);
1361 if (bs->ws) trap_BotResetWeaponState(bs->ws);
1362 if (bs->gs) trap_BotResetAvoidGoals(bs->gs);
1363 if (bs->ms) trap_BotResetAvoidReach(bs->ms);
1364 }
1365
1366 /*
1367 ==============
1368 BotAILoadMap
1369 ==============
1370 */
1371 int BotAILoadMap( int restart ) {
1372 int i;
1373 vmCvar_t mapname;
1374
1375 if (!restart) {
1376 trap_Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM );
1377 trap_BotLibLoadMap( mapname.string );
1378 }
1379
1380 for (i = 0; i < MAX_CLIENTS; i++) {
1381 if (botstates[i] && botstates[i]->inuse) {
1382 BotResetState( botstates[i] );
1383 botstates[i]->setupcount = 4;
1384 }
1385 }
1386
1387 BotSetupDeathmatchAI();
1388
1389 return qtrue;
1390 }
1391
1392 #ifdef MISSIONPACK
1393 void ProximityMine_Trigger( gentity_t *trigger, gentity_t *other, trace_t *trace );
1394 #endif
1395
1396 /*
1397 ==================
1398 BotAIStartFrame
1399 ==================
1400 */
1401 int BotAIStartFrame(int time) {
1402 int i;
1403 gentity_t *ent;
1404 bot_entitystate_t state;
1405 int elapsed_time, thinktime;
1406 static int local_time;
1407 static int botlib_residual;
1408 static int lastbotthink_time;
1409
1410 G_CheckBotSpawn();
1411
1412 trap_Cvar_Update(&bot_rocketjump);
1413 trap_Cvar_Update(&bot_grapple);
1414 trap_Cvar_Update(&bot_fastchat);
1415 trap_Cvar_Update(&bot_nochat);
1416 trap_Cvar_Update(&bot_testrchat);
1417 trap_Cvar_Update(&bot_thinktime);
1418 trap_Cvar_Update(&bot_memorydump);
1419 trap_Cvar_Update(&bot_saveroutingcache);
1420 trap_Cvar_Update(&bot_pause);
1421 trap_Cvar_Update(&bot_report);
1422
1423 if (bot_report.integer) {
1424 // BotTeamplayReport();
1425 // trap_Cvar_Set("bot_report", "0");
1426 BotUpdateInfoConfigStrings();
1427 }
1428
1429 if (bot_pause.integer) {
1430 // execute bot user commands every frame
1431 for( i = 0; i < MAX_CLIENTS; i++ ) {
1432 if( !botstates[i] || !botstates[i]->inuse ) {
1433 continue;
1434 }
1435 if( g_entities[i].client->pers.connected != CON_CONNECTED ) {
1436 continue;
1437 }
1438 botstates[i]->lastucmd.forwardmove = 0;
1439 botstates[i]->lastucmd.rightmove = 0;
1440 botstates[i]->lastucmd.upmove = 0;
1441 botstates[i]->lastucmd.buttons = 0;
1442 botstates[i]->lastucmd.serverTime = time;
1443 trap_BotUserCommand(botstates[i]->client, &botstates[i]->lastucmd);
1444 }
1445 return qtrue;
1446 }
1447
1448 if (bot_memorydump.integer) {
1449 trap_BotLibVarSet("memorydump", "1");
1450 trap_Cvar_Set("bot_memorydump", "0");
1451 }
1452 if (bot_saveroutingcache.integer) {
1453 trap_BotLibVarSet("saveroutingcache", "1");
1454 trap_Cvar_Set("bot_saveroutingcache", "0");
1455 }
1456 //check if bot interbreeding is activated
1457 BotInterbreeding();
1458 //cap the bot think time
1459 if (bot_thinktime.integer > 200) {
1460 trap_Cvar_Set("bot_thinktime", "200");
1461 }
1462 //if the bot think time changed we should reschedule the bots
1463 if (bot_thinktime.integer != lastbotthink_time) {
1464 lastbotthink_time = bot_thinktime.integer;
1465 BotScheduleBotThink();
1466 }
1467
1468 elapsed_time = time - local_time;
1469 local_time = time;
1470
1471 botlib_residual += elapsed_time;
1472
1473 if (elapsed_time > bot_thinktime.integer) thinktime = elapsed_time;
1474 else thinktime = bot_thinktime.integer;
1475
1476 // update the bot library
1477 if ( botlib_residual >= thinktime ) {
1478 botlib_residual -= thinktime;
1479
1480 trap_BotLibStartFrame((float) time / 1000);
1481
1482 if (!trap_AAS_Initialized()) return qfalse;
1483
1484 //update entities in the botlib
1485 for (i = 0; i < MAX_GENTITIES; i++) {
1486 ent = &g_entities[i];
1487 if (!ent->inuse) {
1488 trap_BotLibUpdateEntity(i, NULL);
1489 continue;
1490 }
1491 if (!ent->r.linked) {
1492 trap_BotLibUpdateEntity(i, NULL);
1493 continue;
1494 }
1495 if (ent->r.svFlags & SVF_NOCLIENT) {
1496 trap_BotLibUpdateEntity(i, NULL);
1497 continue;
1498 }
1499 // do not update missiles
1500 if (ent->s.eType == ET_MISSILE && ent->s.weapon != WP_GRAPPLING_HOOK) {
1501 trap_BotLibUpdateEntity(i, NULL);
1502 continue;
1503 }
1504 // do not update event only entities
1505 if (ent->s.eType > ET_EVENTS) {
1506 trap_BotLibUpdateEntity(i, NULL);
1507 continue;
1508 }
1509 #ifdef MISSIONPACK
1510 // never link prox mine triggers
1511 if (ent->r.contents == CONTENTS_TRIGGER) {
1512 if (ent->touch == ProximityMine_Trigger) {
1513 trap_BotLibUpdateEntity(i, NULL);
1514 continue;
1515 }
1516 }
1517 #endif
1518 //
1519 memset(&state, 0, sizeof(bot_entitystate_t));
1520 //
1521 VectorCopy(ent->r.currentOrigin, state.origin);
1522 if (i < MAX_CLIENTS) {
1523 VectorCopy(ent->s.apos.trBase, state.angles);
1524 } else {
1525 VectorCopy(ent->r.currentAngles, state.angles);
1526 }
1527 VectorCopy(ent->s.origin2, state.old_origin);
1528 VectorCopy(ent->r.mins, state.mins);
1529 VectorCopy(ent->r.maxs, state.maxs);
1530 state.type = ent->s.eType;
1531 state.flags = ent->s.eFlags;
1532 if (ent->r.bmodel) state.solid = SOLID_BSP;
1533 else state.solid = SOLID_BBOX;
1534 state.groundent = ent->s.groundEntityNum;
1535 state.modelindex = ent->s.modelindex;
1536 state.modelindex2 = ent->s.modelindex2;
1537 state.frame = ent->s.frame;
1538 state.event = ent->s.event;
1539 state.eventParm = ent->s.eventParm;
1540 state.powerups = ent->s.powerups;
1541 state.legsAnim = ent->s.legsAnim;
1542 state.torsoAnim = ent->s.torsoAnim;
1543 state.weapon = ent->s.weapon;
1544 //
1545 trap_BotLibUpdateEntity(i, &state);
1546 }
1547
1548 BotAIRegularUpdate();
1549 }
1550
1551 floattime = trap_AAS_Time();
1552
1553 // execute scheduled bot AI
1554 for( i = 0; i < MAX_CLIENTS; i++ ) {
1555 if( !botstates[i] || !botstates[i]->inuse ) {
1556 continue;
1557 }
1558 //
1559 botstates[i]->botthink_residual += elapsed_time;
1560 //
1561 if ( botstates[i]->botthink_residual >= thinktime ) {
1562 botstates[i]->botthink_residual -= thinktime;
1563
1564 if (!trap_AAS_Initialized()) return qfalse;
1565
1566 if (g_entities[i].client->pers.connected == CON_CONNECTED) {
1567 BotAI(i, (float) thinktime / 1000);
1568 }
1569 }
1570 }
1571
1572
1573 // execute bot user commands every frame
1574 for( i = 0; i < MAX_CLIENTS; i++ ) {
1575 if( !botstates[i] || !botstates[i]->inuse ) {
1576 continue;
1577 }
1578 if( g_entities[i].client->pers.connected != CON_CONNECTED ) {
1579 continue;
1580 }
1581
1582 BotUpdateInput(botstates[i], time, elapsed_time);
1583 trap_BotUserCommand(botstates[i]->client, &botstates[i]->lastucmd);
1584 }
1585
1586 return qtrue;
1587 }
1588
1589 /*
1590 ==============
1591 BotInitLibrary
1592 ==============
1593 */
1594 int BotInitLibrary(void) {
1595 char buf[144];
1596
1597 //set the maxclients and maxentities library variables before calling BotSetupLibrary
1598 Com_sprintf(buf, sizeof(buf), "%d", level.maxclients);
1599 trap_BotLibVarSet("maxclients", buf);
1600 Com_sprintf(buf, sizeof(buf), "%d", MAX_GENTITIES);
1601 trap_BotLibVarSet("maxentities", buf);
1602 //bsp checksum
1603 trap_Cvar_VariableStringBuffer("sv_mapChecksum", buf, sizeof(buf));
1604 if (strlen(buf)) trap_BotLibVarSet("sv_mapChecksum", buf);
1605 //maximum number of aas links
1606 trap_Cvar_VariableStringBuffer("max_aaslinks", buf, sizeof(buf));
1607 if (strlen(buf)) trap_BotLibVarSet("max_aaslinks", buf);
1608 //maximum number of items in a level
1609 trap_Cvar_VariableStringBuffer("max_levelitems", buf, sizeof(buf));
1610 if (strlen(buf)) trap_BotLibVarSet("max_levelitems", buf);
1611 //game type
1612 trap_Cvar_VariableStringBuffer("g_gametype", buf, sizeof(buf));
1613 if (!strlen(buf)) strcpy(buf, "0");
1614 trap_BotLibVarSet("g_gametype", buf);
1615 //bot developer mode and log file
1616 trap_BotLibVarSet("bot_developer", bot_developer.string);
1617 trap_Cvar_VariableStringBuffer("logfile", buf, sizeof(buf));
1618 trap_BotLibVarSet("log", buf);
1619 //no chatting
1620 trap_Cvar_VariableStringBuffer("bot_nochat", buf, sizeof(buf));
1621 if (strlen(buf)) trap_BotLibVarSet("nochat", buf);
1622 //visualize jump pads
1623 trap_Cvar_VariableStringBuffer("bot_visualizejumppads", buf, sizeof(buf));
1624 if (strlen(buf)) trap_BotLibVarSet("bot_visualizejumppads", buf);
1625 //forced clustering calculations
1626 trap_Cvar_VariableStringBuffer("bot_forceclustering", buf, sizeof(buf));
1627 if (strlen(buf)) trap_BotLibVarSet("forceclustering", buf);
1628 //forced reachability calculations
1629 trap_Cvar_VariableStringBuffer("bot_forcereachability", buf, sizeof(buf));
1630 if (strlen(buf)) trap_BotLibVarSet("forcereachability", buf);
1631 //force writing of AAS to file
1632 trap_Cvar_VariableStringBuffer("bot_forcewrite", buf, sizeof(buf));
1633 if (strlen(buf)) trap_BotLibVarSet("forcewrite", buf);
1634 //no AAS optimization
1635 trap_Cvar_VariableStringBuffer("bot_aasoptimize", buf, sizeof(buf));
1636 if (strlen(buf)) trap_BotLibVarSet("aasoptimize", buf);
1637 //
1638 trap_Cvar_VariableStringBuffer("bot_saveroutingcache", buf, sizeof(buf));
1639 if (strlen(buf)) trap_BotLibVarSet("saveroutingcache", buf);
1640 //reload instead of cache bot character files
1641 trap_Cvar_VariableStringBuffer("bot_reloadcharacters", buf, sizeof(buf));
1642 if (!strlen(buf)) strcpy(buf, "0");
1643 trap_BotLibVarSet("bot_reloadcharacters", buf);
1644 //base directory
1645 trap_Cvar_VariableStringBuffer("fs_basepath", buf, sizeof(buf));
1646 if (strlen(buf)) trap_BotLibVarSet("basedir", buf);
1647 //game directory
1648 trap_Cvar_VariableStringBuffer("fs_game", buf, sizeof(buf));
1649 if (strlen(buf)) trap_BotLibVarSet("gamedir", buf);
1650 //
1651 #ifdef MISSIONPACK
1652 trap_BotLibDefine("MISSIONPACK");
1653 #endif
1654 //setup the bot library
1655 return trap_BotLibSetup();
1656 }
1657
1658 /*
1659 ==============
1660 BotAISetup
1661 ==============
1662 */
1663 int BotAISetup( int restart ) {
1664 int errnum;
1665
1666 trap_Cvar_Register(&bot_thinktime, "bot_thinktime", "100", CVAR_CHEAT);
1667 trap_Cvar_Register(&bot_memorydump, "bot_memorydump", "0", CVAR_CHEAT);
1668 trap_Cvar_Register(&bot_saveroutingcache, "bot_saveroutingcache", "0", CVAR_CHEAT);
1669 trap_Cvar_Register(&bot_pause, "bot_pause", "0", CVAR_CHEAT);
1670 trap_Cvar_Register(&bot_report, "bot_report", "0", CVAR_CHEAT);
1671 trap_Cvar_Register(&bot_testsolid, "bot_testsolid", "0", CVAR_CHEAT);
1672 trap_Cvar_Register(&bot_testclusters, "bot_testclusters", "0", CVAR_CHEAT);
1673 trap_Cvar_Register(&bot_developer, "bot_developer", "0", CVAR_CHEAT);
1674 trap_Cvar_Register(&bot_interbreedchar, "bot_interbreedchar", "", 0);
1675 trap_Cvar_Register(&bot_interbreedbots, "bot_interbreedbots", "10", 0);
1676 trap_Cvar_Register(&bot_interbreedcycle, "bot_interbreedcycle", "20", 0);
1677 trap_Cvar_Register(&bot_interbreedwrite, "bot_interbreedwrite", "", 0);
1678
1679 //if the game is restarted for a tournament
1680 if (restart) {
1681 return qtrue;
1682 }
1683
1684 //initialize the bot states
1685 memset( botstates, 0, sizeof(botstates) );
1686
1687 errnum = BotInitLibrary();
1688 if (errnum != BLERR_NOERROR) return qfalse;
1689 return qtrue;
1690 }
1691
1692 /*
1693 ==============
1694 BotAIShutdown
1695 ==============
1696 */
1697 int BotAIShutdown( int restart ) {
1698
1699 int i;
1700
1701 //if the game is restarted for a tournament
1702 if ( restart ) {
1703 //shutdown all the bots in the botlib
1704 for (i = 0; i < MAX_CLIENTS; i++) {
1705 if (botstates[i] && botstates[i]->inuse) {
1706 BotAIShutdownClient(botstates[i]->client, restart);
1707 }
1708 }
1709 //don't shutdown the bot library
1710 }
1711 else {
1712 trap_BotLibShutdown();
1713 }
1714 return qtrue;
1715 }
1716