Merge branch 'master' into Mario/turrets
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / monsters / sv_monsters.qc
1 #if defined(CSQC)
2 #elif defined(MENUQC)
3 #elif defined(SVQC)
4         #include "../../dpdefs/progsdefs.qh"
5     #include "../../dpdefs/dpextensions.qh"
6     #include "../../warpzonelib/common.qh"
7     #include "../constants.qh"
8     #include "../teams.qh"
9     #include "../util.qh"
10     #include "monsters.qh"
11     #include "sv_monsters.qh"
12     #include "../weapons/weapons.qh"
13     #include "../../server/autocvars.qh"
14     #include "../../server/defs.qh"
15     #include "../deathtypes.qh"
16     #include "../../server/mutators/mutators_include.qh"
17     #include "../../server/vehicles/vehicles_def.qh"
18     #include "../../server/campaign.qh"
19     #include "../../server/command/common.qh"
20     #include "../../server/command/cmd.qh"
21     #include "../../csqcmodellib/sv_model.qh"
22     #include "../../server/round_handler.qh"
23 #endif
24
25 // =========================
26 //      SVQC Monster Properties
27 // =========================
28
29
30 void monster_dropitem()
31 {
32         if(!self.candrop || !self.monster_loot)
33                 return;
34
35         vector org = self.origin + ((self.mins + self.maxs) * 0.5);
36         entity e = spawn(), oldself = self;
37
38         e.monster_loot = self.monster_loot;
39
40         other = e;
41         MUTATOR_CALLHOOK(MonsterDropItem);
42         e = other;
43
44         if(e && e.monster_loot)
45         {
46                 self = e;
47                 e.noalign = true;
48                 e.monster_loot();
49                 e.gravity = 1;
50                 e.movetype = MOVETYPE_TOSS;
51                 e.reset = SUB_Remove;
52                 setorigin(e, org);
53                 e.velocity = randomvec() * 175 + '0 0 325';
54                 e.item_spawnshieldtime = time + 0.7;
55                 e.classname = "droppedweapon"; // use weapon handling to remove it on touch
56                 SUB_SetFade(e, time + autocvar_g_monsters_drop_time, 1);
57                 self = oldself;
58         }
59 }
60
61 float Monster_SkillModifier()
62 {
63         float t = 0.5+self.monster_skill*((1.2-0.3)/10);
64
65         return t;
66 }
67
68 float monster_isvalidtarget (entity targ, entity ent)
69 {
70         if(!targ || !ent)
71                 return false; // someone doesn't exist
72
73         if(targ == ent)
74                 return false; // don't attack ourselves
75
76         //traceline(ent.origin, targ.origin, MOVE_NORMAL, ent);
77
78         //if(trace_ent != targ)
79                 //return false;
80
81         if(targ.vehicle_flags & VHF_ISVEHICLE)
82         if(!((get_monsterinfo(ent.monsterid)).spawnflags & MON_FLAG_RANGED))
83                 return false; // melee attacks are useless against vehicles
84
85         if(time < game_starttime)
86                 return false; // monsters do nothing before the match has started
87
88         if(targ.takedamage == DAMAGE_NO)
89                 return false; // enemy can't be damaged
90
91         if(targ.items & IT_INVISIBILITY)
92                 return false; // enemy is invisible
93
94         if(substring(targ.classname, 0, 10) == "onslaught_")
95                 return false; // don't attack onslaught targets
96
97         if(IS_SPEC(targ) || IS_OBSERVER(targ))
98                 return false; // enemy is a spectator
99
100         if(!(targ.vehicle_flags & VHF_ISVEHICLE))
101         if(targ.deadflag != DEAD_NO || ent.deadflag != DEAD_NO || targ.health <= 0 || ent.health <= 0)
102                 return false; // enemy/self is dead
103
104         if(ent.monster_owner == targ)
105                 return false; // don't attack our master
106
107         if(targ.monster_owner == ent)
108                 return false; // don't attack our pet
109
110         if(!(targ.vehicle_flags & VHF_ISVEHICLE))
111         if(targ.flags & FL_NOTARGET)
112                 return false; // enemy can't be targeted
113
114         if(!autocvar_g_monsters_typefrag)
115         if(targ.BUTTON_CHAT)
116                 return false; // no typefragging!
117
118         if(SAME_TEAM(targ, ent))
119                 return false; // enemy is on our team
120
121         if (targ.frozen)
122                 return false; // ignore frozen
123
124         if(autocvar_g_monsters_target_infront || (ent.spawnflags & MONSTERFLAG_INFRONT))
125         if(ent.enemy != targ)
126         {
127                 float dot;
128
129                 makevectors (ent.angles);
130                 dot = normalize (targ.origin - ent.origin) * v_forward;
131
132                 if(dot <= 0.3)
133                         return false;
134         }
135
136         return true;
137 }
138
139 entity FindTarget (entity ent)
140 {
141         if(MUTATOR_CALLHOOK(MonsterFindTarget)) { return ent.enemy; } // Handled by a mutator
142
143         entity head, closest_target = world;
144         head = findradius(ent.origin, ent.target_range);
145         //head = WarpZone_FindRadius(ent.origin, ent.target_range, true);
146
147         while(head) // find the closest acceptable target to pass to
148         {
149                 if(head.monster_attack)
150                 if(monster_isvalidtarget(head, ent))
151                 {
152                         // if it's a player, use the view origin as reference (stolen from RadiusDamage functions in g_damage.qc)
153                         vector head_center = CENTER_OR_VIEWOFS(head);
154                         //vector head_center = WarpZone_UnTransformOrigin(head, CENTER_OR_VIEWOFS(head));
155                         vector ent_center = CENTER_OR_VIEWOFS(ent);
156
157                         traceline(ent_center, head_center, MOVE_NORMAL, ent);
158
159                         if(trace_ent == head)
160                         if(closest_target)
161                         {
162                                 vector closest_target_center = CENTER_OR_VIEWOFS(closest_target);
163                                 //vector closest_target_center = WarpZone_UnTransformOrigin(closest_target, CENTER_OR_VIEWOFS(closest_target));
164                                 if(vlen(ent_center - head_center) < vlen(ent_center - closest_target_center))
165                                         { closest_target = head; }
166                         }
167                         else { closest_target = head; }
168                 }
169
170                 head = head.chain;
171         }
172
173         return closest_target;
174 }
175
176 void MonsterTouch ()
177 {
178         if(other == world)
179                 return;
180
181         if(self.enemy != other)
182         if(!(other.flags & FL_MONSTER))
183         if(monster_isvalidtarget(other, self))
184                 self.enemy = other;
185 }
186
187 string get_monster_model_datafilename(string m, float sk, string fil)
188 {
189         if(m)
190                 m = strcat(m, "_");
191         else
192                 m = "models/monsters/*_";
193         if(sk >= 0)
194                 m = strcat(m, ftos(sk));
195         else
196                 m = strcat(m, "*");
197         return strcat(m, ".", fil);
198 }
199
200 void PrecacheMonsterSounds(string f)
201 {
202         float fh;
203         string s;
204         fh = fopen(f, FILE_READ);
205         if(fh < 0)
206                 return;
207         while((s = fgets(fh)))
208         {
209                 if(tokenize_console(s) != 3)
210                 {
211                         dprint("Invalid sound info line: ", s, "\n");
212                         continue;
213                 }
214                 PrecacheGlobalSound(strcat(argv(1), " ", argv(2)));
215         }
216         fclose(fh);
217 }
218
219 void precache_monstersounds()
220 {
221         string m = (get_monsterinfo(self.monsterid)).model;
222         float globhandle, n, i;
223         string f;
224
225         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
226         if (globhandle < 0)
227                 return;
228         n = search_getsize(globhandle);
229         for (i = 0; i < n; ++i)
230         {
231                 //print(search_getfilename(globhandle, i), "\n");
232                 f = search_getfilename(globhandle, i);
233                 PrecacheMonsterSounds(f);
234         }
235         search_end(globhandle);
236 }
237
238 void ClearMonsterSounds()
239 {
240 #define _MSOUND(m) if(self.monstersound_##m) { strunzone(self.monstersound_##m); self.monstersound_##m = string_null; }
241         ALLMONSTERSOUNDS
242 #undef _MSOUND
243 }
244
245 .string GetMonsterSoundSampleField(string type)
246 {
247         GetMonsterSoundSampleField_notFound = 0;
248         switch(type)
249         {
250 #define _MSOUND(m) case #m: return monstersound_##m;
251                 ALLMONSTERSOUNDS
252 #undef _MSOUND
253         }
254         GetMonsterSoundSampleField_notFound = 1;
255         return string_null;
256 }
257
258 float LoadMonsterSounds(string f, float first)
259 {
260         float fh;
261         string s;
262         var .string field;
263         fh = fopen(f, FILE_READ);
264         if(fh < 0)
265         {
266                 dprint("Monster sound file not found: ", f, "\n");
267                 return 0;
268         }
269         while((s = fgets(fh)))
270         {
271                 if(tokenize_console(s) != 3)
272                         continue;
273                 field = GetMonsterSoundSampleField(argv(0));
274                 if(GetMonsterSoundSampleField_notFound)
275                         continue;
276                 if(self.field)
277                         strunzone(self.field);
278                 self.field = strzone(strcat(argv(1), " ", argv(2)));
279         }
280         fclose(fh);
281         return 1;
282 }
283
284 .int skin_for_monstersound;
285 void UpdateMonsterSounds()
286 {
287         entity mon = get_monsterinfo(self.monsterid);
288
289         if(self.skin == self.skin_for_monstersound)
290                 return;
291         self.skin_for_monstersound = self.skin;
292         ClearMonsterSounds();
293         //LoadMonsterSounds("sound/monsters/default.sounds", 1);
294         if(!autocvar_g_debug_defaultsounds)
295         if(!LoadMonsterSounds(get_monster_model_datafilename(mon.model, self.skin, "sounds"), 0))
296                 LoadMonsterSounds(get_monster_model_datafilename(mon.model, 0, "sounds"), 0);
297 }
298
299 void MonsterSound(.string samplefield, float sound_delay, float delaytoo, float chan)
300 {
301         if(!autocvar_g_monsters_sounds) { return; }
302
303         if(delaytoo)
304         if(time < self.msound_delay)
305                 return; // too early
306         GlobalSound(self.samplefield, chan, VOICETYPE_PLAYERSOUND);
307
308         self.msound_delay = time + sound_delay;
309 }
310
311 void monster_makevectors(entity e)
312 {
313         vector v;
314
315         v = e.origin + (e.mins + e.maxs) * 0.5;
316         self.v_angle = vectoangles(v - (self.origin + self.view_ofs));
317         self.v_angle_x = -self.v_angle.x;
318
319         makevectors(self.v_angle);
320 }
321
322 float monster_melee(entity targ, float damg, float anim, float er, float anim_finished, float deathtype, float dostop)
323 {
324         if (self.health <= 0)
325                 return false; // attacking while dead?!
326
327         if(dostop)
328         {
329                 self.velocity_x = 0;
330                 self.velocity_y = 0;
331                 self.state = MONSTER_STATE_ATTACK_MELEE;
332         }
333
334         self.frame = anim;
335
336         if(anim_finished != 0)
337                 self.attack_finished_single = time + anim_finished;
338
339         monster_makevectors(targ);
340
341         traceline(self.origin + self.view_ofs, self.origin + v_forward * er, 0, self);
342
343         if(trace_ent.takedamage)
344                 Damage(trace_ent, self, self, damg * Monster_SkillModifier(), deathtype, trace_ent.origin, normalize(trace_ent.origin - self.origin));
345
346         return true;
347 }
348
349 void Monster_CheckMinibossFlag ()
350 {
351         if(MUTATOR_CALLHOOK(MonsterCheckBossFlag))
352                 return;
353
354         float chance = random() * 100;
355
356         // g_monsters_miniboss_chance cvar or spawnflags 64 causes a monster to be a miniboss
357         if ((self.spawnflags & MONSTERFLAG_MINIBOSS) || (chance < autocvar_g_monsters_miniboss_chance))
358         {
359                 self.health += autocvar_g_monsters_miniboss_healthboost;
360                 self.effects |= EF_RED;
361                 if(!self.weapon)
362                         self.weapon = WEP_VORTEX;
363         }
364 }
365
366 float Monster_CanRespawn(entity ent)
367 {
368         other = ent;
369         if(ent.deadflag == DEAD_DEAD) // don't call when monster isn't dead
370         if(MUTATOR_CALLHOOK(MonsterRespawn))
371                 return true; // enabled by a mutator
372
373         if(ent.spawnflags & MONSTERFLAG_NORESPAWN)
374                 return false;
375
376         if(!autocvar_g_monsters_respawn)
377                 return false;
378
379         return true;
380 }
381
382 void monster_respawn()
383 {
384         // is this function really needed?
385         monster_initialize(self.monsterid);
386 }
387
388 void Monster_Fade ()
389 {
390         if(Monster_CanRespawn(self))
391         {
392                 self.spawnflags |= MONSTERFLAG_RESPAWNED;
393                 self.think = monster_respawn;
394                 self.nextthink = time + self.respawntime;
395                 self.monster_lifetime = 0;
396                 self.deadflag = DEAD_RESPAWNING;
397                 if(self.spawnflags & MONSTER_RESPAWN_DEATHPOINT)
398                 {
399                         self.pos1 = self.origin;
400                         self.pos2 = self.angles;
401                 }
402                 self.event_damage = func_null;
403                 self.takedamage = DAMAGE_NO;
404                 setorigin(self, self.pos1);
405                 self.angles = self.pos2;
406                 self.health = self.max_health;
407                 setmodel(self, "null");
408         }
409         else
410         {
411                 // number of monsters spawned with mobspawn command
412                 totalspawned -= 1;
413
414                 SUB_SetFade(self, time + 3, 1);
415         }
416 }
417
418 float Monster_CanJump (vector vel)
419 {
420         if(self.state)
421                 return false; // already attacking
422         if(!(self.flags & FL_ONGROUND))
423                 return false; // not on the ground
424         if(self.health <= 0)
425                 return false; // called when dead?
426         if(time < self.attack_finished_single)
427                 return false; // still attacking
428
429         vector old = self.velocity;
430
431         self.velocity = vel;
432         tracetoss(self, self);
433         self.velocity = old;
434         if (trace_ent != self.enemy)
435                 return false;
436
437         return true;
438 }
439
440 float monster_leap (float anm, void() touchfunc, vector vel, float anim_finished)
441 {
442         if(!Monster_CanJump(vel))
443                 return false;
444
445         self.frame = anm;
446         self.state = MONSTER_STATE_ATTACK_LEAP;
447         self.touch = touchfunc;
448         self.origin_z += 1;
449         self.velocity = vel;
450         self.flags &= ~FL_ONGROUND;
451
452         self.attack_finished_single = time + anim_finished;
453
454         return true;
455 }
456
457 void monster_checkattack(entity e, entity targ)
458 {
459         if(e == world)
460                 return;
461         if(targ == world)
462                 return;
463
464         if(!e.monster_attackfunc)
465                 return;
466
467         if(time < e.attack_finished_single)
468                 return;
469
470         if(vlen(targ.origin - e.origin) <= e.attack_range)
471         if(e.monster_attackfunc(MONSTER_ATTACK_MELEE))
472         {
473                 MonsterSound(monstersound_melee, 0, false, CH_VOICE);
474                 return;
475         }
476
477         if(vlen(targ.origin - e.origin) > e.attack_range)
478         if(e.monster_attackfunc(MONSTER_ATTACK_RANGED))
479         {
480                 MonsterSound(monstersound_ranged, 0, false, CH_VOICE);
481                 return;
482         }
483 }
484
485 void monster_use ()
486 {
487         if(!self.enemy)
488         if(self.health > 0)
489         if(monster_isvalidtarget(activator, self))
490                 self.enemy = activator;
491 }
492
493 .float last_trace;
494 .float last_enemycheck; // for checking enemy
495 vector monster_pickmovetarget(entity targ)
496 {
497         // enemy is always preferred target
498         if(self.enemy)
499         {
500                 vector targ_origin = ((self.enemy.absmin + self.enemy.absmax) * 0.5);
501                 targ_origin = WarpZone_RefSys_TransformOrigin(self.enemy, self, targ_origin); // origin of target as seen by the monster (us)
502                 WarpZone_TraceLine(self.origin, targ_origin, MOVE_NOMONSTERS, self);
503
504                 if((self.enemy == world)
505                         || (self.enemy.deadflag != DEAD_NO || self.enemy.health < 1)
506                         || (self.enemy.frozen)
507                         || (self.enemy.flags & FL_NOTARGET)
508                         || (self.enemy.alpha < 0.5)
509                         || (self.enemy.takedamage == DAMAGE_NO)
510                         || (vlen(self.origin - targ_origin) > self.target_range)
511                         || ((trace_fraction < 1) && (trace_ent != self.enemy)))
512                         //|| (time > self.ctf_droptime + autocvar_g_ctf_pass_timelimit)) // TODO: chase timelimit?
513                 {
514                         self.enemy = world;
515                         self.pass_distance = 0;
516                 }
517
518                 if(self.enemy)
519                 {
520                         /*WarpZone_TrailParticles(world, particleeffectnum("red_pass"), self.origin, targ_origin);
521                         print("Trace origin: ", vtos(targ_origin), "\n");
522                         print("Target origin: ", vtos(self.enemy.origin), "\n");
523                         print("My origin: ", vtos(self.origin), "\n"); */
524
525                         self.monster_movestate = MONSTER_MOVE_ENEMY;
526                         self.last_trace = time + 1.2;
527                         return targ_origin;
528                 }
529
530                 /*makevectors(self.angles);
531                 self.monster_movestate = MONSTER_MOVE_ENEMY;
532                 self.last_trace = time + 1.2;
533                 return self.enemy.origin; */
534         }
535
536         switch(self.monster_moveflags)
537         {
538                 case MONSTER_MOVE_OWNER:
539                 {
540                         self.monster_movestate = MONSTER_MOVE_OWNER;
541                         self.last_trace = time + 0.3;
542                         return (self.monster_owner) ? self.monster_owner.origin : self.origin;
543                 }
544                 case MONSTER_MOVE_SPAWNLOC:
545                 {
546                         self.monster_movestate = MONSTER_MOVE_SPAWNLOC;
547                         self.last_trace = time + 2;
548                         return self.pos1;
549                 }
550                 case MONSTER_MOVE_NOMOVE:
551                 {
552                         self.monster_movestate = MONSTER_MOVE_NOMOVE;
553                         self.last_trace = time + 2;
554                         return self.origin;
555                 }
556                 default:
557                 case MONSTER_MOVE_WANDER:
558                 {
559                         vector pos;
560                         self.monster_movestate = MONSTER_MOVE_WANDER;
561
562                         if(targ)
563                         {
564                                 self.last_trace = time + 0.5;
565                                 pos = targ.origin;
566                         }
567                         else
568                         {
569                                 self.last_trace = time + self.wander_delay;
570
571                                 self.angles_y = rint(random() * 500);
572                                 makevectors(self.angles);
573                                 pos = self.origin + v_forward * self.wander_distance;
574
575                                 if(((self.flags & FL_FLY) && (self.spawnflags & MONSTERFLAG_FLY_VERTICAL)) || (self.flags & FL_SWIM))
576                                 {
577                                         pos.z = random() * 200;
578                                         if(random() >= 0.5)
579                                                 pos.z *= -1;
580                                 }
581                         }
582
583                         return pos;
584                 }
585         }
586 }
587
588 void monster_CalculateVelocity(entity mon, vector to, vector from, float turnrate, float movespeed)
589 {
590         float current_distance = vlen((('1 0 0' * to.x) + ('0 1 0' * to.y)) - (('1 0 0' * from.x) + ('0 1 0' * from.y))); // for the sake of this check, exclude Z axis
591         float initial_height = 0; //min(50, (targ_distance * tanh(20)));
592         float current_height = (initial_height * min(1, (current_distance / self.pass_distance)));
593         //print("current_height = ", ftos(current_height), ", initial_height = ", ftos(initial_height), ".\n");
594
595         vector targpos;
596         if(current_height) // make sure we can actually do this arcing path
597         {
598                 targpos = (to + ('0 0 1' * current_height));
599                 WarpZone_TraceLine(mon.origin, targpos, MOVE_NOMONSTERS, mon);
600                 if(trace_fraction < 1)
601                 {
602                         //print("normal arc line failed, trying to find new pos...");
603                         WarpZone_TraceLine(to, targpos, MOVE_NOMONSTERS, mon);
604                         targpos = (trace_endpos + '0 0 -10');
605                         WarpZone_TraceLine(mon.origin, targpos, MOVE_NOMONSTERS, mon);
606                         if(trace_fraction < 1) { targpos = to; /* print(" ^1FAILURE^7, reverting to original direction.\n"); */ }
607                         /*else { print(" ^3SUCCESS^7, using new arc line.\n"); } */
608                 }
609         }
610         else { targpos = to; }
611
612         //mon.angles = normalize(('0 1 0' * to_y) - ('0 1 0' * from_y));
613
614         vector desired_direction = normalize(targpos - from);
615         if(turnrate) { mon.velocity = (normalize(normalize(mon.velocity) + (desired_direction * 50)) * movespeed); }
616         else { mon.velocity = (desired_direction * movespeed); }
617
618         //mon.steerto = steerlib_attract2(targpos, 0.5, 500, 0.95);
619         //mon.angles = vectoangles(mon.velocity);
620 }
621
622 void monster_move(float runspeed, float walkspeed, float stopspeed, float manim_run, float manim_walk, float manim_idle)
623 {
624         //fixedmakevectors(self.angles);
625
626         if(self.target2)
627                 self.goalentity = find(world, targetname, self.target2);
628
629         entity targ;
630
631         if(self.frozen == 2)
632         {
633                 self.revive_progress = bound(0, self.revive_progress + self.ticrate * self.revive_speed, 1);
634                 self.health = max(1, self.revive_progress * self.max_health);
635                 self.iceblock.alpha = bound(0.2, 1 - self.revive_progress, 1);
636
637                 WaypointSprite_UpdateHealth(self.sprite, self.health);
638
639                 movelib_beak_simple(stopspeed);
640                 self.frame = manim_idle;
641
642                 self.enemy = world;
643                 self.nextthink = time + self.ticrate;
644
645                 if(self.revive_progress >= 1)
646                         Unfreeze(self);
647
648                 return;
649         }
650         else if(self.frozen == 3)
651         {
652                 self.revive_progress = bound(0, self.revive_progress - self.ticrate * self.revive_speed, 1);
653                 self.health = max(0, autocvar_g_nades_ice_health + (self.max_health-autocvar_g_nades_ice_health) * self.revive_progress );
654
655                 WaypointSprite_UpdateHealth(self.sprite, self.health);
656
657                 movelib_beak_simple(stopspeed);
658                 self.frame = manim_idle;
659
660                 self.enemy = world;
661                 self.nextthink = time + self.ticrate;
662
663                 if(self.health < 1)
664                 {
665                         Unfreeze(self);
666                         self.health = 0;
667                         self.event_damage(self, self.frozen_by, 1, DEATH_NADE_ICE_FREEZE, self.origin, '0 0 0');
668                 }
669
670                 else if ( self.revive_progress <= 0 )
671                         Unfreeze(self);
672
673                 return;
674         }
675
676         if(self.flags & FL_SWIM)
677         {
678                 if(self.waterlevel < WATERLEVEL_WETFEET)
679                 {
680                         if(time >= self.last_trace)
681                         {
682                                 self.fish_wasdrowning = true;
683                                 self.last_trace = time + 0.4;
684
685                                 Damage (self, world, world, 2, DEATH_DROWN, self.origin, '0 0 0');
686                                 self.angles = '90 90 0';
687                                 if(random() < 0.5)
688                                 {
689                                         self.velocity_y += random() * 50;
690                                         self.velocity_x -= random() * 50;
691                                 }
692                                 else
693                                 {
694                                         self.velocity_y -= random() * 50;
695                                         self.velocity_x += random() * 50;
696                                 }
697                                 self.velocity_z += random() * 150;
698                         }
699
700
701                         self.movetype = MOVETYPE_BOUNCE;
702                         //self.velocity_z = -200;
703
704                         return;
705                 }
706                 else if(self.fish_wasdrowning)
707                 {
708                         self.fish_wasdrowning = false;
709                         self.angles_x = 0;
710                         self.movetype = MOVETYPE_WALK;
711                 }
712         }
713
714         targ = self.goalentity;
715
716         monster_target = targ;
717         monster_speed_run = runspeed;
718         monster_speed_walk = walkspeed;
719
720         if(MUTATOR_CALLHOOK(MonsterMove) || gameover || self.draggedby != world || (round_handler_IsActive() && !round_handler_IsRoundStarted()) || time < game_starttime || (autocvar_g_campaign && !campaign_bots_may_start) || time < self.spawn_time)
721         {
722                 runspeed = walkspeed = 0;
723                 if(time >= self.spawn_time)
724                         self.frame = manim_idle;
725                 movelib_beak_simple(stopspeed);
726                 return;
727         }
728
729         targ = monster_target;
730         runspeed = bound(0, monster_speed_run * Monster_SkillModifier(), runspeed * 2); // limit maxspeed to prevent craziness
731         walkspeed = bound(0, monster_speed_walk * Monster_SkillModifier(), walkspeed * 2); // limit maxspeed to prevent craziness
732
733         if(time < self.spider_slowness)
734         {
735                 runspeed *= 0.5;
736                 walkspeed *= 0.5;
737         }
738
739         if(teamplay)
740         if(autocvar_g_monsters_teams)
741         if(DIFF_TEAM(self.monster_owner, self))
742                 self.monster_owner = world;
743
744         if(time >= self.last_enemycheck)
745         {
746                 if(!self.enemy)
747                 {
748                         self.enemy = FindTarget(self);
749                         if(self.enemy)
750                         {
751                                 WarpZone_RefSys_Copy(self.enemy, self);
752                                 WarpZone_RefSys_AddInverse(self.enemy, self); // wz1^-1 ... wzn^-1 receiver
753                                 self.moveto = WarpZone_RefSys_TransformOrigin(self.enemy, self, (0.5 * (self.enemy.absmin + self.enemy.absmax)));
754
755                                 self.pass_distance = vlen((('1 0 0' * self.enemy.origin.x) + ('0 1 0' * self.enemy.origin.y)) - (('1 0 0' *  self.origin.x) + ('0 1 0' *  self.origin.y)));
756                                 MonsterSound(monstersound_sight, 0, false, CH_VOICE);
757                         }
758                 }
759
760                 self.last_enemycheck = time + 1; // check for enemies every second
761         }
762
763         if(self.state == MONSTER_STATE_ATTACK_MELEE && time >= self.attack_finished_single)
764                 self.state = 0;
765
766         if(self.state != MONSTER_STATE_ATTACK_MELEE) // don't move if set
767         if(time >= self.last_trace || self.enemy) // update enemy instantly
768                 self.moveto = monster_pickmovetarget(targ);
769
770         if(!self.enemy)
771                 MonsterSound(monstersound_idle, 7, true, CH_VOICE);
772
773         if(self.state == MONSTER_STATE_ATTACK_LEAP && (self.flags & FL_ONGROUND))
774         {
775                 self.state = 0;
776                 self.touch = MonsterTouch;
777         }
778
779         if(self.state == MONSTER_STATE_ATTACK_MELEE)
780                 self.moveto = self.origin;
781
782         if(self.enemy && self.enemy.vehicle)
783                 runspeed = 0;
784
785         if(!(((self.flags & FL_FLY) && (self.spawnflags & MONSTERFLAG_FLY_VERTICAL)) || (self.flags & FL_SWIM)))
786                 //v_forward = normalize(self.moveto - self.origin);
787         //else
788                 self.moveto_z = self.origin.z;
789
790         if(vlen(self.origin - self.moveto) > 64)
791         {
792                 if((self.flags & FL_ONGROUND) || ((self.flags & FL_FLY) || (self.flags & FL_SWIM)))
793                         monster_CalculateVelocity(self, self.moveto, self.origin, true, ((self.enemy) ? runspeed : walkspeed));
794
795                 /*&if(self.flags & FL_FLY || self.flags & FL_SWIM)
796                         movelib_move_simple(v_forward, ((self.enemy) ? runspeed : walkspeed), 0.6);
797                 else
798                         movelib_move_simple_gravity(v_forward, ((self.enemy) ? runspeed : walkspeed), 0.6); */
799
800                 if(time > self.pain_finished)
801                 if(time > self.attack_finished_single)
802                 if(vlen(self.velocity) > 10)
803                         self.frame = ((self.enemy) ? manim_run : manim_walk);
804                 else
805                         self.frame = manim_idle;
806         }
807         else
808         {
809                 entity e = find(world, targetname, self.target2);
810                 if(e.target2)
811                         self.target2 = e.target2;
812                 else if(e.target)
813                         self.target2 = e.target;
814
815                 movelib_beak_simple(stopspeed);
816                 if(time > self.attack_finished_single)
817                 if(time > self.pain_finished)
818                 if (vlen(self.velocity) <= 30)
819                         self.frame = manim_idle;
820         }
821
822         self.steerto = steerlib_attract2(self.moveto, 0.5, 500, 0.95);
823
824         vector real_angle = vectoangles(self.steerto) - self.angles;
825         float turny = 25;
826         if(self.state == MONSTER_STATE_ATTACK_MELEE)
827                 turny = 0;
828         if(turny)
829         {
830                 turny = bound(turny * -1, shortangle_f(real_angle.y, self.angles.y), turny);
831                 self.angles_y += turny;
832         }
833
834         monster_checkattack(self, self.enemy);
835 }
836
837 void monster_remove(entity mon)
838 {
839         if(!mon)
840                 return; // nothing to remove
841
842         pointparticles(particleeffectnum("item_pickup"), mon.origin, '0 0 0', 1);
843
844         if(mon.weaponentity)
845                 remove(mon.weaponentity);
846
847         if(mon.iceblock)
848                 remove(mon.iceblock);
849
850         WaypointSprite_Kill(mon.sprite);
851
852         remove(mon);
853 }
854
855 void monster_dead_think()
856 {
857         self.nextthink = time + self.ticrate;
858
859         CSQCMODEL_AUTOUPDATE();
860
861         if(self.monster_lifetime != 0)
862         if(time >= self.monster_lifetime)
863         {
864                 Monster_Fade();
865                 return;
866         }
867 }
868
869 void monsters_setstatus()
870 {
871         self.stat_monsters_total = monsters_total;
872         self.stat_monsters_killed = monsters_killed;
873 }
874
875 void Monster_Appear()
876 {
877         self.enemy = activator;
878         self.spawnflags &= ~MONSTERFLAG_APPEAR; // otherwise, we get an endless loop
879         monster_initialize(self.monsterid);
880 }
881
882 float Monster_CheckAppearFlags(entity ent, float monster_id)
883 {
884         if(!(ent.spawnflags & MONSTERFLAG_APPEAR))
885                 return false;
886
887         ent.think = func_null;
888         ent.monsterid = monster_id; // set so this monster is properly registered (otherwise, normal initialization is used)
889         ent.nextthink = 0;
890         ent.use = Monster_Appear;
891         ent.flags = FL_MONSTER; // set so this monster can get butchered
892
893         return true;
894 }
895
896 void monsters_reset()
897 {
898         setorigin(self, self.pos1);
899         self.angles = self.pos2;
900
901         Unfreeze(self); // remove any icy remains
902
903         self.health = self.max_health;
904         self.velocity = '0 0 0';
905         self.enemy = world;
906         self.goalentity = world;
907         self.attack_finished_single = 0;
908         self.moveto = self.origin;
909 }
910
911 void monsters_corpse_damage (entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force)
912 {
913         self.health -= damage;
914
915         Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, self, attacker);
916
917         if(self.health <= -100) // 100 health until gone?
918         {
919                 Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, self, attacker);
920
921                 // number of monsters spawned with mobspawn command
922                 totalspawned -= 1;
923
924                 self.think = SUB_Remove;
925                 self.nextthink = time + 0.1;
926                 self.event_damage = func_null;
927         }
928 }
929
930 void monster_die(entity attacker, float gibbed)
931 {
932         self.think = monster_dead_think;
933         self.nextthink = time;
934         self.monster_lifetime = time + 5;
935
936         if(self.frozen)
937         {
938                 Unfreeze(self); // remove any icy remains
939                 self.health = 0; // reset by Unfreeze
940         }
941
942         monster_dropitem();
943
944         MonsterSound(monstersound_death, 0, false, CH_VOICE);
945
946         if(!(self.spawnflags & MONSTERFLAG_SPAWNED) && !(self.spawnflags & MONSTERFLAG_RESPAWNED))
947                 monsters_killed += 1;
948
949         if(IS_PLAYER(attacker))
950         if(autocvar_g_monsters_score_spawned || !((self.spawnflags & MONSTERFLAG_SPAWNED) || (self.spawnflags & MONSTERFLAG_RESPAWNED)))
951                 PlayerScore_Add(attacker, SP_SCORE, +autocvar_g_monsters_score_kill);
952
953         if(gibbed)
954         {
955                 // number of monsters spawned with mobspawn command
956                 totalspawned -= 1;
957         }
958
959         if(self.candrop && self.weapon)
960                 W_ThrowNewWeapon(self, self.weapon, 0, self.origin, randomvec() * 150 + '0 0 325');
961
962         self.event_damage       = ((gibbed) ? func_null : monsters_corpse_damage);
963         self.solid                      = SOLID_CORPSE;
964         self.takedamage         = DAMAGE_AIM;
965         self.deadflag           = DEAD_DEAD;
966         self.enemy                      = world;
967         self.movetype           = MOVETYPE_TOSS;
968         self.moveto                     = self.origin;
969         self.touch                      = MonsterTouch; // reset incase monster was pouncing
970         self.reset                      = func_null;
971         self.state                      = 0;
972         self.attack_finished_single = 0;
973
974         if(!((self.flags & FL_FLY) || (self.flags & FL_SWIM)))
975                 self.velocity = '0 0 0';
976
977         MON_ACTION(self.monsterid, MR_DEATH);
978 }
979
980 void monsters_damage (entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force)
981 {
982         if(self.frozen && deathtype != DEATH_KILL && deathtype != DEATH_NADE_ICE_FREEZE)
983                 return;
984
985         if((self.spawnflags & MONSTERFLAG_INVINCIBLE) && deathtype != DEATH_KILL)
986                 return;
987
988         if(time < self.pain_finished && deathtype != DEATH_KILL)
989                 return;
990
991         if(time < self.spawnshieldtime && deathtype != DEATH_KILL)
992                 return;
993
994         if(deathtype == DEATH_FALL && self.draggedby != world)
995                 return;
996
997         vector v;
998         float take, save;
999
1000         v = healtharmor_applydamage(self.armorvalue, self.m_armor_blockpercent, deathtype, damage);
1001         take = v.x;
1002         save = v.y;
1003
1004         self.health -= take;
1005
1006         WaypointSprite_UpdateHealth(self.sprite, self.health);
1007
1008         self.dmg_time = time;
1009
1010         if(sound_allowed(MSG_BROADCAST, attacker) && deathtype != DEATH_DROWN)
1011                 spamsound (self, CH_PAIN, "misc/bodyimpact1.wav", VOL_BASE, ATTEN_NORM);  // FIXME: PLACEHOLDER
1012
1013         self.velocity += force * self.damageforcescale;
1014
1015         if(deathtype != DEATH_DROWN)
1016         {
1017                 Violence_GibSplash_At(hitloc, force, 2, bound(0, take, 200) / 16, self, attacker);
1018                 if (take > 50)
1019                         Violence_GibSplash_At(hitloc, force * -0.1, 3, 1, self, attacker);
1020                 if (take > 100)
1021                         Violence_GibSplash_At(hitloc, force * -0.2, 3, 1, self, attacker);
1022         }
1023
1024         if(self.health <= 0)
1025         {
1026                 if(deathtype == DEATH_KILL)
1027                         self.candrop = false; // killed by mobkill command
1028
1029                 // TODO: fix this?
1030                 activator = attacker;
1031                 other = self.enemy;
1032                 SUB_UseTargets();
1033                 self.target2 = self.oldtarget2; // reset to original target on death, incase we respawn
1034
1035                 monster_die(attacker, (self.health <= -100 || deathtype == DEATH_KILL));
1036
1037                 WaypointSprite_Kill(self.sprite);
1038
1039                 frag_attacker = attacker;
1040                 frag_target = self;
1041                 MUTATOR_CALLHOOK(MonsterDies);
1042
1043                 if(self.health <= -100 || deathtype == DEATH_KILL) // check if we're already gibbed
1044                 {
1045                         Violence_GibSplash(self, 1, 0.5, attacker);
1046
1047                         self.think = SUB_Remove;
1048                         self.nextthink = time + 0.1;
1049                 }
1050         }
1051 }
1052
1053 void monster_setupcolors(entity mon)
1054 {
1055         if(IS_PLAYER(mon.monster_owner))
1056                 mon.colormap = mon.monster_owner.colormap;
1057         else if(teamplay && mon.team)
1058                 mon.colormap = 1024 + (mon.team - 1) * 17;
1059         else
1060         {
1061                 if(mon.monster_skill <= MONSTER_SKILL_EASY)
1062                         mon.colormap = 1029;
1063                 else if(mon.monster_skill <= MONSTER_SKILL_MEDIUM)
1064                         mon.colormap = 1027;
1065                 else if(mon.monster_skill <= MONSTER_SKILL_HARD)
1066                         mon.colormap = 1038;
1067                 else if(mon.monster_skill <= MONSTER_SKILL_INSANE)
1068                         mon.colormap = 1028;
1069                 else if(mon.monster_skill <= MONSTER_SKILL_NIGHTMARE)
1070                         mon.colormap = 1032;
1071                 else
1072                         mon.colormap = 1024;
1073         }
1074 }
1075
1076 void monster_changeteam(entity ent, float newteam)
1077 {
1078         if(!teamplay) { return; }
1079
1080         ent.team = newteam;
1081         ent.monster_attack = true; // new team, activate attacking
1082         monster_setupcolors(ent);
1083
1084         if(ent.sprite)
1085         {
1086                 WaypointSprite_UpdateTeamRadar(ent.sprite, RADARICON_DANGER, ((newteam) ? Team_ColorRGB(newteam) : '1 0 0'));
1087
1088                 ent.sprite.team = newteam;
1089                 ent.sprite.SendFlags |= 1;
1090         }
1091 }
1092
1093 void monster_think()
1094 {
1095         self.think = monster_think;
1096         self.nextthink = self.ticrate;
1097
1098         if(self.monster_lifetime)
1099         if(time >= self.monster_lifetime)
1100         {
1101                 Damage(self, self, self, self.health + self.max_health, DEATH_KILL, self.origin, self.origin);
1102                 return;
1103         }
1104
1105         MON_ACTION(self.monsterid, MR_THINK);
1106
1107         CSQCMODEL_AUTOUPDATE();
1108 }
1109
1110 float monster_spawn()
1111 {
1112         MON_ACTION(self.monsterid, MR_SETUP);
1113
1114         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1115         {
1116                 Monster_CheckMinibossFlag();
1117                 self.health *= Monster_SkillModifier();
1118         }
1119
1120         self.max_health = self.health;
1121         self.pain_finished = self.nextthink;
1122
1123         if(IS_PLAYER(self.monster_owner))
1124                 self.effects |= EF_DIMLIGHT;
1125
1126         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1127         if(!self.skin)
1128                 self.skin = rint(random() * 4);
1129
1130         if(!self.attack_range)
1131                 self.attack_range = autocvar_g_monsters_attack_range;
1132
1133         if(!self.wander_delay) { self.wander_delay = 2; }
1134         if(!self.wander_distance) { self.wander_distance = 600; }
1135
1136         precache_monstersounds();
1137         UpdateMonsterSounds();
1138
1139         if(teamplay)
1140                 self.monster_attack = true; // we can have monster enemies in team games
1141
1142         MonsterSound(monstersound_spawn, 0, false, CH_VOICE);
1143
1144         WaypointSprite_Spawn(M_NAME(self.monsterid), 0, 1024, self, '0 0 1' * (self.maxs.z + 15), world, self.team, self, sprite, true, RADARICON_DANGER, ((self.team) ? Team_ColorRGB(self.team) : '1 0 0'));
1145         if(!(self.spawnflags & MONSTERFLAG_INVINCIBLE))
1146         {
1147                 WaypointSprite_UpdateMaxHealth(self.sprite, self.max_health);
1148                 WaypointSprite_UpdateHealth(self.sprite, self.health);
1149         }
1150
1151         self.think = monster_think;
1152         self.nextthink = time + self.ticrate;
1153
1154         if(MUTATOR_CALLHOOK(MonsterSpawn))
1155                 return false;
1156
1157         return true;
1158 }
1159
1160 float monster_initialize(float mon_id)
1161 {
1162         if(!autocvar_g_monsters) { return false; }
1163         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED)) { MON_ACTION(mon_id, MR_PRECACHE); }
1164         if(Monster_CheckAppearFlags(self, mon_id)) { return true; } // return true so the monster isn't removed
1165
1166         entity mon = get_monsterinfo(mon_id);
1167
1168         if(!self.monster_skill)
1169                 self.monster_skill = cvar("g_monsters_skill");
1170
1171         // support for quake style removing monsters based on skill
1172         if(self.monster_skill == MONSTER_SKILL_EASY) if(self.spawnflags & MONSTERSKILL_NOTEASY) { return false; }
1173         if(self.monster_skill == MONSTER_SKILL_MEDIUM) if(self.spawnflags & MONSTERSKILL_NOTMEDIUM) { return false; }
1174         if(self.monster_skill == MONSTER_SKILL_HARD) if(self.spawnflags & MONSTERSKILL_NOTHARD) { return false; }
1175
1176         if(self.team && !teamplay)
1177                 self.team = 0;
1178
1179         if(!(self.spawnflags & MONSTERFLAG_SPAWNED)) // naturally spawned monster
1180         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED)) // don't count re-spawning monsters either
1181                 monsters_total += 1;
1182
1183         setmodel(self, mon.model);
1184         //setsize(self, mon.mins, mon.maxs);
1185         self.flags                              = FL_MONSTER;
1186         self.takedamage                 = DAMAGE_AIM;
1187         self.bot_attack                 = true;
1188         self.iscreature                 = true;
1189         self.teleportable               = true;
1190         self.damagedbycontents  = true;
1191         self.monsterid                  = mon_id;
1192         self.damageforcescale   = 0;
1193         self.event_damage               = monsters_damage;
1194         self.touch                              = MonsterTouch;
1195         self.use                                = monster_use;
1196         self.solid                              = SOLID_BBOX;
1197         self.movetype                   = MOVETYPE_WALK;
1198         self.spawnshieldtime    = time + autocvar_g_monsters_spawnshieldtime;
1199         self.enemy                              = world;
1200         self.velocity                   = '0 0 0';
1201         self.moveto                             = self.origin;
1202         self.pos1                               = self.origin;
1203         self.pos2                               = self.angles;
1204         self.reset                              = monsters_reset;
1205         self.netname                    = mon.netname;
1206         self.monster_name               = M_NAME(mon_id);
1207         self.candrop                    = true;
1208         self.view_ofs                   = '0 0 1' * (self.maxs.z * 0.5);
1209         self.oldtarget2                 = self.target2;
1210         self.pass_distance              = 0;
1211         self.deadflag                   = DEAD_NO;
1212         self.noalign                    = ((mon.spawnflags & MONSTER_TYPE_FLY) || (mon.spawnflags & MONSTER_TYPE_SWIM));
1213         self.spawn_time                 = time;
1214         self.spider_slowness    = 0;
1215         self.gravity                    = 1;
1216         self.dphitcontentsmask  = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_BOTCLIP | DPCONTENTS_MONSTERCLIP;
1217
1218         if(!self.scale)
1219                 self.scale = 1;
1220
1221         if(autocvar_g_monsters_edit)
1222                 self.grab = 1; // owner may carry their monster
1223
1224         if(autocvar_g_fullbrightplayers)
1225                 self.effects |= EF_FULLBRIGHT;
1226
1227         if(autocvar_g_nodepthtestplayers)
1228                 self.effects |= EF_NODEPTHTEST;
1229
1230         if(mon.spawnflags & MONSTER_TYPE_SWIM)
1231                 self.flags |= FL_SWIM;
1232
1233         if(mon.spawnflags & MONSTER_TYPE_FLY)
1234         {
1235                 self.flags |= FL_FLY;
1236                 self.movetype = MOVETYPE_FLY;
1237         }
1238
1239         if(mon.spawnflags & MONSTER_SIZE_BROKEN)
1240         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1241                 self.scale *= 1.3;
1242
1243         setsize(self, mon.mins * self.scale, mon.maxs * self.scale);
1244
1245         if(!self.ticrate)
1246                 self.ticrate = autocvar_g_monsters_think_delay;
1247
1248         self.ticrate = bound(sys_frametime, self.ticrate, 60);
1249
1250         if(!self.m_armor_blockpercent)
1251                 self.m_armor_blockpercent = 0.5;
1252
1253         if(!self.target_range)
1254                 self.target_range = autocvar_g_monsters_target_range;
1255
1256         if(!self.respawntime)
1257                 self.respawntime = autocvar_g_monsters_respawn_delay;
1258
1259         if(!self.monster_moveflags)
1260                 self.monster_moveflags = MONSTER_MOVE_WANDER;
1261
1262         if(!self.noalign)
1263         {
1264                 setorigin(self, self.origin + '0 0 20');
1265                 tracebox(self.origin + '0 0 64', self.mins, self.maxs, self.origin - '0 0 10000', MOVE_WORLDONLY, self);
1266                 setorigin(self, trace_endpos);
1267         }
1268
1269         if(!monster_spawn())
1270                 return false;
1271
1272         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1273                 monster_setupcolors(self);
1274
1275         CSQCMODEL_AUTOINIT();
1276
1277         return true;
1278 }