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