Preliminary support for triggering items (default action is to give the item to the...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / t_items.qc
1 #include "t_items.qh"
2
3 #include "items/_mod.qh"
4
5 #if defined(SVQC)
6
7     #include "../server/bot/api.qh"
8
9     #include <server/mutators/_mod.qh>
10
11     #include "../server/weapons/common.qh"
12     #include "../server/weapons/selection.qh"
13     #include "../server/weapons/weaponsystem.qh"
14
15     #include "constants.qh"
16     #include <common/deathtypes/all.qh>
17     #include <common/notifications/all.qh>
18         #include "triggers/subs.qh"
19     #include "util.qh"
20
21     #include <common/monsters/_mod.qh>
22
23     #include <common/weapons/_all.qh>
24
25     #include "../lib/warpzone/util_server.qh"
26 #elif defined(CSQC)
27         #include "physics/movetypes/movetypes.qh"
28         #include <common/weapons/_all.qh>
29         #include "../lib/csqcmodel/cl_model.qh"
30         #include "../lib/csqcmodel/common.qh"
31 #endif
32
33 REGISTER_NET_LINKED(ENT_CLIENT_ITEM)
34
35 #ifdef CSQC
36 bool autocvar_cl_ghost_items_vehicle = true;
37 .vector item_glowmod;
38 void Item_SetAlpha(entity this)
39 {
40         bool veh_hud = (hud && autocvar_cl_ghost_items_vehicle);
41
42         if(!veh_hud && (this.ItemStatus & ITS_AVAILABLE))
43         {
44                 this.alpha = 1;
45                 this.colormod = '1 1 1';
46                 this.glowmod = this.item_glowmod;
47         }
48         else
49         {
50                 if (autocvar_cl_ghost_items_color)
51                 {
52                         this.alpha = autocvar_cl_ghost_items;
53                         this.colormod = this.glowmod = autocvar_cl_ghost_items_color;
54                 }
55                 else
56                         this.alpha = -1;
57         }
58
59         if(!veh_hud)
60         if(this.ItemStatus & ITS_STAYWEP)
61         {
62                 this.colormod = this.glowmod = autocvar_cl_weapon_stay_color;
63                 this.alpha = autocvar_cl_weapon_stay_alpha;
64         }
65 }
66
67 void ItemDraw(entity this)
68 {
69     if(this.gravity)
70     {
71         Movetype_Physics_MatchServer(this, false);
72         if(IS_ONGROUND(this))
73         { // For some reason avelocity gets set to '0 0 0' here ...
74             this.oldorigin = this.origin;
75             this.gravity = 0;
76
77             if(autocvar_cl_animate_items)
78             { // ... so reset it if animations are requested.
79                 if(this.ItemStatus & ITS_ANIMATE1)
80                     this.avelocity = '0 180 0';
81
82                 if(this.ItemStatus & ITS_ANIMATE2)
83                     this.avelocity = '0 -90 0';
84             }
85
86             // delay is for blocking item's position for a while;
87             // it's a workaround for dropped weapons that receive the position
88             // another time right after they spawn overriding animation position
89             this.onground_time = time + 0.5;
90         }
91     }
92     else if (autocvar_cl_animate_items)
93     {
94         if(this.ItemStatus & ITS_ANIMATE1)
95         {
96             this.angles += this.avelocity * frametime;
97             float fade_in = bound(0, time - this.onground_time, 1);
98             setorigin(this, this.oldorigin + fade_in * ('0 0 10' + '0 0 8' * sin((time - this.onground_time) * 2)));
99         }
100
101         if(this.ItemStatus & ITS_ANIMATE2)
102         {
103             this.angles += this.avelocity * frametime;
104             float fade_in = bound(0, time - this.onground_time, 1);
105             setorigin(this, this.oldorigin + fade_in * ('0 0 8' + '0 0 4' * sin((time - this.onground_time) * 3)));
106         }
107     }
108
109     Item_SetAlpha(this);
110 }
111
112 void ItemDrawSimple(entity this)
113 {
114     if(this.gravity)
115     {
116         Movetype_Physics_MatchServer(this, false);
117
118         if(IS_ONGROUND(this))
119             this.gravity = 0;
120     }
121
122     Item_SetAlpha(this);
123 }
124
125 void Item_PreDraw(entity this)
126 {
127         if(warpzone_warpzones_exist)
128         {
129                 // just incase warpzones were initialized last, reset these
130                 //this.alpha = 1; // alpha is already set by the draw function
131                 this.drawmask = MASK_NORMAL;
132                 return;
133         }
134         float alph;
135         vector org = getpropertyvec(VF_ORIGIN);
136         if(!checkpvs(org, this)) // this makes sense as long as we don't support recursive warpzones
137                 alph = 0;
138         else if(this.fade_start)
139                 alph = bound(0, (this.fade_end - vlen(org - this.origin - 0.5 * (this.mins + this.maxs))) / (this.fade_end - this.fade_start), 1);
140         else
141                 alph = 1;
142         //printf("%v <-> %v\n", view_origin, this.origin + 0.5 * (this.mins + this.maxs));
143         if(!hud && (this.ItemStatus & ITS_AVAILABLE))
144                 this.alpha = alph;
145         if(alph <= 0)
146                 this.drawmask = 0;
147         else
148                 this.drawmask = MASK_NORMAL;
149 }
150
151 void ItemRemove(entity this)
152 {
153         if(this.mdl)
154                 strunzone(this.mdl);
155 }
156
157 NET_HANDLE(ENT_CLIENT_ITEM, bool isnew)
158 {
159     int sf = ReadByte();
160
161     if(sf & ISF_LOCATION)
162     {
163         this.origin_x = ReadCoord();
164         this.origin_y = ReadCoord();
165         this.origin_z = ReadCoord();
166         setorigin(this, this.origin);
167         this.oldorigin = this.origin;
168     }
169
170     if(sf & ISF_ANGLES)
171     {
172         this.angles_x = ReadAngle();
173         this.angles_y = ReadAngle();
174         this.angles_z = ReadAngle();
175     }
176
177     if(sf & ISF_SIZE)
178     {
179         float use_bigsize = ReadByte();
180         setsize(this, '-16 -16 0', (use_bigsize) ? '16 16 48' : '16 16 32');
181     }
182
183     if(sf & ISF_STATUS) // need to read/write status frist so model can handle simple, fb etc.
184     {
185         this.ItemStatus = ReadByte();
186
187         Item_SetAlpha(this);
188
189         if(autocvar_cl_fullbright_items)
190             if(this.ItemStatus & ITS_ALLOWFB)
191                 this.effects |= EF_FULLBRIGHT;
192
193         if(this.ItemStatus & ITS_GLOW)
194         {
195             if(this.ItemStatus & ITS_AVAILABLE)
196                 this.effects |= (EF_ADDITIVE | EF_FULLBRIGHT);
197             else
198                  this.effects &= ~(EF_ADDITIVE | EF_FULLBRIGHT);
199         }
200     }
201
202     if(sf & ISF_MODEL)
203     {
204         this.drawmask  = MASK_NORMAL;
205                 set_movetype(this, MOVETYPE_TOSS);
206                 if (isnew) IL_PUSH(g_drawables, this);
207         this.draw       = ItemDraw;
208         this.solid = SOLID_TRIGGER;
209         //this.flags |= FL_ITEM;
210
211         bool use_bigsize = ReadByte();
212
213         this.fade_end = ReadShort();
214         this.fade_start = ReadShort();
215         if(this.fade_start && !autocvar_cl_items_nofade)
216                 setpredraw(this, Item_PreDraw);
217
218         if(this.mdl)
219             strunzone(this.mdl);
220
221         this.mdl = "";
222         string _fn = ReadString();
223
224         if(autocvar_cl_simple_items && (this.ItemStatus & ITS_ALLOWSI))
225         {
226             string _fn2 = substring(_fn, 0 , strlen(_fn) -4);
227             this.draw = ItemDrawSimple;
228
229             if(fexists(sprintf("%s%s.md3", _fn2, autocvar_cl_simpleitems_postfix)))
230                 this.mdl = strzone(sprintf("%s%s.md3", _fn2, autocvar_cl_simpleitems_postfix));
231             else if(fexists(sprintf("%s%s.dpm", _fn2, autocvar_cl_simpleitems_postfix)))
232                 this.mdl = strzone(sprintf("%s%s.dpm", _fn2, autocvar_cl_simpleitems_postfix));
233             else if(fexists(sprintf("%s%s.iqm", _fn2, autocvar_cl_simpleitems_postfix)))
234                 this.mdl = strzone(sprintf("%s%s.iqm", _fn2, autocvar_cl_simpleitems_postfix));
235             else if(fexists(sprintf("%s%s.mdl", _fn2, autocvar_cl_simpleitems_postfix)))
236                 this.mdl = strzone(sprintf("%s%s.mdl", _fn2, autocvar_cl_simpleitems_postfix));
237             else
238             {
239                 this.draw = ItemDraw;
240                 LOG_TRACE("Simple item requested for ", _fn, " but no model exists for it");
241             }
242         }
243
244         if(this.draw != ItemDrawSimple)
245             this.mdl = strzone(_fn);
246
247
248         if(this.mdl == "")
249             LOG_TRACE("^1WARNING!^7 this.mdl is unset for item ", this.classname, ", tell tZork about this!");
250
251         precache_model(this.mdl);
252         _setmodel(this, this.mdl);
253
254         setsize(this, '-16 -16 0', (use_bigsize) ? '16 16 48' : '16 16 32');
255     }
256
257     if(sf & ISF_COLORMAP)
258     {
259         this.colormap = ReadShort();
260         this.item_glowmod_x = ReadByte() / 255.0;
261         this.item_glowmod_y = ReadByte() / 255.0;
262         this.item_glowmod_z = ReadByte() / 255.0;
263     }
264
265     if(sf & ISF_DROP)
266     {
267         this.gravity = 1;
268         this.pushable = true;
269         //this.angles = '0 0 0';
270         set_movetype(this, MOVETYPE_TOSS);
271         this.velocity_x = ReadCoord();
272         this.velocity_y = ReadCoord();
273         this.velocity_z = ReadCoord();
274         setorigin(this, this.oldorigin);
275
276         if(!this.move_time)
277         {
278             this.move_time = time;
279             this.spawntime = time;
280         }
281         else
282             this.move_time = max(this.move_time, time);
283     }
284
285     if(autocvar_cl_animate_items)
286     {
287         if(this.ItemStatus & ITS_ANIMATE1)
288             this.avelocity = '0 180 0';
289
290         if(this.ItemStatus & ITS_ANIMATE2)
291             this.avelocity = '0 -90 0';
292     }
293
294     this.entremove = ItemRemove;
295
296     return true;
297 }
298
299 #endif
300
301 #ifdef SVQC
302 bool ItemSend(entity this, entity to, int sf)
303 {
304         if(this.gravity)
305                 sf |= ISF_DROP;
306         else
307                 sf &= ~ISF_DROP;
308
309         WriteHeader(MSG_ENTITY, ENT_CLIENT_ITEM);
310         WriteByte(MSG_ENTITY, sf);
311
312         //WriteByte(MSG_ENTITY, this.cnt);
313         if(sf & ISF_LOCATION)
314         {
315                 WriteCoord(MSG_ENTITY, this.origin.x);
316                 WriteCoord(MSG_ENTITY, this.origin.y);
317                 WriteCoord(MSG_ENTITY, this.origin.z);
318         }
319
320         if(sf & ISF_ANGLES)
321         {
322                 WriteAngle(MSG_ENTITY, this.angles_x);
323                 WriteAngle(MSG_ENTITY, this.angles_y);
324                 WriteAngle(MSG_ENTITY, this.angles_z);
325         }
326
327         if(sf & ISF_SIZE)
328         {
329                 Pickup p = this.itemdef;
330                 WriteByte(MSG_ENTITY, p.instanceOfPowerup || p.instanceOfHealth || p.instanceOfArmor);
331         }
332
333         if(sf & ISF_STATUS)
334                 WriteByte(MSG_ENTITY, this.ItemStatus);
335
336         if(sf & ISF_MODEL)
337         {
338                 Pickup p = this.itemdef;
339                 WriteByte(MSG_ENTITY, p.instanceOfPowerup || p.instanceOfHealth || p.instanceOfArmor);
340                 WriteShort(MSG_ENTITY, this.fade_end);
341                 WriteShort(MSG_ENTITY, this.fade_start);
342
343                 if(this.mdl == "")
344                         LOG_TRACE("^1WARNING!^7 this.mdl is unset for item ", this.classname, "expect a crash just about now");
345
346                 WriteString(MSG_ENTITY, this.mdl);
347         }
348
349
350         if(sf & ISF_COLORMAP)
351         {
352                 WriteShort(MSG_ENTITY, this.colormap);
353                 WriteByte(MSG_ENTITY, this.glowmod.x * 255.0);
354         WriteByte(MSG_ENTITY, this.glowmod.y * 255.0);
355         WriteByte(MSG_ENTITY, this.glowmod.z * 255.0);
356         }
357
358         if(sf & ISF_DROP)
359         {
360                 WriteCoord(MSG_ENTITY, this.velocity.x);
361                 WriteCoord(MSG_ENTITY, this.velocity.y);
362                 WriteCoord(MSG_ENTITY, this.velocity.z);
363         }
364
365         return true;
366 }
367
368 void ItemUpdate(entity this)
369 {
370         this.oldorigin = this.origin;
371         this.SendFlags |= ISF_LOCATION;
372 }
373
374 void UpdateItemAfterTeleport(entity this)
375 {
376         if(getSendEntity(this) == ItemSend)
377                 ItemUpdate(this);
378 }
379
380 bool have_pickup_item(entity this)
381 {
382         if(this.itemdef.instanceOfPowerup)
383         {
384                 if(autocvar_g_powerups > 0)
385                         return true;
386                 if(autocvar_g_powerups == 0)
387                         return false;
388         }
389         else
390         {
391                 if(autocvar_g_pickup_items > 0)
392                         return true;
393                 if(autocvar_g_pickup_items == 0)
394                         return false;
395                 if(g_weaponarena)
396                         if(this.weapons || this.itemdef.instanceOfAmmo) // no item or ammo pickups in weaponarena
397                                 return false;
398         }
399         return true;
400 }
401
402 /*
403 float Item_Customize()
404 {
405         if(this.spawnshieldtime)
406                 return true;
407         if(this.weapons & ~other.weapons)
408         {
409                 this.colormod = '0 0 0';
410                 this.glowmod = this.colormod;
411                 this.alpha = 0.5 + 0.5 * g_ghost_items; // halfway more alpha
412                 return true;
413         }
414         else
415         {
416                 if(g_ghost_items)
417                 {
418                         this.colormod = stov(autocvar_g_ghost_items_color);
419                         this.glowmod = this.colormod;
420                         this.alpha = g_ghost_items;
421                         return true;
422                 }
423                 else
424                         return false;
425         }
426 }
427 */
428
429 void Item_Show (entity e, float mode)
430 {
431         e.effects &= ~(EF_ADDITIVE | EF_STARDUST | EF_FULLBRIGHT | EF_NODEPTHTEST);
432         e.ItemStatus &= ~ITS_STAYWEP;
433         entity def = e.itemdef;
434         if (mode > 0)
435         {
436                 // make the item look normal, and be touchable
437                 e.model = e.mdl;
438                 e.solid = SOLID_TRIGGER;
439                 e.spawnshieldtime = 1;
440                 e.ItemStatus |= ITS_AVAILABLE;
441         }
442         else if (mode < 0)
443         {
444                 // hide the item completely
445                 e.model = string_null;
446                 e.solid = SOLID_NOT;
447                 e.spawnshieldtime = 1;
448                 e.ItemStatus &= ~ITS_AVAILABLE;
449         }
450         else {
451         bool nostay = def.instanceOfWeaponPickup ? !!(def.m_weapon.weapons & WEPSET_SUPERWEAPONS) : false // no weapon-stay on superweapons
452                 || e.team // weapon stay isn't supported for teamed weapons
453                 ;
454         if(def.instanceOfWeaponPickup && !nostay && g_weapon_stay)
455         {
456                 // make the item translucent and not touchable
457                 e.model = e.mdl;
458                 e.solid = SOLID_TRIGGER; // can STILL be picked up!
459                 e.effects |= EF_STARDUST;
460                 e.spawnshieldtime = 0; // field indicates whether picking it up may give you anything other than the weapon
461                 e.ItemStatus |= (ITS_AVAILABLE | ITS_STAYWEP);
462         }
463         else
464         {
465                 //setmodel(e, "null");
466                 e.solid = SOLID_NOT;
467                 e.colormod = '0 0 0';
468                 //e.glowmod = e.colormod;
469                 e.spawnshieldtime = 1;
470                 e.ItemStatus &= ~ITS_AVAILABLE;
471         }}
472
473         if (def.m_glow)
474                 e.ItemStatus |= ITS_GLOW;
475
476         if (autocvar_g_nodepthtestitems)
477                 e.effects |= EF_NODEPTHTEST;
478
479
480         if (autocvar_g_fullbrightitems)
481                 e.ItemStatus |= ITS_ALLOWFB;
482
483         if (autocvar_sv_simple_items)
484                 e.ItemStatus |= ITS_ALLOWSI;
485
486         // relink entity (because solid may have changed)
487         setorigin(e, e.origin);
488         e.SendFlags |= ISF_STATUS;
489 }
490
491 void Item_Think(entity this)
492 {
493         this.nextthink = time;
494         if(this.origin != this.oldorigin)
495                 ItemUpdate(this);
496 }
497
498 bool Item_ItemsTime_SpectatorOnly(GameItem it);
499 bool Item_ItemsTime_Allow(GameItem it);
500 float Item_ItemsTime_UpdateTime(entity e, float t);
501 void Item_ItemsTime_SetTime(entity e, float t);
502 void Item_ItemsTime_SetTimesForAllPlayers();
503
504 void Item_Respawn (entity this)
505 {
506         Item_Show(this, 1);
507         sound(this, CH_TRIGGER, this.itemdef.m_respawnsound, VOL_BASE, ATTEN_NORM);     // play respawn sound
508         setorigin(this, this.origin);
509
510     if (Item_ItemsTime_Allow(this.itemdef) || this.weapons & WEPSET_SUPERWEAPONS)
511         {
512                 float t = Item_ItemsTime_UpdateTime(this, 0);
513                 Item_ItemsTime_SetTime(this, t);
514                 Item_ItemsTime_SetTimesForAllPlayers();
515         }
516
517         setthink(this, Item_Think);
518         this.nextthink = time;
519
520         //Send_Effect(EFFECT_ITEM_RESPAWN, this.origin + this.mins_z * '0 0 1' + '0 0 48', '0 0 0', 1);
521         Send_Effect(EFFECT_ITEM_RESPAWN, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
522 }
523
524 void Item_RespawnCountdown (entity this)
525 {
526         if(this.count >= ITEM_RESPAWN_TICKS)
527         {
528                 if(this.waypointsprite_attached)
529                         WaypointSprite_Kill(this.waypointsprite_attached);
530                 Item_Respawn(this);
531         }
532         else
533         {
534                 this.nextthink = time + 1;
535                 this.count += 1;
536                 if(this.count == 1)
537                 {
538                         MUTATOR_CALLHOOK(Item_RespawnCountdown, string_null, '0 0 0');
539                         do {
540                                 {
541                                         entity wi = Weapons_from(this.weapon);
542                                         if (wi != WEP_Null) {
543                                                 entity wp = WaypointSprite_Spawn(WP_Weapon, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Weapon);
544                                                 wp.wp_extra = wi.m_id;
545                                                 break;
546                                         }
547                                 }
548                                 {
549                                         entity ii = this.itemdef;
550                                         if (ii != NULL) {
551                                                 entity wp = WaypointSprite_Spawn(WP_Item, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Item);
552                                                 wp.wp_extra = ii.m_id;
553                                                 break;
554                                         }
555                                 }
556                         } while (0);
557             if(this.waypointsprite_attached)
558             {
559                 GameItem def = this.itemdef;
560                 if (Item_ItemsTime_SpectatorOnly(def))
561                     WaypointSprite_UpdateRule(this.waypointsprite_attached, 0, SPRITERULE_SPECTATOR);
562                 WaypointSprite_UpdateBuildFinished(this.waypointsprite_attached, time + ITEM_RESPAWN_TICKS);
563             }
564                 }
565
566                 if(this.waypointsprite_attached)
567                 {
568                         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
569                                 if(this.waypointsprite_attached.waypointsprite_visible_for_player(this.waypointsprite_attached, it, it))
570                                 {
571                                         msg_entity = it;
572                                         soundto(MSG_ONE, this, CH_TRIGGER, SND(ITEMRESPAWNCOUNTDOWN), VOL_BASE, ATTEN_NORM);    // play respawn sound
573                                 }
574                         });
575
576                         WaypointSprite_Ping(this.waypointsprite_attached);
577                         //WaypointSprite_UpdateHealth(this.waypointsprite_attached, this.count);
578                 }
579         }
580 }
581
582 void Item_RespawnThink(entity this)
583 {
584         this.nextthink = time;
585         if(this.origin != this.oldorigin)
586                 ItemUpdate(this);
587
588         if(time >= this.wait)
589                 Item_Respawn(this);
590 }
591
592 void Item_ScheduleRespawnIn(entity e, float t)
593 {
594         // if the respawn time is longer than 10 seconds, show a waypoint, otherwise, just respawn normally
595         if ((Item_ItemsTime_Allow(e.itemdef) || e.weapons & WEPSET_SUPERWEAPONS) && (t - ITEM_RESPAWN_TICKS) > 0)
596         {
597                 setthink(e, Item_RespawnCountdown);
598                 e.nextthink = time + max(0, t - ITEM_RESPAWN_TICKS);
599                 e.scheduledrespawntime = e.nextthink + ITEM_RESPAWN_TICKS;
600                 e.count = 0;
601                 t = Item_ItemsTime_UpdateTime(e, e.scheduledrespawntime);
602                 Item_ItemsTime_SetTime(e, t);
603                 Item_ItemsTime_SetTimesForAllPlayers();
604         }
605         else
606         {
607                 setthink(e, Item_RespawnThink);
608                 e.nextthink = time;
609                 e.scheduledrespawntime = time + t;
610                 e.wait = time + t;
611         }
612 }
613
614 void Item_ScheduleRespawn(entity e)
615 {
616         if(e.respawntime > 0)
617         {
618                 Item_Show(e, 0);
619                 Item_ScheduleRespawnIn(e, ITEM_RESPAWNTIME(e));
620         }
621         else // if respawntime is -1, this item does not respawn
622                 Item_Show(e, -1);
623 }
624
625 void Item_ScheduleInitialRespawn(entity e)
626 {
627         Item_Show(e, 0);
628         Item_ScheduleRespawnIn(e, game_starttime - time + ((e.respawntimestart) ? e.respawntimestart : ITEM_RESPAWNTIME_INITIAL(e)));
629 }
630
631 float Item_GiveAmmoTo(entity item, entity player, .float ammotype, float ammomax, float mode)
632 {
633         if (!item.(ammotype))
634                 return false;
635
636         if (item.spawnshieldtime)
637         {
638                 if ((player.(ammotype) < ammomax) || item.pickup_anyway > 0)
639                 {
640                         player.(ammotype) = bound(player.(ammotype), ammomax, player.(ammotype) + item.(ammotype));
641                         goto YEAH;
642                 }
643         }
644         else if(g_weapon_stay == 2)
645         {
646                 float mi = min(item.(ammotype), ammomax);
647                 if (player.(ammotype) < mi)
648                 {
649                         player.(ammotype) = mi;
650                         goto YEAH;
651                 }
652         }
653
654         return false;
655
656 LABEL(YEAH)
657         switch(mode)
658         {
659                 case ITEM_MODE_FUEL:
660                         player.pauserotfuel_finished = max(player.pauserotfuel_finished, time + autocvar_g_balance_pause_fuel_rot);
661                         break;
662                 case ITEM_MODE_HEALTH:
663                         player.pauserothealth_finished = max(player.pauserothealth_finished, time + autocvar_g_balance_pause_health_rot);
664                         break;
665                 case ITEM_MODE_ARMOR:
666                         player.pauserotarmor_finished = max(player.pauserotarmor_finished, time + autocvar_g_balance_pause_armor_rot);
667                         break;
668                 default:
669                         break;
670         }
671         return true;
672 }
673
674 float Item_GiveTo(entity item, entity player)
675 {
676         float _switchweapon;
677         float pickedup;
678
679         // if nothing happens to player, just return without taking the item
680         pickedup = false;
681         _switchweapon = false;
682         // in case the player has autoswitch enabled do the following:
683         // if the player is using their best weapon before items are given, they
684         // probably want to switch to an even better weapon after items are given
685         if (player.autoswitch)
686         if (PS(player).m_switchweapon == w_getbestweapon(player))
687                 _switchweapon = true;
688
689         if (!(player.weapons & WepSet_FromWeapon(PS(player).m_switchweapon)))
690                 _switchweapon = true;
691
692         pickedup |= Item_GiveAmmoTo(item, player, ammo_fuel, g_pickup_fuel_max, ITEM_MODE_FUEL);
693         pickedup |= Item_GiveAmmoTo(item, player, ammo_shells, g_pickup_shells_max, ITEM_MODE_NONE);
694         pickedup |= Item_GiveAmmoTo(item, player, ammo_nails, g_pickup_nails_max, ITEM_MODE_NONE);
695         pickedup |= Item_GiveAmmoTo(item, player, ammo_rockets, g_pickup_rockets_max, ITEM_MODE_NONE);
696         pickedup |= Item_GiveAmmoTo(item, player, ammo_cells, g_pickup_cells_max, ITEM_MODE_NONE);
697         pickedup |= Item_GiveAmmoTo(item, player, ammo_plasma, g_pickup_plasma_max, ITEM_MODE_NONE);
698         pickedup |= Item_GiveAmmoTo(item, player, health, item.max_health, ITEM_MODE_HEALTH);
699         pickedup |= Item_GiveAmmoTo(item, player, armorvalue, item.max_armorvalue, ITEM_MODE_ARMOR);
700
701         if (item.itemdef.instanceOfWeaponPickup)
702         {
703                 WepSet w;
704                 w = item.weapons;
705                 w &= ~player.weapons;
706
707                 if (w || (item.spawnshieldtime && item.pickup_anyway > 0))
708                 {
709                         pickedup = true;
710                         FOREACH(Weapons, it != WEP_Null, {
711                                 if(w & (it.m_wepset))
712                                 {
713                                         W_DropEvent(wr_pickup, player, it.m_id, item);
714                                         W_GiveWeapon(player, it.m_id);
715                                 }
716                         });
717                 }
718         }
719
720         if (item.itemdef.instanceOfPowerup)
721         {
722                 if ((item.itemdef == ITEM_JetpackRegen) && !(player.items & IT_FUEL_REGEN))
723                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_FUELREGEN_GOT);
724                 else if ((item.itemdef == ITEM_Jetpack) && !(player.items & IT_JETPACK))
725                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_JETPACK_GOT);
726         }
727
728         int its;
729         if((its = (item.items - (item.items & player.items)) & IT_PICKUPMASK))
730         {
731                 pickedup = true;
732                 player.items |= its;
733                 Send_Notification(NOTIF_ONE, player, MSG_INFO, INFO_ITEM_WEAPON_GOT, item.netname);
734         }
735
736         if (item.strength_finished)
737         {
738                 pickedup = true;
739                 player.strength_finished = max(player.strength_finished, time) + item.strength_finished;
740         }
741         if (item.invincible_finished)
742         {
743                 pickedup = true;
744                 player.invincible_finished = max(player.invincible_finished, time) + item.invincible_finished;
745         }
746         if (item.superweapons_finished)
747         {
748                 pickedup = true;
749                 player.superweapons_finished = max(player.superweapons_finished, time) + item.superweapons_finished;
750         }
751
752 LABEL(skip)
753
754         // always eat teamed entities
755         if(item.team)
756                 pickedup = true;
757
758         if (!pickedup)
759                 return 0;
760
761         // crude hack to enforce switching weapons
762         if(g_cts && item.itemdef.instanceOfWeaponPickup)
763         {
764                 W_SwitchWeapon_Force(player, Weapons_from(item.weapon));
765                 return 1;
766         }
767
768         if (_switchweapon)
769                 if (PS(player).m_switchweapon != w_getbestweapon(player))
770                         W_SwitchWeapon_Force(player, w_getbestweapon(player));
771
772         return 1;
773 }
774
775 void Item_Touch(entity this, entity toucher)
776 {
777
778         // remove the item if it's currnetly in a NODROP brush or hits a NOIMPACT surface (such as sky)
779         if (this.classname == "droppedweapon")
780         {
781                 if (ITEM_TOUCH_NEEDKILL())
782                 {
783                         delete(this);
784                         return;
785                 }
786         }
787
788         if(!(toucher.flags & FL_PICKUPITEMS)
789         || STAT(FROZEN, toucher)
790         || IS_DEAD(toucher)
791         || (this.solid != SOLID_TRIGGER)
792         || (this.owner == toucher)
793         || (time < this.item_spawnshieldtime)
794         ) { return; }
795
796         switch (MUTATOR_CALLHOOK(ItemTouch, this, toucher))
797         {
798                 case MUT_ITEMTOUCH_RETURN: { return; }
799                 case MUT_ITEMTOUCH_PICKUP: { toucher = M_ARGV(1, entity); goto pickup; }
800         }
801
802         toucher = M_ARGV(1, entity);
803
804         if (this.classname == "droppedweapon")
805         {
806                 this.strength_finished = max(0, this.strength_finished - time);
807                 this.invincible_finished = max(0, this.invincible_finished - time);
808                 this.superweapons_finished = max(0, this.superweapons_finished - time);
809         }
810         entity it = this.itemdef;
811         bool gave = ITEM_HANDLE(Pickup, it, this, toucher);
812         if (!gave)
813         {
814                 if (this.classname == "droppedweapon")
815                 {
816                         // undo what we did above
817                         this.strength_finished += time;
818                         this.invincible_finished += time;
819                         this.superweapons_finished += time;
820                 }
821                 return;
822         }
823
824 LABEL(pickup)
825
826         toucher.last_pickup = time;
827
828         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
829         _sound (toucher, (this.itemdef.instanceOfPowerup ? CH_TRIGGER_SINGLE : CH_TRIGGER), (this.item_pickupsound ? this.item_pickupsound : Sound_fixpath(this.item_pickupsound_ent)), VOL_BASE, ATTEN_NORM);
830
831         if (this.classname == "droppedweapon")
832                 delete (this);
833         else if (this.spawnshieldtime)
834         {
835                 entity e;
836                 if(this.team)
837                 {
838                         RandomSelection_Init();
839                         IL_EACH(g_items, it.team == this.team,
840                         {
841                                 if(it.itemdef) // is a registered item
842                                 {
843                                         Item_Show(it, -1);
844                                         RandomSelection_AddEnt(it, it.cnt, 0);
845                                 }
846                         });
847                         e = RandomSelection_chosen_ent;
848
849                 }
850                 else
851                         e = this;
852                 Item_ScheduleRespawn(e);
853         }
854 }
855
856 void Item_Reset(entity this)
857 {
858         Item_Show(this, !this.state);
859         setorigin(this, this.origin);
860
861         if (this.classname != "droppedweapon")
862         {
863                 setthink(this, Item_Think);
864                 this.nextthink = time;
865
866                 if (this.waypointsprite_attached)
867                         WaypointSprite_Kill(this.waypointsprite_attached);
868
869                 if (this.itemdef.instanceOfPowerup || (this.weapons & WEPSET_SUPERWEAPONS)) // do not spawn powerups initially!
870                         Item_ScheduleInitialRespawn(this);
871         }
872 }
873
874 void Item_FindTeam(entity this)
875 {
876         entity e;
877
878         if(this.effects & EF_NODRAW)
879         {
880                 // marker for item team search
881                 LOG_TRACE("Initializing item team ", ftos(this.team));
882                 RandomSelection_Init();
883                 IL_EACH(g_items, it.team == this.team,
884                 {
885                         if(it.itemdef) // is a registered item
886                                 RandomSelection_AddEnt(it, it.cnt, 0);
887                 });
888
889                 e = RandomSelection_chosen_ent;
890                 e.state = 0;
891                 Item_Show(e, 1);
892
893                 IL_EACH(g_items, it.team == this.team,
894                 {
895                         if(it.itemdef) // is a registered item
896                         {
897                                 if(it != e)
898                                 {
899                                         // make it non-spawned
900                                         Item_Show(it, -1);
901                                         it.state = 1; // state 1 = initially hidden item, apparently
902                                 }
903                                 it.effects &= ~EF_NODRAW;
904                         }
905                 });
906
907                 Item_Reset(this);
908         }
909 }
910
911 // Savage: used for item garbage-collection
912 void RemoveItem(entity this)
913 {
914         if(wasfreed(this) || !this) { return; }
915         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
916         delete(this);
917 }
918
919 // pickup evaluation functions
920 // these functions decide how desirable an item is to the bots
921
922 float generic_pickupevalfunc(entity player, entity item) {return item.bot_pickupbasevalue;}
923
924 float weapon_pickupevalfunc(entity player, entity item)
925 {
926         float c;
927         int rating = item.bot_pickupbasevalue;
928
929         // See if I have it already
930         if(player.weapons & item.weapons)
931         {
932                 // If I can pick it up
933                 if(!item.spawnshieldtime)
934                         c = 0;
935                 else if(player.ammo_cells || player.ammo_shells || player.ammo_plasma || player.ammo_nails || player.ammo_rockets)
936                 {
937                         if (rating > 0)
938                                 rating = BOT_PICKUP_RATING_LOW * 0.5 * (1 + rating / BOT_PICKUP_RATING_HIGH);
939                         // Skilled bots will grab more
940                         c = 1 + bound(0, skill / 10, 1) * 0.5;
941                 }
942                 else
943                         c = 0;
944         }
945         else
946                 c = 1;
947
948         if (c <= 0)
949                 return 0;
950
951         // If custom weapon priorities for bots is enabled rate most wanted weapons higher
952         if(bot_custom_weapon)
953         {
954                 int best_ratio = 0;
955                 int missing = 0;
956
957                 // evaluate weapon usefulness in all ranges
958                 for(int list = 0; list < 3; list++)
959                 {
960                         int position = -1;
961                         int wep_count = 0;
962                         int wpn = item.weapon;
963                         for (int j = 0; j < WEP_LAST; ++j)
964                         {
965                                 int list_wpn = 0;
966                                 if (list == 0) list_wpn = bot_weapons_far[j];
967                                 else if (list == 1) list_wpn = bot_weapons_mid[j];
968                                 else list_wpn = bot_weapons_close[j];
969
970                                 if (weaponsInMap & Weapons_from(list_wpn).m_wepset) // only if available
971                                 {
972                                         if (list_wpn > 0)
973                                                 wep_count++;
974                                         if (position == -1 && list_wpn == wpn)
975                                                 position = wep_count;
976                                 }
977                         }
978                         if (position == -1)
979                         {
980                                 missing++;
981                                 position = wep_count; // if missing assume last
982                         }
983                         if (wep_count)
984                         {
985                                 if (!best_ratio || position / wep_count < best_ratio)
986                                         best_ratio = position / wep_count;
987                         }
988                 }
989
990                 if (missing < 3 && best_ratio)
991                         c = c - best_ratio * 0.3;
992         }
993
994         return rating * c;
995 }
996
997 float commodity_pickupevalfunc(entity player, entity item)
998 {
999         bool need_shells = false, need_nails = false, need_rockets = false, need_cells = false, need_plasma = false, need_fuel = false;
1000         float c = 0;
1001
1002         // Detect needed ammo
1003         FOREACH(Weapons, it != WEP_Null, {
1004                 if(!(player.weapons & (it.m_wepset)))
1005                         continue;
1006
1007                 switch(it.ammo_field)
1008                 {
1009                         case ammo_shells:  need_shells  = true; break;
1010                         case ammo_nails:   need_nails   = true; break;
1011                         case ammo_rockets: need_rockets = true; break;
1012                         case ammo_cells:   need_cells   = true; break;
1013                         case ammo_plasma:  need_plasma  = true; break;
1014                         case ammo_fuel:    need_fuel    = true; break;
1015                 }
1016         });
1017
1018         // TODO: figure out if the player even has the weapon this ammo is for?
1019         // may not affect strategy much though...
1020         // find out how much more ammo/armor/health the player can hold
1021         if (need_shells)
1022         if (item.ammo_shells)
1023         if (player.ammo_shells < g_pickup_shells_max)
1024                 c = c + max(0, 1 - player.ammo_shells / g_pickup_shells_max);
1025         if (need_nails)
1026         if (item.ammo_nails)
1027         if (player.ammo_nails < g_pickup_nails_max)
1028                 c = c + max(0, 1 - player.ammo_nails / g_pickup_nails_max);
1029         if (need_rockets)
1030         if (item.ammo_rockets)
1031         if (player.ammo_rockets < g_pickup_rockets_max)
1032                 c = c + max(0, 1 - player.ammo_rockets / g_pickup_rockets_max);
1033         if (need_cells)
1034         if (item.ammo_cells)
1035         if (player.ammo_cells < g_pickup_cells_max)
1036                 c = c + max(0, 1 - player.ammo_cells / g_pickup_cells_max);
1037         if (need_plasma)
1038         if (item.ammo_plasma)
1039         if (player.ammo_plasma < g_pickup_plasma_max)
1040                 c = c + max(0, 1 - player.ammo_plasma / g_pickup_plasma_max);
1041         if (need_fuel)
1042         if (item.ammo_fuel)
1043         if (player.ammo_fuel < g_pickup_fuel_max)
1044                 c = c + max(0, 1 - player.ammo_fuel / g_pickup_fuel_max);
1045         if (item.armorvalue)
1046         if (player.armorvalue < item.max_armorvalue)
1047                 c = c + max(0, 1 - player.armorvalue / item.max_armorvalue);
1048         if (item.health)
1049         if (player.health < item.max_health)
1050                 c = c + max(0, 1 - player.health / item.max_health);
1051
1052         return item.bot_pickupbasevalue * c;
1053 }
1054
1055 void Item_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
1056 {
1057         if(ITEM_DAMAGE_NEEDKILL(deathtype))
1058                 RemoveItem(this);
1059 }
1060
1061 void item_use(entity this, entity actor, entity trigger)
1062 {
1063         // use the touch function to handle collection
1064         gettouch(this)(this, actor);
1065 }
1066
1067 void _StartItem(entity this, entity def, float defaultrespawntime, float defaultrespawntimejitter)
1068 {
1069         string itemname = def.m_name;
1070         Model itemmodel = def.m_model;
1071     Sound pickupsound = def.m_sound;
1072         float(entity player, entity item) pickupevalfunc = def.m_pickupevalfunc;
1073         float pickupbasevalue = def.m_botvalue;
1074         int itemflags = def.m_itemflags;
1075
1076         startitem_failed = false;
1077
1078         this.item_model_ent = itemmodel;
1079     this.item_pickupsound_ent = pickupsound;
1080
1081         if(!this.respawntime) // both need to be set
1082         {
1083                 this.respawntime = defaultrespawntime;
1084                 this.respawntimejitter = defaultrespawntimejitter;
1085         }
1086
1087         int itemid = def.m_itemid;
1088         this.items = itemid;
1089         int weaponid = def.instanceOfWeaponPickup ? def.m_weapon.m_id : 0;
1090         this.weapon = weaponid;
1091
1092         if(!this.fade_end)
1093         {
1094                 this.fade_start = autocvar_g_items_mindist;
1095                 this.fade_end = autocvar_g_items_maxdist;
1096         }
1097
1098         if(weaponid)
1099                 this.weapons = WepSet_FromWeapon(Weapons_from(weaponid));
1100
1101         this.flags = FL_ITEM | itemflags;
1102         IL_PUSH(g_items, this);
1103
1104         if(MUTATOR_CALLHOOK(FilterItem, this)) // error means we do not want the item
1105         {
1106                 startitem_failed = true;
1107                 delete(this);
1108                 return;
1109         }
1110
1111         // is it a dropped weapon?
1112         if (this.classname == "droppedweapon")
1113         {
1114                 this.reset = SUB_Remove;
1115                 // it's a dropped weapon
1116                 set_movetype(this, MOVETYPE_TOSS);
1117
1118                 // Savage: remove thrown items after a certain period of time ("garbage collection")
1119                 setthink(this, RemoveItem);
1120                 this.nextthink = time + 20;
1121
1122                 this.takedamage = DAMAGE_YES;
1123                 this.event_damage = Item_Damage;
1124
1125                 if(this.strength_finished || this.invincible_finished || this.superweapons_finished)
1126                 {
1127                         // if item is worthless after a timer, have it expire then
1128                         this.nextthink = max(this.strength_finished, this.invincible_finished, this.superweapons_finished);
1129                 }
1130
1131                 // don't drop if in a NODROP zone (such as lava)
1132                 traceline(this.origin, this.origin, MOVE_NORMAL, this);
1133                 if (trace_dpstartcontents & DPCONTENTS_NODROP)
1134                 {
1135                         startitem_failed = true;
1136                         delete(this);
1137                         return;
1138                 }
1139         }
1140         else
1141         {
1142                 if(!have_pickup_item(this))
1143                 {
1144                         startitem_failed = true;
1145                         delete (this);
1146                         return;
1147                 }
1148
1149                 if(this.angles != '0 0 0')
1150                         this.SendFlags |= ISF_ANGLES;
1151
1152                 this.reset = Item_Reset;
1153                 // it's a level item
1154                 if(this.spawnflags & 1)
1155                         this.noalign = 1;
1156                 if (this.noalign > 0)
1157                         set_movetype(this, MOVETYPE_NONE);
1158                 else
1159                         set_movetype(this, MOVETYPE_TOSS);
1160                 // do item filtering according to game mode and other things
1161                 if (this.noalign <= 0)
1162                 {
1163                         // first nudge it off the floor a little bit to avoid math errors
1164                         setorigin(this, this.origin + '0 0 1');
1165                         // set item size before we spawn a spawnfunc_waypoint
1166                         setsize(this, def.m_mins, def.m_maxs);
1167                         this.SendFlags |= ISF_SIZE;
1168                         // note droptofloor returns false if stuck/or would fall too far
1169                         if (!this.noalign)
1170                                 droptofloor(this);
1171                         waypoint_spawnforitem(this);
1172                 }
1173
1174                 /*
1175                  * can't do it that way, as it would break maps
1176                  * TODO make a target_give like entity another way, that perhaps has
1177                  * the weapon name in a key
1178                 if(this.targetname)
1179                 {
1180                         // target_give not yet supported; maybe later
1181                         print("removed targeted ", this.classname, "\n");
1182                         startitem_failed = true;
1183                         remove (this);
1184                         return;
1185                 }
1186                 */
1187
1188                 if(this.targetname != "" && (this.spawnflags & 16))
1189                         this.use = item_use;
1190
1191                 if(autocvar_spawn_debug >= 2)
1192                 {
1193             // why not flags & fl_item?
1194                     FOREACH_ENTITY_RADIUS(this.origin, 3, it.is_item, {
1195                 LOG_TRACE("XXX Found duplicated item: ", itemname, vtos(this.origin));
1196                 LOG_TRACE(" vs ", it.netname, vtos(it.origin));
1197                 error("Mapper sucks.");
1198             });
1199                         this.is_item = true;
1200                 }
1201
1202                 weaponsInMap |= WepSet_FromWeapon(Weapons_from(weaponid));
1203
1204                 precache_model(this.model);
1205                 precache_sound(this.item_pickupsound);
1206
1207                 if (   def.instanceOfPowerup
1208                         || def.instanceOfWeaponPickup
1209                         || (def.instanceOfHealth && def != ITEM_HealthSmall)
1210                         || (def.instanceOfArmor && def != ITEM_ArmorSmall)
1211                         || (itemid & (IT_KEY1 | IT_KEY2))
1212                 ) this.target = "###item###"; // for finding the nearest item using find()
1213
1214                 Item_ItemsTime_SetTime(this, 0);
1215         }
1216
1217         this.bot_pickup = true;
1218         this.bot_pickupevalfunc = pickupevalfunc;
1219         this.bot_pickupbasevalue = pickupbasevalue;
1220         this.mdl = this.model ? this.model : strzone(this.item_model_ent.model_str());
1221         this.netname = itemname;
1222         settouch(this, Item_Touch);
1223         setmodel(this, MDL_Null); // precision set below
1224         //this.effects |= EF_LOWPRECISION;
1225
1226         setsize (this, this.pos1 =  def.m_mins, this.pos2 = def.m_maxs);
1227
1228         this.SendFlags |= ISF_SIZE;
1229
1230         if (!(this.spawnflags & 1024)) {
1231                 if(def.instanceOfPowerup)
1232                         this.ItemStatus |= ITS_ANIMATE1;
1233
1234                 if(this.armorvalue || this.health)
1235                         this.ItemStatus |= ITS_ANIMATE2;
1236         }
1237
1238         if(def.instanceOfWeaponPickup)
1239         {
1240                 if (this.classname != "droppedweapon") // if dropped, colormap is already set up nicely
1241                         this.colormap = 1024; // color shirt=0 pants=0 grey
1242                 else
1243                         this.gravity = 1;
1244                 if (!(this.spawnflags & 1024))
1245                         this.ItemStatus |= ITS_ANIMATE1;
1246                 this.SendFlags |= ISF_COLORMAP;
1247         }
1248
1249         this.state = 0;
1250         if(this.team) // broken, no idea why.
1251         {
1252                 if(!this.cnt)
1253                         this.cnt = 1; // item probability weight
1254
1255                 this.effects |= EF_NODRAW; // marker for item team search
1256                 InitializeEntity(this, Item_FindTeam, INITPRIO_FINDTARGET);
1257         }
1258         else
1259                 Item_Reset(this);
1260
1261         Net_LinkEntity(this, !(def.instanceOfPowerup || def.instanceOfHealth || def.instanceOfArmor), 0, ItemSend);
1262
1263         // call this hook after everything else has been done
1264         if (MUTATOR_CALLHOOK(Item_Spawn, this))
1265         {
1266                 startitem_failed = true;
1267                 delete(this);
1268                 return;
1269         }
1270 }
1271
1272 void StartItem(entity this, GameItem def)
1273 {
1274     _StartItem(
1275         this,
1276         this.itemdef = def,
1277         def.m_respawntime(), // defaultrespawntime
1278         def.m_respawntimejitter() // defaultrespawntimejitter
1279         );
1280 }
1281
1282 spawnfunc(item_rockets)
1283 {
1284         if(!this.ammo_rockets)
1285                 this.ammo_rockets = g_pickup_rockets;
1286         if(!this.pickup_anyway)
1287                 this.pickup_anyway = g_pickup_ammo_anyway;
1288     StartItem(this, ITEM_Rockets);
1289 }
1290
1291 spawnfunc(item_bullets)
1292 {
1293         if(!weaponswapping)
1294         if(autocvar_sv_q3acompat_machineshotgunswap)
1295         if(this.classname != "droppedweapon")
1296         {
1297                 weaponswapping = true;
1298                 spawnfunc_item_shells(this);
1299                 weaponswapping = false;
1300                 return;
1301         }
1302
1303         if(!this.ammo_nails)
1304                 this.ammo_nails = g_pickup_nails;
1305         if(!this.pickup_anyway)
1306                 this.pickup_anyway = g_pickup_ammo_anyway;
1307     StartItem(this, ITEM_Bullets);
1308 }
1309
1310 spawnfunc(item_cells)
1311 {
1312         if(!this.ammo_cells)
1313                 this.ammo_cells = g_pickup_cells;
1314         if(!this.pickup_anyway)
1315                 this.pickup_anyway = g_pickup_ammo_anyway;
1316         StartItem(this, ITEM_Cells);
1317 }
1318
1319 spawnfunc(item_plasma)
1320 {
1321         if(!this.ammo_plasma)
1322                 this.ammo_plasma = g_pickup_plasma;
1323         if(!this.pickup_anyway)
1324                 this.pickup_anyway = g_pickup_ammo_anyway;
1325         StartItem(this, ITEM_Plasma);
1326 }
1327
1328 spawnfunc(item_shells)
1329 {
1330         if(!weaponswapping)
1331         if(autocvar_sv_q3acompat_machineshotgunswap)
1332         if(this.classname != "droppedweapon")
1333         {
1334                 weaponswapping = true;
1335                 spawnfunc_item_bullets(this);
1336                 weaponswapping = false;
1337                 return;
1338         }
1339
1340         if(!this.ammo_shells)
1341                 this.ammo_shells = g_pickup_shells;
1342         if(!this.pickup_anyway)
1343                 this.pickup_anyway = g_pickup_ammo_anyway;
1344         StartItem(this, ITEM_Shells);
1345 }
1346
1347 spawnfunc(item_armor_small)
1348 {
1349         if(!this.armorvalue)
1350                 this.armorvalue = g_pickup_armorsmall;
1351         if(!this.max_armorvalue)
1352                 this.max_armorvalue = g_pickup_armorsmall_max;
1353         if(!this.pickup_anyway)
1354                 this.pickup_anyway = g_pickup_armorsmall_anyway;
1355         StartItem(this, ITEM_ArmorSmall);
1356 }
1357
1358 spawnfunc(item_armor_medium)
1359 {
1360         if(!this.armorvalue)
1361                 this.armorvalue = g_pickup_armormedium;
1362         if(!this.max_armorvalue)
1363                 this.max_armorvalue = g_pickup_armormedium_max;
1364         if(!this.pickup_anyway)
1365                 this.pickup_anyway = g_pickup_armormedium_anyway;
1366         StartItem(this, ITEM_ArmorMedium);
1367 }
1368
1369 spawnfunc(item_armor_big)
1370 {
1371         if(!this.armorvalue)
1372                 this.armorvalue = g_pickup_armorbig;
1373         if(!this.max_armorvalue)
1374                 this.max_armorvalue = g_pickup_armorbig_max;
1375         if(!this.pickup_anyway)
1376                 this.pickup_anyway = g_pickup_armorbig_anyway;
1377         StartItem(this, ITEM_ArmorBig);
1378 }
1379
1380 spawnfunc(item_armor_mega)
1381 {
1382         if(!this.armorvalue)
1383                 this.armorvalue = g_pickup_armormega;
1384         if(!this.max_armorvalue)
1385                 this.max_armorvalue = g_pickup_armormega_max;
1386         if(!this.pickup_anyway)
1387                 this.pickup_anyway = g_pickup_armormega_anyway;
1388         StartItem(this, ITEM_ArmorMega);
1389 }
1390
1391 spawnfunc(item_health_small)
1392 {
1393         if(!this.max_health)
1394                 this.max_health = g_pickup_healthsmall_max;
1395         if(!this.health)
1396                 this.health = g_pickup_healthsmall;
1397         if(!this.pickup_anyway)
1398                 this.pickup_anyway = g_pickup_healthsmall_anyway;
1399         StartItem(this, ITEM_HealthSmall);
1400 }
1401
1402 spawnfunc(item_health_medium)
1403 {
1404         if(!this.max_health)
1405                 this.max_health = g_pickup_healthmedium_max;
1406         if(!this.health)
1407                 this.health = g_pickup_healthmedium;
1408         if(!this.pickup_anyway)
1409                 this.pickup_anyway = g_pickup_healthmedium_anyway;
1410     StartItem(this, ITEM_HealthMedium);
1411 }
1412
1413 spawnfunc(item_health_big)
1414 {
1415         if(!this.max_health)
1416                 this.max_health = g_pickup_healthbig_max;
1417         if(!this.health)
1418                 this.health = g_pickup_healthbig;
1419         if(!this.pickup_anyway)
1420                 this.pickup_anyway = g_pickup_healthbig_anyway;
1421         StartItem(this, ITEM_HealthBig);
1422 }
1423
1424 spawnfunc(item_health_mega)
1425 {
1426     if(!this.max_health)
1427         this.max_health = g_pickup_healthmega_max;
1428     if(!this.health)
1429         this.health = g_pickup_healthmega;
1430     if(!this.pickup_anyway)
1431         this.pickup_anyway = g_pickup_healthmega_anyway;
1432     StartItem(this, ITEM_HealthMega);
1433 }
1434
1435 // support old misnamed entities
1436 spawnfunc(item_armor1) { spawnfunc_item_armor_small(this); }  // FIXME: in Quake this is green armor, in Xonotic maps it is an armor shard
1437 spawnfunc(item_armor25) { spawnfunc_item_armor_mega(this); }
1438 spawnfunc(item_armor_large) { spawnfunc_item_armor_mega(this); }
1439 spawnfunc(item_health1) { spawnfunc_item_health_small(this); }
1440 spawnfunc(item_health25) { spawnfunc_item_health_medium(this); }
1441 spawnfunc(item_health_large) { spawnfunc_item_health_big(this); }
1442 spawnfunc(item_health100) { spawnfunc_item_health_mega(this); }
1443
1444 spawnfunc(item_strength)
1445 {
1446                 if(!this.strength_finished)
1447                         this.strength_finished = autocvar_g_balance_powerup_strength_time;
1448                 StartItem(this, ITEM_Strength);
1449 }
1450
1451 spawnfunc(item_invincible)
1452 {
1453                 if(!this.invincible_finished)
1454                         this.invincible_finished = autocvar_g_balance_powerup_invincible_time;
1455                 StartItem(this, ITEM_Shield);
1456 }
1457
1458 // compatibility:
1459 spawnfunc(item_quad) { this.classname = "item_strength";spawnfunc_item_strength(this);}
1460
1461 void target_items_use(entity this, entity actor, entity trigger)
1462 {
1463         if(actor.classname == "droppedweapon")
1464         {
1465                 EXACTTRIGGER_TOUCH(this, trigger);
1466                 delete(actor);
1467                 return;
1468         }
1469
1470         if (!IS_PLAYER(actor))
1471                 return;
1472         if(IS_DEAD(actor))
1473                 return;
1474         if(trigger.solid == SOLID_TRIGGER)
1475         {
1476                 EXACTTRIGGER_TOUCH(this, trigger);
1477         }
1478
1479         IL_EACH(g_items, it.enemy == actor && it.classname == "droppedweapon",
1480         {
1481                 delete(it);
1482         });
1483
1484         if(GiveItems(actor, 0, tokenize_console(this.netname)))
1485                 centerprint(actor, this.message);
1486 }
1487
1488 spawnfunc(target_items)
1489 {
1490         int n, j;
1491         string s;
1492
1493         this.use = target_items_use;
1494         if(!this.strength_finished)
1495                 this.strength_finished = autocvar_g_balance_powerup_strength_time;
1496         if(!this.invincible_finished)
1497                 this.invincible_finished = autocvar_g_balance_powerup_invincible_time;
1498         if(!this.superweapons_finished)
1499                 this.superweapons_finished = autocvar_g_balance_superweapons_time;
1500
1501         n = tokenize_console(this.netname);
1502         if(argv(0) == "give")
1503         {
1504                 this.netname = substring(this.netname, argv_start_index(1), argv_end_index(-1) - argv_start_index(1));
1505         }
1506         else
1507         {
1508                 for(j = 0; j < n; ++j)
1509                 {
1510                         if     (argv(j) == "unlimited_ammo")         this.items |= IT_UNLIMITED_AMMO;
1511                         else if(argv(j) == "unlimited_weapon_ammo")  this.items |= IT_UNLIMITED_WEAPON_AMMO;
1512                         else if(argv(j) == "unlimited_superweapons") this.items |= IT_UNLIMITED_SUPERWEAPONS;
1513                         else if(argv(j) == "strength")               this.items |= ITEM_Strength.m_itemid;
1514                         else if(argv(j) == "invincible")             this.items |= ITEM_Shield.m_itemid;
1515                         else if(argv(j) == "superweapons")           this.items |= IT_SUPERWEAPON;
1516                         else if(argv(j) == "jetpack")                this.items |= ITEM_Jetpack.m_itemid;
1517                         else if(argv(j) == "fuel_regen")             this.items |= ITEM_JetpackRegen.m_itemid;
1518                         else
1519                         {
1520                                 FOREACH(Weapons, it != WEP_Null, {
1521                                         s = W_UndeprecateName(argv(j));
1522                                         if(s == it.netname)
1523                                         {
1524                                                 this.weapons |= (it.m_wepset);
1525                                                 if(this.spawnflags == 0 || this.spawnflags == 2)
1526                                                         it.wr_init(it);
1527                                                 break;
1528                                         }
1529                                 });
1530                         }
1531                 }
1532
1533                 string itemprefix, valueprefix;
1534                 if(this.spawnflags == 0)
1535                 {
1536                         itemprefix = "";
1537                         valueprefix = "";
1538                 }
1539                 else if(this.spawnflags == 1)
1540                 {
1541                         itemprefix = "max ";
1542                         valueprefix = "max ";
1543                 }
1544                 else if(this.spawnflags == 2)
1545                 {
1546                         itemprefix = "min ";
1547                         valueprefix = "min ";
1548                 }
1549                 else if(this.spawnflags == 4)
1550                 {
1551                         itemprefix = "minus ";
1552                         valueprefix = "max ";
1553                 }
1554                 else
1555                 {
1556                         error("invalid spawnflags");
1557                         itemprefix = valueprefix = string_null;
1558                 }
1559
1560                 this.netname = "";
1561                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & IT_UNLIMITED_WEAPON_AMMO), "unlimited_weapon_ammo");
1562                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & IT_UNLIMITED_SUPERWEAPONS), "unlimited_superweapons");
1563                 this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, this.strength_finished * boolean(this.items & ITEM_Strength.m_itemid), "strength");
1564                 this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, this.invincible_finished * boolean(this.items & ITEM_Shield.m_itemid), "invincible");
1565                 this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, this.superweapons_finished * boolean(this.items & IT_SUPERWEAPON), "superweapons");
1566                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & ITEM_Jetpack.m_itemid), "jetpack");
1567                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & ITEM_JetpackRegen.m_itemid), "fuel_regen");
1568                 if(this.ammo_shells != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_shells), "shells");
1569                 if(this.ammo_nails != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_nails), "nails");
1570                 if(this.ammo_rockets != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_rockets), "rockets");
1571                 if(this.ammo_cells != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_cells), "cells");
1572                 if(this.ammo_plasma != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_plasma), "plasma");
1573                 if(this.ammo_fuel != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_fuel), "fuel");
1574                 if(this.health != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.health), "health");
1575                 if(this.armorvalue != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.armorvalue), "armor");
1576                 FOREACH(Weapons, it != WEP_Null, this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, !!(this.weapons & (it.m_wepset)), it.netname));
1577         }
1578         this.netname = strzone(this.netname);
1579         //print(this.netname, "\n");
1580
1581         n = tokenize_console(this.netname);
1582         for(j = 0; j < n; ++j)
1583         {
1584                 FOREACH(Weapons, it != WEP_Null && W_UndeprecateName(argv(j)) == it.netname, {
1585             it.wr_init(it);
1586             break;
1587                 });
1588         }
1589 }
1590
1591 spawnfunc(item_fuel)
1592 {
1593         if(!this.ammo_fuel)
1594                 this.ammo_fuel = g_pickup_fuel;
1595         if(!this.pickup_anyway)
1596                 this.pickup_anyway = g_pickup_ammo_anyway;
1597         StartItem(this, ITEM_JetpackFuel);
1598 }
1599
1600 spawnfunc(item_fuel_regen)
1601 {
1602         if(start_items & ITEM_JetpackRegen.m_itemid)
1603         {
1604                 spawnfunc_item_fuel(this);
1605                 return;
1606         }
1607         StartItem(this, ITEM_JetpackRegen);
1608 }
1609
1610 spawnfunc(item_jetpack)
1611 {
1612         if(!this.ammo_fuel)
1613                 this.ammo_fuel = g_pickup_fuel_jetpack;
1614         if(start_items & ITEM_Jetpack.m_itemid)
1615         {
1616                 spawnfunc_item_fuel(this);
1617                 return;
1618         }
1619         StartItem(this, ITEM_Jetpack);
1620 }
1621
1622 float GiveWeapon(entity e, float wpn, float op, float val)
1623 {
1624         WepSet v0, v1;
1625         WepSet s = WepSet_FromWeapon(Weapons_from(wpn));
1626         v0 = (e.weapons & s);
1627         switch(op)
1628         {
1629                 case OP_SET:
1630                         if(val > 0)
1631                                 e.weapons |= s;
1632                         else
1633                                 e.weapons &= ~s;
1634                         break;
1635                 case OP_MIN:
1636                 case OP_PLUS:
1637                         if(val > 0)
1638                                 e.weapons |= s;
1639                         break;
1640                 case OP_MAX:
1641                         if(val <= 0)
1642                                 e.weapons &= ~s;
1643                         break;
1644                 case OP_MINUS:
1645                         if(val > 0)
1646                                 e.weapons &= ~s;
1647                         break;
1648         }
1649         v1 = (e.weapons & s);
1650         return (v0 != v1);
1651 }
1652
1653 void GiveSound(entity e, float v0, float v1, float t, Sound snd_incr, Sound snd_decr)
1654 {
1655         if(v1 == v0)
1656                 return;
1657         if(v1 <= v0 - t)
1658         {
1659                 if(snd_decr != NULL)
1660                         sound (e, CH_TRIGGER, snd_decr, VOL_BASE, ATTEN_NORM);
1661         }
1662         else if(v0 >= v0 + t)
1663         {
1664                 if(snd_incr != NULL)
1665                         sound (e, CH_TRIGGER, snd_incr, VOL_BASE, ATTEN_NORM);
1666         }
1667 }
1668
1669 void GiveRot(entity e, float v0, float v1, .float rotfield, float rottime, .float regenfield, float regentime)
1670 {
1671         if(v0 < v1)
1672                 e.(rotfield) = max(e.(rotfield), time + rottime);
1673         else if(v0 > v1)
1674                 e.(regenfield) = max(e.(regenfield), time + regentime);
1675 }
1676 float GiveItems(entity e, float beginarg, float endarg)
1677 {
1678         float got, i, val, op;
1679         float _switchweapon;
1680         string cmd;
1681
1682         val = 999;
1683         op = OP_SET;
1684
1685         got = 0;
1686
1687         _switchweapon = false;
1688         if (e.autoswitch)
1689                 if (PS(e).m_switchweapon == w_getbestweapon(e))
1690                         _switchweapon = true;
1691
1692         e.strength_finished = max(0, e.strength_finished - time);
1693         e.invincible_finished = max(0, e.invincible_finished - time);
1694         e.superweapons_finished = max(0, e.superweapons_finished - time);
1695
1696         PREGIVE(e, items);
1697         PREGIVE_WEAPONS(e);
1698         PREGIVE(e, strength_finished);
1699         PREGIVE(e, invincible_finished);
1700         PREGIVE(e, superweapons_finished);
1701         PREGIVE(e, ammo_nails);
1702         PREGIVE(e, ammo_cells);
1703         PREGIVE(e, ammo_plasma);
1704         PREGIVE(e, ammo_shells);
1705         PREGIVE(e, ammo_rockets);
1706         PREGIVE(e, ammo_fuel);
1707         PREGIVE(e, armorvalue);
1708         PREGIVE(e, health);
1709
1710         for(i = beginarg; i < endarg; ++i)
1711         {
1712                 cmd = argv(i);
1713
1714                 if(cmd == "0" || stof(cmd))
1715                 {
1716                         val = stof(cmd);
1717                         continue;
1718                 }
1719                 switch(cmd)
1720                 {
1721                         case "no":
1722                                 op = OP_MAX;
1723                                 val = 0;
1724                                 continue;
1725                         case "max":
1726                                 op = OP_MAX;
1727                                 continue;
1728                         case "min":
1729                                 op = OP_MIN;
1730                                 continue;
1731                         case "plus":
1732                                 op = OP_PLUS;
1733                                 continue;
1734                         case "minus":
1735                                 op = OP_MINUS;
1736                                 continue;
1737                         case "ALL":
1738                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
1739                                 got += GiveValue(e, strength_finished, op, val);
1740                                 got += GiveValue(e, invincible_finished, op, val);
1741                                 got += GiveValue(e, superweapons_finished, op, val);
1742                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO, op, val);
1743                         case "all":
1744                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
1745                                 got += GiveValue(e, health, op, val);
1746                                 got += GiveValue(e, armorvalue, op, val);
1747                         case "allweapons":
1748                                 FOREACH(Weapons, it != WEP_Null && !(it.spawnflags & WEP_FLAG_MUTATORBLOCKED), got += GiveWeapon(e, it.m_id, op, val));
1749                         case "allammo":
1750                                 got += GiveValue(e, ammo_cells, op, val);
1751                                 got += GiveValue(e, ammo_plasma, op, val);
1752                                 got += GiveValue(e, ammo_shells, op, val);
1753                                 got += GiveValue(e, ammo_nails, op, val);
1754                                 got += GiveValue(e, ammo_rockets, op, val);
1755                                 got += GiveValue(e, ammo_fuel, op, val);
1756                                 break;
1757                         case "unlimited_ammo":
1758                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO, op, val);
1759                                 break;
1760                         case "unlimited_weapon_ammo":
1761                                 got += GiveBit(e, items, IT_UNLIMITED_WEAPON_AMMO, op, val);
1762                                 break;
1763                         case "unlimited_superweapons":
1764                                 got += GiveBit(e, items, IT_UNLIMITED_SUPERWEAPONS, op, val);
1765                                 break;
1766                         case "jetpack":
1767                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
1768                                 break;
1769                         case "fuel_regen":
1770                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
1771                                 break;
1772                         case "strength":
1773                                 got += GiveValue(e, strength_finished, op, val);
1774                                 break;
1775                         case "invincible":
1776                                 got += GiveValue(e, invincible_finished, op, val);
1777                                 break;
1778                         case "superweapons":
1779                                 got += GiveValue(e, superweapons_finished, op, val);
1780                                 break;
1781                         case "cells":
1782                                 got += GiveValue(e, ammo_cells, op, val);
1783                                 break;
1784                         case "plasma":
1785                                 got += GiveValue(e, ammo_plasma, op, val);
1786                                 break;
1787                         case "shells":
1788                                 got += GiveValue(e, ammo_shells, op, val);
1789                                 break;
1790                         case "nails":
1791                         case "bullets":
1792                                 got += GiveValue(e, ammo_nails, op, val);
1793                                 break;
1794                         case "rockets":
1795                                 got += GiveValue(e, ammo_rockets, op, val);
1796                                 break;
1797                         case "health":
1798                                 got += GiveValue(e, health, op, val);
1799                                 break;
1800                         case "armor":
1801                                 got += GiveValue(e, armorvalue, op, val);
1802                                 break;
1803                         case "fuel":
1804                                 got += GiveValue(e, ammo_fuel, op, val);
1805                                 break;
1806                         default:
1807                                 FOREACH(Weapons, it != WEP_Null && W_UndeprecateName(cmd) == it.netname, {
1808                     got += GiveWeapon(e, it.m_id, op, val);
1809                     break;
1810                                 });
1811                                 break;
1812                 }
1813                 val = 999;
1814                 op = OP_SET;
1815         }
1816
1817         POSTGIVE_BIT(e, items, ITEM_JetpackRegen.m_itemid, SND_ITEMPICKUP, SND_Null);
1818         POSTGIVE_BIT(e, items, IT_UNLIMITED_SUPERWEAPONS, SND_POWERUP, SND_POWEROFF);
1819         POSTGIVE_BIT(e, items, IT_UNLIMITED_WEAPON_AMMO, SND_POWERUP, SND_POWEROFF);
1820         POSTGIVE_BIT(e, items, ITEM_Jetpack.m_itemid, SND_ITEMPICKUP, SND_Null);
1821         FOREACH(Weapons, it != WEP_Null, {
1822                 POSTGIVE_WEAPON(e, it, SND_WEAPONPICKUP, SND_Null);
1823                 if(!(save_weapons & (it.m_wepset)))
1824                         if(e.weapons & (it.m_wepset))
1825                                 it.wr_init(it);
1826         });
1827         POSTGIVE_VALUE(e, strength_finished, 1, SND_POWERUP, SND_POWEROFF);
1828         POSTGIVE_VALUE(e, invincible_finished, 1, SND_Shield, SND_POWEROFF);
1829         //POSTGIVE_VALUE(e, superweapons_finished, 1, SND_Null, SND_Null);
1830         POSTGIVE_VALUE(e, ammo_nails, 0, SND_ITEMPICKUP, SND_Null);
1831         POSTGIVE_VALUE(e, ammo_cells, 0, SND_ITEMPICKUP, SND_Null);
1832         POSTGIVE_VALUE(e, ammo_plasma, 0, SND_ITEMPICKUP, SND_Null);
1833         POSTGIVE_VALUE(e, ammo_shells, 0, SND_ITEMPICKUP, SND_Null);
1834         POSTGIVE_VALUE(e, ammo_rockets, 0, SND_ITEMPICKUP, SND_Null);
1835         POSTGIVE_VALUE_ROT(e, ammo_fuel, 1, pauserotfuel_finished, autocvar_g_balance_pause_fuel_rot, pauseregen_finished, autocvar_g_balance_pause_fuel_regen, SND_ITEMPICKUP, SND_Null);
1836         POSTGIVE_VALUE_ROT(e, armorvalue, 1, pauserotarmor_finished, autocvar_g_balance_pause_armor_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_ARMOR25, SND_Null);
1837         POSTGIVE_VALUE_ROT(e, health, 1, pauserothealth_finished, autocvar_g_balance_pause_health_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_MEGAHEALTH, SND_Null);
1838
1839         if(e.superweapons_finished <= 0)
1840                 if(e.weapons & WEPSET_SUPERWEAPONS)
1841                         e.superweapons_finished = autocvar_g_balance_superweapons_time;
1842
1843         if(e.strength_finished <= 0)
1844                 e.strength_finished = 0;
1845         else
1846                 e.strength_finished += time;
1847         if(e.invincible_finished <= 0)
1848                 e.invincible_finished = 0;
1849         else
1850                 e.invincible_finished += time;
1851         if(e.superweapons_finished <= 0)
1852                 e.superweapons_finished = 0;
1853         else
1854                 e.superweapons_finished += time;
1855
1856         if (!(e.weapons & WepSet_FromWeapon(PS(e).m_switchweapon)))
1857                 _switchweapon = true;
1858         if(_switchweapon)
1859                 W_SwitchWeapon_Force(e, w_getbestweapon(e));
1860
1861         return got;
1862 }
1863 #endif