]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/monsters/sv_monsters.qc
Merge branch 'master' into Mario/weapons_new
[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.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.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.frozen == 2)
609         {
610                 self.revive_progress = bound(0, self.revive_progress + self.ticrate * self.revive_speed, 1);
611                 self.health = max(1, self.revive_progress * self.max_health);
612                 self.iceblock.alpha = bound(0.2, 1 - self.revive_progress, 1);
613
614                 WaypointSprite_UpdateHealth(self.sprite, self.health);
615
616                 movelib_beak_simple(stopspeed);
617                 self.frame = manim_idle;
618
619                 self.enemy = world;
620                 self.nextthink = time + self.ticrate;
621
622                 if(self.revive_progress >= 1)
623                         Unfreeze(self);
624
625                 return;
626         }
627         else if(self.frozen == 3)
628         {
629                 self.revive_progress = bound(0, self.revive_progress - self.ticrate * self.revive_speed, 1);
630                 self.health = max(0, autocvar_g_nades_ice_health + (self.max_health-autocvar_g_nades_ice_health) * self.revive_progress );
631
632                 WaypointSprite_UpdateHealth(self.sprite, self.health);
633
634                 movelib_beak_simple(stopspeed);
635                 self.frame = manim_idle;
636
637                 self.enemy = world;
638                 self.nextthink = time + self.ticrate;
639
640                 if(self.health < 1)
641                 {
642                         Unfreeze(self);
643                         self.health = 0;
644                         self.event_damage(self, self.frozen_by, 1, DEATH_NADE_ICE_FREEZE, self.origin, '0 0 0');
645                 }
646
647                 else if ( self.revive_progress <= 0 )
648                         Unfreeze(self);
649
650                 return;
651         }
652
653         if(self.flags & FL_SWIM)
654         {
655                 if(self.waterlevel < WATERLEVEL_WETFEET)
656                 {
657                         if(time >= self.last_trace)
658                         {
659                                 self.fish_wasdrowning = TRUE;
660                                 self.last_trace = time + 0.4;
661
662                                 Damage (self, world, world, 2, DEATH_DROWN, self.origin, '0 0 0');
663                                 self.angles = '90 90 0';
664                                 if(random() < 0.5)
665                                 {
666                                         self.velocity_y += random() * 50;
667                                         self.velocity_x -= random() * 50;
668                                 }
669                                 else
670                                 {
671                                         self.velocity_y -= random() * 50;
672                                         self.velocity_x += random() * 50;
673                                 }
674                                 self.velocity_z += random() * 150;
675                         }
676
677
678                         self.movetype = MOVETYPE_BOUNCE;
679                         //self.velocity_z = -200;
680
681                         return;
682                 }
683                 else if(self.fish_wasdrowning)
684                 {
685                         self.fish_wasdrowning = FALSE;
686                         self.angles_x = 0;
687                         self.movetype = MOVETYPE_WALK;
688                 }
689         }
690
691         targ = self.goalentity;
692
693         monster_target = targ;
694         monster_speed_run = runspeed;
695         monster_speed_walk = walkspeed;
696
697         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)
698         {
699                 runspeed = walkspeed = 0;
700                 if(time >= self.spawn_time)
701                         self.frame = manim_idle;
702                 movelib_beak_simple(stopspeed);
703                 return;
704         }
705
706         targ = monster_target;
707         runspeed = bound(0, monster_speed_run * Monster_SkillModifier(), runspeed * 2); // limit maxspeed to prevent craziness
708         walkspeed = bound(0, monster_speed_walk * Monster_SkillModifier(), walkspeed * 2); // limit maxspeed to prevent craziness
709
710         if(time < self.spider_slowness)
711         {
712                 runspeed *= 0.5;
713                 walkspeed *= 0.5;
714         }
715
716         if(teamplay)
717         if(autocvar_g_monsters_teams)
718         if(DIFF_TEAM(self.monster_owner, self))
719                 self.monster_owner = world;
720
721         if(time >= self.last_enemycheck)
722         {
723                 if(!self.enemy)
724                 {
725                         self.enemy = FindTarget(self);
726                         if(self.enemy)
727                         {
728                                 WarpZone_RefSys_Copy(self.enemy, self);
729                                 WarpZone_RefSys_AddInverse(self.enemy, self); // wz1^-1 ... wzn^-1 receiver
730                                 self.moveto = WarpZone_RefSys_TransformOrigin(self.enemy, self, (0.5 * (self.enemy.absmin + self.enemy.absmax)));
731                                 
732                                 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)));
733                                 MonsterSound(monstersound_sight, 0, FALSE, CH_VOICE);
734                         }
735                 }
736
737                 self.last_enemycheck = time + 1; // check for enemies every second
738         }
739
740         if(self.state == MONSTER_STATE_ATTACK_MELEE && time >= self.attack_finished_single)
741                 self.state = 0;
742
743         if(self.state != MONSTER_STATE_ATTACK_MELEE) // don't move if set
744         if(time >= self.last_trace || self.enemy) // update enemy instantly
745                 self.moveto = monster_pickmovetarget(targ);
746
747         if(!self.enemy)
748                 MonsterSound(monstersound_idle, 7, TRUE, CH_VOICE);
749
750         if(self.state == MONSTER_STATE_ATTACK_LEAP && (self.flags & FL_ONGROUND))
751         {
752                 self.state = 0;
753                 self.touch = MonsterTouch;
754         }
755
756         if(self.state == MONSTER_STATE_ATTACK_MELEE)
757                 self.moveto = self.origin;
758
759         if(self.enemy && self.enemy.vehicle)
760                 runspeed = 0;
761
762         if(!(((self.flags & FL_FLY) && (self.spawnflags & MONSTERFLAG_FLY_VERTICAL)) || (self.flags & FL_SWIM)))
763                 //v_forward = normalize(self.moveto - self.origin);
764         //else
765                 self.moveto_z = self.origin_z;
766
767         if(vlen(self.origin - self.moveto) > 64)
768         {
769                 if((self.flags & FL_ONGROUND) || ((self.flags & FL_FLY) || (self.flags & FL_SWIM)))
770                         monster_CalculateVelocity(self, self.moveto, self.origin, TRUE, ((self.enemy) ? runspeed : walkspeed));
771                 
772                 /*&if(self.flags & FL_FLY || self.flags & FL_SWIM)
773                         movelib_move_simple(v_forward, ((self.enemy) ? runspeed : walkspeed), 0.6);
774                 else
775                         movelib_move_simple_gravity(v_forward, ((self.enemy) ? runspeed : walkspeed), 0.6); */
776
777                 if(time > self.pain_finished)
778                 if(time > self.attack_finished_single)
779                 if(vlen(self.velocity) > 10)
780                         self.frame = ((self.enemy) ? manim_run : manim_walk);
781                 else
782                         self.frame = manim_idle;
783         }
784         else
785         {
786                 entity e = find(world, targetname, self.target2);
787                 if(e.target2)
788                         self.target2 = e.target2;
789                 else if(e.target)
790                         self.target2 = e.target;
791
792                 movelib_beak_simple(stopspeed);
793                 if(time > self.attack_finished_single)
794                 if(time > self.pain_finished)
795                 if (vlen(self.velocity) <= 30)
796                         self.frame = manim_idle;
797         }
798         
799         self.steerto = steerlib_attract2(self.moveto, 0.5, 500, 0.95);
800         
801         vector real_angle = vectoangles(self.steerto) - self.angles;
802         float turny = 25;
803         if(self.state == MONSTER_STATE_ATTACK_MELEE)
804                 turny = 0;
805         if(turny)
806         {
807                 turny = bound(turny * -1, shortangle_f(real_angle_y, self.angles_y), turny);
808                 self.angles_y += turny;
809         }
810
811         monster_checkattack(self, self.enemy);
812 }
813
814 void monster_remove(entity mon)
815 {
816         if(!mon)
817                 return; // nothing to remove
818
819         pointparticles(particleeffectnum("item_pickup"), mon.origin, '0 0 0', 1);
820
821         if(mon.weaponentity)
822                 remove(mon.weaponentity);
823
824         if(mon.iceblock)
825                 remove(mon.iceblock);
826
827         WaypointSprite_Kill(mon.sprite);
828
829         remove(mon);
830 }
831
832 void monster_dead_think()
833 {
834         self.nextthink = time + self.ticrate;
835
836         CSQCMODEL_AUTOUPDATE();
837
838         if(self.monster_lifetime != 0)
839         if(time >= self.monster_lifetime)
840         {
841                 Monster_Fade();
842                 return;
843         }
844 }
845
846 void monsters_setstatus()
847 {
848         self.stat_monsters_total = monsters_total;
849         self.stat_monsters_killed = monsters_killed;
850 }
851
852 void Monster_Appear()
853 {
854         self.enemy = activator;
855         self.spawnflags &= ~MONSTERFLAG_APPEAR; // otherwise, we get an endless loop
856         monster_initialize(self.monsterid);
857 }
858
859 float Monster_CheckAppearFlags(entity ent, float monster_id)
860 {
861         if(!(ent.spawnflags & MONSTERFLAG_APPEAR))
862                 return FALSE;
863
864         ent.think = func_null;
865         ent.monsterid = monster_id; // set so this monster is properly registered (otherwise, normal initialization is used)
866         ent.nextthink = 0;
867         ent.use = Monster_Appear;
868         ent.flags = FL_MONSTER; // set so this monster can get butchered
869
870         return TRUE;
871 }
872
873 void monsters_reset()
874 {
875         setorigin(self, self.pos1);
876         self.angles = self.pos2;
877
878         Unfreeze(self); // remove any icy remains
879
880         self.health = self.max_health;
881         self.velocity = '0 0 0';
882         self.enemy = world;
883         self.goalentity = world;
884         self.attack_finished_single = 0;
885         self.moveto = self.origin;
886 }
887
888 void monsters_corpse_damage (entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force)
889 {
890         self.health -= damage;
891
892         Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, self, attacker);
893
894         if(self.health <= -100) // 100 health until gone?
895         {
896                 Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16, self, attacker);
897
898                 // number of monsters spawned with mobspawn command
899                 totalspawned -= 1;
900
901                 self.think = SUB_Remove;
902                 self.nextthink = time + 0.1;
903                 self.event_damage = func_null;
904         }
905 }
906
907 void monster_die(entity attacker, float gibbed)
908 {
909         self.think = monster_dead_think;
910         self.nextthink = time;
911         self.monster_lifetime = time + 5;
912
913         if(self.frozen)
914         {
915                 Unfreeze(self); // remove any icy remains
916                 self.health = 0; // reset by Unfreeze
917         }
918
919         monster_dropitem();
920
921         MonsterSound(monstersound_death, 0, FALSE, CH_VOICE);
922
923         if(!(self.spawnflags & MONSTERFLAG_SPAWNED) && !(self.spawnflags & MONSTERFLAG_RESPAWNED))
924                 monsters_killed += 1;
925
926         if(IS_PLAYER(attacker))
927         if(autocvar_g_monsters_score_spawned || !((self.spawnflags & MONSTERFLAG_SPAWNED) || (self.spawnflags & MONSTERFLAG_RESPAWNED)))
928                 PlayerScore_Add(attacker, SP_SCORE, +autocvar_g_monsters_score_kill);
929
930         if(gibbed)
931         {
932                 // number of monsters spawned with mobspawn command
933                 totalspawned -= 1;
934         }
935
936         if(self.candrop && self.weapon)
937                 W_ThrowNewWeapon(self, self.weapon, 0, self.origin, randomvec() * 150 + '0 0 325');
938
939         self.event_damage       = ((gibbed) ? func_null : monsters_corpse_damage);
940         self.solid                      = SOLID_CORPSE;
941         self.takedamage         = DAMAGE_AIM;
942         self.deadflag           = DEAD_DEAD;
943         self.enemy                      = world;
944         self.movetype           = MOVETYPE_TOSS;
945         self.moveto                     = self.origin;
946         self.touch                      = MonsterTouch; // reset incase monster was pouncing
947         self.reset                      = func_null;
948         self.state                      = 0;
949         self.attack_finished_single = 0;
950
951         if(!((self.flags & FL_FLY) || (self.flags & FL_SWIM)))
952                 self.velocity = '0 0 0';
953
954         MON_ACTION(self.monsterid, MR_DEATH);
955 }
956
957 void monsters_damage (entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force)
958 {
959         if(self.frozen && deathtype != DEATH_KILL && deathtype != DEATH_NADE_ICE_FREEZE)
960                 return;
961
962         if((self.spawnflags & MONSTERFLAG_INVINCIBLE) && deathtype != DEATH_KILL)
963                 return;
964
965         if(time < self.pain_finished && deathtype != DEATH_KILL)
966                 return;
967
968         if(time < self.spawnshieldtime && deathtype != DEATH_KILL)
969                 return;
970
971         if(deathtype == DEATH_FALL && self.draggedby != world)
972                 return;
973
974         vector v;
975         float take, save;
976
977         v = healtharmor_applydamage(self.armorvalue, self.m_armor_blockpercent, deathtype, damage);
978         take = v_x;
979         save = v_y;
980
981         self.health -= take;
982
983         WaypointSprite_UpdateHealth(self.sprite, self.health);
984
985         self.dmg_time = time;
986
987         if(sound_allowed(MSG_BROADCAST, attacker) && deathtype != DEATH_DROWN)
988                 spamsound (self, CH_PAIN, "misc/bodyimpact1.wav", VOL_BASE, ATTEN_NORM);  // FIXME: PLACEHOLDER
989
990         self.velocity += force * self.damageforcescale;
991
992         if(deathtype != DEATH_DROWN)
993         {
994                 Violence_GibSplash_At(hitloc, force, 2, bound(0, take, 200) / 16, self, attacker);
995                 if (take > 50)
996                         Violence_GibSplash_At(hitloc, force * -0.1, 3, 1, self, attacker);
997                 if (take > 100)
998                         Violence_GibSplash_At(hitloc, force * -0.2, 3, 1, self, attacker);
999         }
1000
1001         if(self.health <= 0)
1002         {
1003                 if(deathtype == DEATH_KILL)
1004                         self.candrop = FALSE; // killed by mobkill command
1005
1006                 // TODO: fix this?
1007                 activator = attacker;
1008                 other = self.enemy;
1009                 SUB_UseTargets();
1010                 self.target2 = self.oldtarget2; // reset to original target on death, incase we respawn
1011
1012                 monster_die(attacker, (self.health <= -100 || deathtype == DEATH_KILL));
1013
1014                 WaypointSprite_Kill(self.sprite);
1015
1016                 frag_attacker = attacker;
1017                 frag_target = self;
1018                 MUTATOR_CALLHOOK(MonsterDies);
1019
1020                 if(self.health <= -100 || deathtype == DEATH_KILL) // check if we're already gibbed
1021                 {
1022                         Violence_GibSplash(self, 1, 0.5, attacker);
1023
1024                         self.think = SUB_Remove;
1025                         self.nextthink = time + 0.1;
1026                 }
1027         }
1028 }
1029
1030 void monster_setupcolors(entity mon)
1031 {
1032         if(IS_PLAYER(mon.monster_owner))
1033                 mon.colormap = mon.monster_owner.colormap;
1034         else if(teamplay && mon.team)
1035                 mon.colormap = 1024 + (mon.team - 1) * 17;
1036         else
1037         {
1038                 if(mon.monster_skill <= MONSTER_SKILL_EASY)
1039                         mon.colormap = 1029;
1040                 else if(mon.monster_skill <= MONSTER_SKILL_MEDIUM)
1041                         mon.colormap = 1027;
1042                 else if(mon.monster_skill <= MONSTER_SKILL_HARD)
1043                         mon.colormap = 1038;
1044                 else if(mon.monster_skill <= MONSTER_SKILL_INSANE)
1045                         mon.colormap = 1028;
1046                 else if(mon.monster_skill <= MONSTER_SKILL_NIGHTMARE)
1047                         mon.colormap = 1032;
1048                 else
1049                         mon.colormap = 1024;
1050         }
1051 }
1052
1053 void monster_changeteam(entity ent, float newteam)
1054 {
1055         if(!teamplay) { return; }
1056         
1057         ent.team = newteam;
1058         ent.monster_attack = TRUE; // new team, activate attacking
1059         monster_setupcolors(ent);
1060         
1061         if(ent.sprite)
1062         {
1063                 WaypointSprite_UpdateTeamRadar(ent.sprite, RADARICON_DANGER, ((newteam) ? Team_ColorRGB(newteam) : '1 0 0'));
1064
1065                 ent.sprite.team = newteam;
1066                 ent.sprite.SendFlags |= 1;
1067         }
1068 }
1069
1070 void monster_think()
1071 {
1072         self.think = monster_think;
1073         self.nextthink = self.ticrate;
1074
1075         if(self.monster_lifetime)
1076         if(time >= self.monster_lifetime)
1077         {
1078                 Damage(self, self, self, self.health + self.max_health, DEATH_KILL, self.origin, self.origin);
1079                 return;
1080         }
1081
1082         MON_ACTION(self.monsterid, MR_THINK);
1083
1084         CSQCMODEL_AUTOUPDATE();
1085 }
1086
1087 float monster_spawn()
1088 {
1089         MON_ACTION(self.monsterid, MR_SETUP);
1090
1091         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1092         {
1093                 Monster_CheckMinibossFlag();
1094                 self.health *= Monster_SkillModifier();
1095         }
1096
1097         self.max_health = self.health;
1098         self.pain_finished = self.nextthink;
1099
1100         if(IS_PLAYER(self.monster_owner))
1101                 self.effects |= EF_DIMLIGHT;
1102
1103         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1104         if(!self.skin)
1105                 self.skin = rint(random() * 4);
1106
1107         if(!self.attack_range)
1108                 self.attack_range = autocvar_g_monsters_attack_range;
1109
1110         if(!self.wander_delay) { self.wander_delay = 2; }
1111         if(!self.wander_distance) { self.wander_distance = 600; }
1112
1113         precache_monstersounds();
1114         UpdateMonsterSounds();
1115
1116         if(teamplay)
1117                 self.monster_attack = TRUE; // we can have monster enemies in team games
1118
1119         MonsterSound(monstersound_spawn, 0, FALSE, CH_VOICE);
1120
1121         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'));
1122         if(!(self.spawnflags & MONSTERFLAG_INVINCIBLE))
1123         {
1124                 WaypointSprite_UpdateMaxHealth(self.sprite, self.max_health);
1125                 WaypointSprite_UpdateHealth(self.sprite, self.health);
1126         }
1127
1128         self.think = monster_think;
1129         self.nextthink = time + self.ticrate;
1130
1131         if(MUTATOR_CALLHOOK(MonsterSpawn))
1132                 return FALSE;
1133
1134         return TRUE;
1135 }
1136
1137 float monster_initialize(float mon_id)
1138 {
1139         if(!autocvar_g_monsters) { return FALSE; }
1140         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED)) { MON_ACTION(mon_id, MR_PRECACHE); }
1141         if(Monster_CheckAppearFlags(self, mon_id)) { return TRUE; } // return true so the monster isn't removed
1142
1143         entity mon = get_monsterinfo(mon_id);
1144
1145         if(!self.monster_skill)
1146                 self.monster_skill = cvar("g_monsters_skill");
1147
1148         // support for quake style removing monsters based on skill
1149         if(self.monster_skill == MONSTER_SKILL_EASY) if(self.spawnflags & MONSTERSKILL_NOTEASY) { return FALSE; }
1150         if(self.monster_skill == MONSTER_SKILL_MEDIUM) if(self.spawnflags & MONSTERSKILL_NOTMEDIUM) { return FALSE; }
1151         if(self.monster_skill == MONSTER_SKILL_HARD) if(self.spawnflags & MONSTERSKILL_NOTHARD) { return FALSE; }
1152
1153         if(self.team && !teamplay)
1154                 self.team = 0;
1155
1156         if(!(self.spawnflags & MONSTERFLAG_SPAWNED)) // naturally spawned monster
1157         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED)) // don't count re-spawning monsters either
1158                 monsters_total += 1;
1159
1160         setmodel(self, mon.model);
1161         //setsize(self, mon.mins, mon.maxs);
1162         self.flags                              = FL_MONSTER;
1163         self.takedamage                 = DAMAGE_AIM;
1164         self.bot_attack                 = TRUE;
1165         self.iscreature                 = TRUE;
1166         self.teleportable               = TRUE;
1167         self.damagedbycontents  = TRUE;
1168         self.monsterid                  = mon_id;
1169         self.damageforcescale   = 0;
1170         self.event_damage               = monsters_damage;
1171         self.touch                              = MonsterTouch;
1172         self.use                                = monster_use;
1173         self.solid                              = SOLID_BBOX;
1174         self.movetype                   = MOVETYPE_WALK;
1175         self.spawnshieldtime    = time + autocvar_g_monsters_spawnshieldtime;
1176         self.enemy                              = world;
1177         self.velocity                   = '0 0 0';
1178         self.moveto                             = self.origin;
1179         self.pos1                               = self.origin;
1180         self.pos2                               = self.angles;
1181         self.reset                              = monsters_reset;
1182         self.netname                    = mon.netname;
1183         self.monster_name               = M_NAME(mon_id);
1184         self.candrop                    = TRUE;
1185         self.view_ofs                   = '0 0 1' * (self.maxs_z * 0.5);
1186         self.oldtarget2                 = self.target2;
1187         self.pass_distance              = 0;
1188         self.deadflag                   = DEAD_NO;
1189         self.noalign                    = ((mon.spawnflags & MONSTER_TYPE_FLY) || (mon.spawnflags & MONSTER_TYPE_SWIM));
1190         self.spawn_time                 = time;
1191         self.spider_slowness    = 0;
1192         self.gravity                    = 1;
1193         self.dphitcontentsmask  = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_BOTCLIP | DPCONTENTS_MONSTERCLIP;
1194
1195         if(!self.scale)
1196                 self.scale = 1;
1197
1198         if(autocvar_g_monsters_edit)
1199                 self.grab = 1; // owner may carry their monster
1200
1201         if(autocvar_g_fullbrightplayers)
1202                 self.effects |= EF_FULLBRIGHT;
1203
1204         if(autocvar_g_nodepthtestplayers)
1205                 self.effects |= EF_NODEPTHTEST;
1206
1207         if(mon.spawnflags & MONSTER_TYPE_SWIM)
1208                 self.flags |= FL_SWIM;
1209
1210         if(mon.spawnflags & MONSTER_TYPE_FLY)
1211         {
1212                 self.flags |= FL_FLY;
1213                 self.movetype = MOVETYPE_FLY;
1214         }
1215
1216         if(mon.spawnflags & MONSTER_SIZE_BROKEN)
1217         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1218                 self.scale *= 1.3;
1219                 
1220         setsize(self, mon.mins * self.scale, mon.maxs * self.scale);
1221
1222         if(!self.ticrate)
1223                 self.ticrate = autocvar_g_monsters_think_delay;
1224
1225         self.ticrate = bound(sys_frametime, self.ticrate, 60);
1226
1227         if(!self.m_armor_blockpercent)
1228                 self.m_armor_blockpercent = 0.5;
1229
1230         if(!self.target_range)
1231                 self.target_range = autocvar_g_monsters_target_range;
1232
1233         if(!self.respawntime)
1234                 self.respawntime = autocvar_g_monsters_respawn_delay;
1235
1236         if(!self.monster_moveflags)
1237                 self.monster_moveflags = MONSTER_MOVE_WANDER;
1238
1239         if(!self.noalign)
1240         {
1241                 setorigin(self, self.origin + '0 0 20');
1242                 tracebox(self.origin + '0 0 64', self.mins, self.maxs, self.origin - '0 0 10000', MOVE_WORLDONLY, self);
1243                 setorigin(self, trace_endpos);
1244         }
1245
1246         if(!monster_spawn())
1247                 return FALSE;
1248
1249         if(!(self.spawnflags & MONSTERFLAG_RESPAWNED))
1250                 monster_setupcolors(self);
1251
1252         CSQCMODEL_AUTOINIT();
1253
1254         return TRUE;
1255 }