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