]> icculus.org git repositories - divverent/darkplaces.git/blob - prvm_cmds.c
fixed double-jump bug in prediction when jumping up sides of crates or on stairs
[divverent/darkplaces.git] / prvm_cmds.c
1 // AK
2 // Basically every vm builtin cmd should be in here.
3 // All 3 builtin and extension lists can be found here
4 // cause large (I think they will) parts are from pr_cmds the same copyright like in pr_cmds
5 // also applies here
6
7 #include "prvm_cmds.h"
8
9 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
10 void VM_Warning(const char *fmt, ...)
11 {
12         va_list argptr;
13         char msg[MAX_INPUTLINE];
14
15         va_start(argptr,fmt);
16         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
17         va_end(argptr);
18
19         Con_Print(msg);
20         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
21         //PRVM_PrintState();
22 }
23
24
25 //============================================================================
26 // Common
27
28 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
29 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
30 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
31 // TODO: will this war ever end? [2007-01-23 LordHavoc]
32
33 void VM_CheckEmptyString (const char *s)
34 {
35         if (s[0] <= ' ')
36                 PRVM_ERROR ("%s: Bad string", PRVM_NAME);
37 }
38
39 //============================================================================
40 //BUILT-IN FUNCTIONS
41
42 void VM_VarString(int first, char *out, int outlength)
43 {
44         int i;
45         const char *s;
46         char *outend;
47
48         outend = out + outlength - 1;
49         for (i = first;i < prog->argc && out < outend;i++)
50         {
51                 s = PRVM_G_STRING((OFS_PARM0+i*3));
52                 while (out < outend && *s)
53                         *out++ = *s++;
54         }
55         *out++ = 0;
56 }
57
58 /*
59 =================
60 VM_checkextension
61
62 returns true if the extension is supported by the server
63
64 checkextension(extensionname)
65 =================
66 */
67
68 // kind of helper function
69 static qboolean checkextension(const char *name)
70 {
71         int len;
72         char *e, *start;
73         len = (int)strlen(name);
74
75         for (e = prog->extensionstring;*e;e++)
76         {
77                 while (*e == ' ')
78                         e++;
79                 if (!*e)
80                         break;
81                 start = e;
82                 while (*e && *e != ' ')
83                         e++;
84                 if ((e - start) == len && !strncasecmp(start, name, len))
85                         return true;
86         }
87         return false;
88 }
89
90 void VM_checkextension (void)
91 {
92         VM_SAFEPARMCOUNT(1,VM_checkextension);
93
94         PRVM_G_FLOAT(OFS_RETURN) = checkextension(PRVM_G_STRING(OFS_PARM0));
95 }
96
97 /*
98 =================
99 VM_error
100
101 This is a TERMINAL error, which will kill off the entire prog.
102 Dumps self.
103
104 error(value)
105 =================
106 */
107 void VM_error (void)
108 {
109         prvm_edict_t    *ed;
110         char string[VM_STRINGTEMP_LENGTH];
111
112         VM_VarString(0, string, sizeof(string));
113         Con_Printf("======%s ERROR in %s:\n%s\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
114         if(prog->self)
115         {
116                 ed = PRVM_G_EDICT(prog->self->ofs);
117                 PRVM_ED_Print(ed);
118         }
119
120         PRVM_ERROR ("%s: Program error in function %s:\n%s\nTip: read above for entity information\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
121 }
122
123 /*
124 =================
125 VM_objerror
126
127 Dumps out self, then an error message.  The program is aborted and self is
128 removed, but the level can continue.
129
130 objerror(value)
131 =================
132 */
133 void VM_objerror (void)
134 {
135         prvm_edict_t    *ed;
136         char string[VM_STRINGTEMP_LENGTH];
137
138         VM_VarString(0, string, sizeof(string));
139         Con_Printf("======OBJECT ERROR======\n"); // , PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
140         if(prog->self)
141         {
142                 ed = PRVM_G_EDICT (prog->self->ofs);
143                 PRVM_ED_Print(ed);
144
145                 PRVM_ED_Free (ed);
146         }
147         else
148                 // objerror has to display the object fields -> else call
149                 PRVM_ERROR ("VM_objecterror: self not defined !");
150         Con_Printf("%s OBJECT ERROR in %s:\n%s\nTip: read above for entity information\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
151 }
152
153 /*
154 =================
155 VM_print
156
157 print to console
158
159 print(...[string])
160 =================
161 */
162 void VM_print (void)
163 {
164         char string[VM_STRINGTEMP_LENGTH];
165
166         VM_VarString(0, string, sizeof(string));
167         Con_Print(string);
168 }
169
170 /*
171 =================
172 VM_bprint
173
174 broadcast print to everyone on server
175
176 bprint(...[string])
177 =================
178 */
179 void VM_bprint (void)
180 {
181         char string[VM_STRINGTEMP_LENGTH];
182
183         if(!sv.active)
184         {
185                 VM_Warning("VM_bprint: game is not server(%s) !\n", PRVM_NAME);
186                 return;
187         }
188
189         VM_VarString(0, string, sizeof(string));
190         SV_BroadcastPrint(string);
191 }
192
193 /*
194 =================
195 VM_sprint (menu & client but only if server.active == true)
196
197 single print to a specific client
198
199 sprint(float clientnum,...[string])
200 =================
201 */
202 void VM_sprint (void)
203 {
204         client_t        *client;
205         int                     clientnum;
206         char string[VM_STRINGTEMP_LENGTH];
207
208         //find client for this entity
209         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
210         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
211         {
212                 VM_Warning("VM_sprint: %s: invalid client or server is not active !\n", PRVM_NAME);
213                 return;
214         }
215
216         client = svs.clients + clientnum;
217         if (!client->netconnection)
218                 return;
219
220         VM_VarString(1, string, sizeof(string));
221         MSG_WriteChar(&client->netconnection->message,svc_print);
222         MSG_WriteString(&client->netconnection->message, string);
223 }
224
225 /*
226 =================
227 VM_centerprint
228
229 single print to the screen
230
231 centerprint(clientent, value)
232 =================
233 */
234 void VM_centerprint (void)
235 {
236         char string[VM_STRINGTEMP_LENGTH];
237
238         VM_VarString(0, string, sizeof(string));
239         SCR_CenterPrint(string);
240 }
241
242 /*
243 =================
244 VM_normalize
245
246 vector normalize(vector)
247 =================
248 */
249 void VM_normalize (void)
250 {
251         float   *value1;
252         vec3_t  newvalue;
253         double  f;
254
255         VM_SAFEPARMCOUNT(1,VM_normalize);
256
257         value1 = PRVM_G_VECTOR(OFS_PARM0);
258
259         f = VectorLength2(value1);
260         if (f)
261         {
262                 f = 1.0 / sqrt(f);
263                 VectorScale(value1, f, newvalue);
264         }
265         else
266                 VectorClear(newvalue);
267
268         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
269 }
270
271 /*
272 =================
273 VM_vlen
274
275 scalar vlen(vector)
276 =================
277 */
278 void VM_vlen (void)
279 {
280         VM_SAFEPARMCOUNT(1,VM_vlen);
281         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
282 }
283
284 /*
285 =================
286 VM_vectoyaw
287
288 float vectoyaw(vector)
289 =================
290 */
291 void VM_vectoyaw (void)
292 {
293         float   *value1;
294         float   yaw;
295
296         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
297
298         value1 = PRVM_G_VECTOR(OFS_PARM0);
299
300         if (value1[1] == 0 && value1[0] == 0)
301                 yaw = 0;
302         else
303         {
304                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
305                 if (yaw < 0)
306                         yaw += 360;
307         }
308
309         PRVM_G_FLOAT(OFS_RETURN) = yaw;
310 }
311
312
313 /*
314 =================
315 VM_vectoangles
316
317 vector vectoangles(vector)
318 =================
319 */
320 void VM_vectoangles (void)
321 {
322         float   *value1;
323         float   forward;
324         float   yaw, pitch;
325
326         VM_SAFEPARMCOUNT(1,VM_vectoangles);
327
328         value1 = PRVM_G_VECTOR(OFS_PARM0);
329
330         if (value1[1] == 0 && value1[0] == 0)
331         {
332                 yaw = 0;
333                 if (value1[2] > 0)
334                         pitch = 90;
335                 else
336                         pitch = 270;
337         }
338         else
339         {
340                 // LordHavoc: optimized a bit
341                 if (value1[0])
342                 {
343                         yaw = (atan2(value1[1], value1[0]) * 180 / M_PI);
344                         if (yaw < 0)
345                                 yaw += 360;
346                 }
347                 else if (value1[1] > 0)
348                         yaw = 90;
349                 else
350                         yaw = 270;
351
352                 forward = sqrt(value1[0]*value1[0] + value1[1]*value1[1]);
353                 pitch = (atan2(value1[2], forward) * 180 / M_PI);
354                 if (pitch < 0)
355                         pitch += 360;
356         }
357
358         PRVM_G_FLOAT(OFS_RETURN+0) = pitch;
359         PRVM_G_FLOAT(OFS_RETURN+1) = yaw;
360         PRVM_G_FLOAT(OFS_RETURN+2) = 0;
361 }
362
363 /*
364 =================
365 VM_random
366
367 Returns a number from 0<= num < 1
368
369 float random()
370 =================
371 */
372 void VM_random (void)
373 {
374         VM_SAFEPARMCOUNT(0,VM_random);
375
376         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
377 }
378
379 /*
380 =================
381 PF_sound
382
383 Each entity can have eight independant sound sources, like voice,
384 weapon, feet, etc.
385
386 Channel 0 is an auto-allocate channel, the others override anything
387 already running on that entity/channel pair.
388
389 An attenuation of 0 will play full volume everywhere in the level.
390 Larger attenuations will drop off.
391
392 =================
393 */
394 /*
395 void PF_sound (void)
396 {
397         char            *sample;
398         int                     channel;
399         prvm_edict_t            *entity;
400         int             volume;
401         float attenuation;
402
403         entity = PRVM_G_EDICT(OFS_PARM0);
404         channel = PRVM_G_FLOAT(OFS_PARM1);
405         sample = PRVM_G_STRING(OFS_PARM2);
406         volume = PRVM_G_FLOAT(OFS_PARM3) * 255;
407         attenuation = PRVM_G_FLOAT(OFS_PARM4);
408
409         if (volume < 0 || volume > 255)
410                 Host_Error ("SV_StartSound: volume = %i", volume);
411
412         if (attenuation < 0 || attenuation > 4)
413                 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
414
415         if (channel < 0 || channel > 7)
416                 Host_Error ("SV_StartSound: channel = %i", channel);
417
418         SV_StartSound (entity, channel, sample, volume, attenuation);
419 }
420 */
421
422 /*
423 =========
424 VM_localsound
425
426 localsound(string sample)
427 =========
428 */
429 void VM_localsound(void)
430 {
431         const char *s;
432
433         VM_SAFEPARMCOUNT(1,VM_localsound);
434
435         s = PRVM_G_STRING(OFS_PARM0);
436
437         if(!S_LocalSound (s))
438         {
439                 PRVM_G_FLOAT(OFS_RETURN) = -4;
440                 VM_Warning("VM_localsound: Failed to play %s for %s !\n", s, PRVM_NAME);
441                 return;
442         }
443
444         PRVM_G_FLOAT(OFS_RETURN) = 1;
445 }
446
447 /*
448 =================
449 VM_break
450
451 break()
452 =================
453 */
454 void VM_break (void)
455 {
456         PRVM_ERROR ("%s: break statement", PRVM_NAME);
457 }
458
459 //============================================================================
460
461 /*
462 =================
463 VM_localcmd
464
465 Sends text over to the client's execution buffer
466
467 [localcmd (string, ...) or]
468 cmd (string, ...)
469 =================
470 */
471 void VM_localcmd (void)
472 {
473         char string[VM_STRINGTEMP_LENGTH];
474         VM_VarString(0, string, sizeof(string));
475         Cbuf_AddText(string);
476 }
477
478 /*
479 =================
480 VM_cvar
481
482 float cvar (string)
483 =================
484 */
485 void VM_cvar (void)
486 {
487         VM_SAFEPARMCOUNT(1,VM_cvar);
488
489         PRVM_G_FLOAT(OFS_RETURN) = Cvar_VariableValue(PRVM_G_STRING(OFS_PARM0));
490 }
491
492 /*
493 =================
494 VM_cvar_string
495
496 const string    VM_cvar_string (string)
497 =================
498 */
499 void VM_cvar_string(void)
500 {
501         const char *name;
502         VM_SAFEPARMCOUNT(1,VM_cvar_string);
503
504         name = PRVM_G_STRING(OFS_PARM0);
505
506         VM_CheckEmptyString(name);
507
508         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableString(name));
509 }
510
511
512 /*
513 ========================
514 VM_cvar_defstring
515
516 const string    VM_cvar_defstring (string)
517 ========================
518 */
519 void VM_cvar_defstring (void)
520 {
521         const char *name;
522         VM_SAFEPARMCOUNT(1,VM_cvar_string);
523
524         name = PRVM_G_STRING(OFS_PARM0);
525
526         VM_CheckEmptyString(name);
527
528         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDefString(name));
529 }
530 /*
531 =================
532 VM_cvar_set
533
534 void cvar_set (string,string)
535 =================
536 */
537 void VM_cvar_set (void)
538 {
539         VM_SAFEPARMCOUNT(2,VM_cvar_set);
540
541         Cvar_Set(PRVM_G_STRING(OFS_PARM0), PRVM_G_STRING(OFS_PARM1));
542 }
543
544 /*
545 =========
546 VM_dprint
547
548 dprint(...[string])
549 =========
550 */
551 void VM_dprint (void)
552 {
553         char string[VM_STRINGTEMP_LENGTH];
554         if (developer.integer)
555         {
556                 VM_VarString(0, string, sizeof(string));
557 #if 1
558                 Con_Printf("%s", string);
559 #else
560                 Con_Printf("%s: %s", PRVM_NAME, string);
561 #endif
562         }
563 }
564
565 /*
566 =========
567 VM_ftos
568
569 string  ftos(float)
570 =========
571 */
572
573 void VM_ftos (void)
574 {
575         float v;
576         char s[128];
577
578         VM_SAFEPARMCOUNT(1, VM_ftos);
579
580         v = PRVM_G_FLOAT(OFS_PARM0);
581
582         if ((float)((int)v) == v)
583                 sprintf(s, "%i", (int)v);
584         else
585                 sprintf(s, "%f", v);
586         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
587 }
588
589 /*
590 =========
591 VM_fabs
592
593 float   fabs(float)
594 =========
595 */
596
597 void VM_fabs (void)
598 {
599         float   v;
600
601         VM_SAFEPARMCOUNT(1,VM_fabs);
602
603         v = PRVM_G_FLOAT(OFS_PARM0);
604         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
605 }
606
607 /*
608 =========
609 VM_vtos
610
611 string  vtos(vector)
612 =========
613 */
614
615 void VM_vtos (void)
616 {
617         char s[512];
618
619         VM_SAFEPARMCOUNT(1,VM_vtos);
620
621         sprintf (s, "'%5.1f %5.1f %5.1f'", PRVM_G_VECTOR(OFS_PARM0)[0], PRVM_G_VECTOR(OFS_PARM0)[1], PRVM_G_VECTOR(OFS_PARM0)[2]);
622         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
623 }
624
625 /*
626 =========
627 VM_etos
628
629 string  etos(entity)
630 =========
631 */
632
633 void VM_etos (void)
634 {
635         char s[128];
636
637         VM_SAFEPARMCOUNT(1, VM_etos);
638
639         sprintf (s, "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
640         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
641 }
642
643 /*
644 =========
645 VM_stof
646
647 float stof(...[string])
648 =========
649 */
650 void VM_stof(void)
651 {
652         char string[VM_STRINGTEMP_LENGTH];
653         VM_VarString(0, string, sizeof(string));
654         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
655 }
656
657 /*
658 ========================
659 VM_itof
660
661 float itof(intt ent)
662 ========================
663 */
664 void VM_itof(void)
665 {
666         VM_SAFEPARMCOUNT(1, VM_itof);
667         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
668 }
669
670 /*
671 ========================
672 VM_ftoe
673
674 entity ftoe(float num)
675 ========================
676 */
677 void VM_ftoe(void)
678 {
679         int ent;
680         VM_SAFEPARMCOUNT(1, VM_ftoe);
681
682         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
683         if (ent < 0 || ent >= MAX_EDICTS || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
684                 ent = 0; // return world instead of a free or invalid entity
685
686         PRVM_G_INT(OFS_RETURN) = ent;
687 }
688
689 /*
690 =========
691 VM_spawn
692
693 entity spawn()
694 =========
695 */
696
697 void VM_spawn (void)
698 {
699         prvm_edict_t    *ed;
700         prog->xfunction->builtinsprofile += 20;
701         ed = PRVM_ED_Alloc();
702         VM_RETURN_EDICT(ed);
703 }
704
705 /*
706 =========
707 VM_remove
708
709 remove(entity e)
710 =========
711 */
712
713 void VM_remove (void)
714 {
715         prvm_edict_t    *ed;
716         prog->xfunction->builtinsprofile += 20;
717
718         VM_SAFEPARMCOUNT(1, VM_remove);
719
720         ed = PRVM_G_EDICT(OFS_PARM0);
721         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
722         {
723                 if (developer.integer >= 1)
724                         VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
725         }
726         else if( ed->priv.required->free )
727         {
728                 if (developer.integer >= 1)
729                         VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
730         }
731         else
732                 PRVM_ED_Free (ed);
733 //      if (ed == prog->edicts)
734 //              PRVM_ERROR ("remove: tried to remove world");
735 //      if (PRVM_NUM_FOR_EDICT(ed) <= sv.maxclients)
736 //              Host_Error("remove: tried to remove a client");
737 }
738
739 /*
740 =========
741 VM_find
742
743 entity  find(entity start, .string field, string match)
744 =========
745 */
746
747 void VM_find (void)
748 {
749         int             e;
750         int             f;
751         const char      *s, *t;
752         prvm_edict_t    *ed;
753
754         VM_SAFEPARMCOUNT(3,VM_find);
755
756         e = PRVM_G_EDICTNUM(OFS_PARM0);
757         f = PRVM_G_INT(OFS_PARM1);
758         s = PRVM_G_STRING(OFS_PARM2);
759
760         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
761         // expects it to find all the monsters, so we must be careful to support
762         // searching for ""
763
764         for (e++ ; e < prog->num_edicts ; e++)
765         {
766                 prog->xfunction->builtinsprofile++;
767                 ed = PRVM_EDICT_NUM(e);
768                 if (ed->priv.required->free)
769                         continue;
770                 t = PRVM_E_STRING(ed,f);
771                 if (!t)
772                         t = "";
773                 if (!strcmp(t,s))
774                 {
775                         VM_RETURN_EDICT(ed);
776                         return;
777                 }
778         }
779
780         VM_RETURN_EDICT(prog->edicts);
781 }
782
783 /*
784 =========
785 VM_findfloat
786
787   entity        findfloat(entity start, .float field, float match)
788   entity        findentity(entity start, .entity field, entity match)
789 =========
790 */
791 // LordHavoc: added this for searching float, int, and entity reference fields
792 void VM_findfloat (void)
793 {
794         int             e;
795         int             f;
796         float   s;
797         prvm_edict_t    *ed;
798
799         VM_SAFEPARMCOUNT(3,VM_findfloat);
800
801         e = PRVM_G_EDICTNUM(OFS_PARM0);
802         f = PRVM_G_INT(OFS_PARM1);
803         s = PRVM_G_FLOAT(OFS_PARM2);
804
805         for (e++ ; e < prog->num_edicts ; e++)
806         {
807                 prog->xfunction->builtinsprofile++;
808                 ed = PRVM_EDICT_NUM(e);
809                 if (ed->priv.required->free)
810                         continue;
811                 if (PRVM_E_FLOAT(ed,f) == s)
812                 {
813                         VM_RETURN_EDICT(ed);
814                         return;
815                 }
816         }
817
818         VM_RETURN_EDICT(prog->edicts);
819 }
820
821 /*
822 =========
823 VM_findchain
824
825 entity  findchain(.string field, string match)
826 =========
827 */
828 // chained search for strings in entity fields
829 // entity(.string field, string match) findchain = #402;
830 void VM_findchain (void)
831 {
832         int             i;
833         int             f;
834         int             chain_of;
835         const char      *s, *t;
836         prvm_edict_t    *ent, *chain;
837
838         VM_SAFEPARMCOUNT(2,VM_findchain);
839
840         // is the same like !(prog->flag & PRVM_FE_CHAIN) - even if the operator precedence is another
841         if(!prog->flag & PRVM_FE_CHAIN)
842                 PRVM_ERROR("VM_findchain: %s doesnt have a chain field !", PRVM_NAME);
843
844         chain_of = PRVM_ED_FindField("chain")->ofs;
845
846         chain = prog->edicts;
847
848         f = PRVM_G_INT(OFS_PARM0);
849         s = PRVM_G_STRING(OFS_PARM1);
850
851         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
852         // expects it to find all the monsters, so we must be careful to support
853         // searching for ""
854
855         ent = PRVM_NEXT_EDICT(prog->edicts);
856         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
857         {
858                 prog->xfunction->builtinsprofile++;
859                 if (ent->priv.required->free)
860                         continue;
861                 t = PRVM_E_STRING(ent,f);
862                 if (!t)
863                         t = "";
864                 if (strcmp(t,s))
865                         continue;
866
867                 PRVM_E_INT(ent,chain_of) = PRVM_NUM_FOR_EDICT(chain);
868                 chain = ent;
869         }
870
871         VM_RETURN_EDICT(chain);
872 }
873
874 /*
875 =========
876 VM_findchainfloat
877
878 entity  findchainfloat(.string field, float match)
879 entity  findchainentity(.string field, entity match)
880 =========
881 */
882 // LordHavoc: chained search for float, int, and entity reference fields
883 // entity(.string field, float match) findchainfloat = #403;
884 void VM_findchainfloat (void)
885 {
886         int             i;
887         int             f;
888         int             chain_of;
889         float   s;
890         prvm_edict_t    *ent, *chain;
891
892         VM_SAFEPARMCOUNT(2, VM_findchainfloat);
893
894         if(!prog->flag & PRVM_FE_CHAIN)
895                 PRVM_ERROR("VM_findchainfloat: %s doesnt have a chain field !", PRVM_NAME);
896
897         chain_of = PRVM_ED_FindField("chain")->ofs;
898
899         chain = (prvm_edict_t *)prog->edicts;
900
901         f = PRVM_G_INT(OFS_PARM0);
902         s = PRVM_G_FLOAT(OFS_PARM1);
903
904         ent = PRVM_NEXT_EDICT(prog->edicts);
905         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
906         {
907                 prog->xfunction->builtinsprofile++;
908                 if (ent->priv.required->free)
909                         continue;
910                 if (PRVM_E_FLOAT(ent,f) != s)
911                         continue;
912
913                 PRVM_E_INT(ent,chain_of) = PRVM_EDICT_TO_PROG(chain);
914                 chain = ent;
915         }
916
917         VM_RETURN_EDICT(chain);
918 }
919
920 /*
921 ========================
922 VM_findflags
923
924 entity  findflags(entity start, .float field, float match)
925 ========================
926 */
927 // LordHavoc: search for flags in float fields
928 void VM_findflags (void)
929 {
930         int             e;
931         int             f;
932         int             s;
933         prvm_edict_t    *ed;
934
935         VM_SAFEPARMCOUNT(3, VM_findflags);
936
937
938         e = PRVM_G_EDICTNUM(OFS_PARM0);
939         f = PRVM_G_INT(OFS_PARM1);
940         s = (int)PRVM_G_FLOAT(OFS_PARM2);
941
942         for (e++ ; e < prog->num_edicts ; e++)
943         {
944                 prog->xfunction->builtinsprofile++;
945                 ed = PRVM_EDICT_NUM(e);
946                 if (ed->priv.required->free)
947                         continue;
948                 if (!PRVM_E_FLOAT(ed,f))
949                         continue;
950                 if ((int)PRVM_E_FLOAT(ed,f) & s)
951                 {
952                         VM_RETURN_EDICT(ed);
953                         return;
954                 }
955         }
956
957         VM_RETURN_EDICT(prog->edicts);
958 }
959
960 /*
961 ========================
962 VM_findchainflags
963
964 entity  findchainflags(.float field, float match)
965 ========================
966 */
967 // LordHavoc: chained search for flags in float fields
968 void VM_findchainflags (void)
969 {
970         int             i;
971         int             f;
972         int             s;
973         int             chain_of;
974         prvm_edict_t    *ent, *chain;
975
976         VM_SAFEPARMCOUNT(2, VM_findchainflags);
977
978         if(!prog->flag & PRVM_FE_CHAIN)
979                 PRVM_ERROR("VM_findchainflags: %s doesnt have a chain field !", PRVM_NAME);
980
981         chain_of = PRVM_ED_FindField("chain")->ofs;
982
983         chain = (prvm_edict_t *)prog->edicts;
984
985         f = PRVM_G_INT(OFS_PARM0);
986         s = (int)PRVM_G_FLOAT(OFS_PARM1);
987
988         ent = PRVM_NEXT_EDICT(prog->edicts);
989         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
990         {
991                 prog->xfunction->builtinsprofile++;
992                 if (ent->priv.required->free)
993                         continue;
994                 if (!PRVM_E_FLOAT(ent,f))
995                         continue;
996                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
997                         continue;
998
999                 PRVM_E_INT(ent,chain_of) = PRVM_EDICT_TO_PROG(chain);
1000                 chain = ent;
1001         }
1002
1003         VM_RETURN_EDICT(chain);
1004 }
1005
1006 /*
1007 =========
1008 VM_coredump
1009
1010 coredump()
1011 =========
1012 */
1013 void VM_coredump (void)
1014 {
1015         VM_SAFEPARMCOUNT(0,VM_coredump);
1016
1017         Cbuf_AddText("prvm_edicts ");
1018         Cbuf_AddText(PRVM_NAME);
1019         Cbuf_AddText("\n");
1020 }
1021
1022 /*
1023 =========
1024 VM_stackdump
1025
1026 stackdump()
1027 =========
1028 */
1029 void PRVM_StackTrace(void);
1030 void VM_stackdump (void)
1031 {
1032         VM_SAFEPARMCOUNT(0, VM_stackdump);
1033
1034         PRVM_StackTrace();
1035 }
1036
1037 /*
1038 =========
1039 VM_crash
1040
1041 crash()
1042 =========
1043 */
1044
1045 void VM_crash(void)
1046 {
1047         VM_SAFEPARMCOUNT(0, VM_crash);
1048
1049         PRVM_ERROR("Crash called by %s",PRVM_NAME);
1050 }
1051
1052 /*
1053 =========
1054 VM_traceon
1055
1056 traceon()
1057 =========
1058 */
1059 void VM_traceon (void)
1060 {
1061         VM_SAFEPARMCOUNT(0,VM_traceon);
1062
1063         prog->trace = true;
1064 }
1065
1066 /*
1067 =========
1068 VM_traceoff
1069
1070 traceoff()
1071 =========
1072 */
1073 void VM_traceoff (void)
1074 {
1075         VM_SAFEPARMCOUNT(0,VM_traceoff);
1076
1077         prog->trace = false;
1078 }
1079
1080 /*
1081 =========
1082 VM_eprint
1083
1084 eprint(entity e)
1085 =========
1086 */
1087 void VM_eprint (void)
1088 {
1089         VM_SAFEPARMCOUNT(1,VM_eprint);
1090
1091         PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0));
1092 }
1093
1094 /*
1095 =========
1096 VM_rint
1097
1098 float   rint(float)
1099 =========
1100 */
1101 void VM_rint (void)
1102 {
1103         float f;
1104         VM_SAFEPARMCOUNT(1,VM_rint);
1105
1106         f = PRVM_G_FLOAT(OFS_PARM0);
1107         if (f > 0)
1108                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1109         else
1110                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1111 }
1112
1113 /*
1114 =========
1115 VM_floor
1116
1117 float   floor(float)
1118 =========
1119 */
1120 void VM_floor (void)
1121 {
1122         VM_SAFEPARMCOUNT(1,VM_floor);
1123
1124         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1125 }
1126
1127 /*
1128 =========
1129 VM_ceil
1130
1131 float   ceil(float)
1132 =========
1133 */
1134 void VM_ceil (void)
1135 {
1136         VM_SAFEPARMCOUNT(1,VM_ceil);
1137
1138         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1139 }
1140
1141
1142 /*
1143 =============
1144 VM_nextent
1145
1146 entity  nextent(entity)
1147 =============
1148 */
1149 void VM_nextent (void)
1150 {
1151         int             i;
1152         prvm_edict_t    *ent;
1153
1154         i = PRVM_G_EDICTNUM(OFS_PARM0);
1155         while (1)
1156         {
1157                 prog->xfunction->builtinsprofile++;
1158                 i++;
1159                 if (i == prog->num_edicts)
1160                 {
1161                         VM_RETURN_EDICT(prog->edicts);
1162                         return;
1163                 }
1164                 ent = PRVM_EDICT_NUM(i);
1165                 if (!ent->priv.required->free)
1166                 {
1167                         VM_RETURN_EDICT(ent);
1168                         return;
1169                 }
1170         }
1171 }
1172
1173 //=============================================================================
1174
1175 /*
1176 ==============
1177 VM_changelevel
1178 server and menu
1179
1180 changelevel(string map)
1181 ==============
1182 */
1183 void VM_changelevel (void)
1184 {
1185         VM_SAFEPARMCOUNT(1, VM_changelevel);
1186
1187         if(!sv.active)
1188         {
1189                 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1190                 return;
1191         }
1192
1193 // make sure we don't issue two changelevels
1194         if (svs.changelevel_issued)
1195                 return;
1196         svs.changelevel_issued = true;
1197
1198         Cbuf_AddText (va("changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1199 }
1200
1201 /*
1202 =========
1203 VM_sin
1204
1205 float   sin(float)
1206 =========
1207 */
1208 void VM_sin (void)
1209 {
1210         VM_SAFEPARMCOUNT(1,VM_sin);
1211         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1212 }
1213
1214 /*
1215 =========
1216 VM_cos
1217 float   cos(float)
1218 =========
1219 */
1220 void VM_cos (void)
1221 {
1222         VM_SAFEPARMCOUNT(1,VM_cos);
1223         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1224 }
1225
1226 /*
1227 =========
1228 VM_sqrt
1229
1230 float   sqrt(float)
1231 =========
1232 */
1233 void VM_sqrt (void)
1234 {
1235         VM_SAFEPARMCOUNT(1,VM_sqrt);
1236         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1237 }
1238
1239 /*
1240 =========
1241 VM_asin
1242
1243 float   asin(float)
1244 =========
1245 */
1246 void VM_asin (void)
1247 {
1248         VM_SAFEPARMCOUNT(1,VM_asin);
1249         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1250 }
1251
1252 /*
1253 =========
1254 VM_acos
1255 float   acos(float)
1256 =========
1257 */
1258 void VM_acos (void)
1259 {
1260         VM_SAFEPARMCOUNT(1,VM_acos);
1261         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1262 }
1263
1264 /*
1265 =========
1266 VM_atan
1267 float   atan(float)
1268 =========
1269 */
1270 void VM_atan (void)
1271 {
1272         VM_SAFEPARMCOUNT(1,VM_atan);
1273         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1274 }
1275
1276 /*
1277 =========
1278 VM_atan2
1279 float   atan2(float,float)
1280 =========
1281 */
1282 void VM_atan2 (void)
1283 {
1284         VM_SAFEPARMCOUNT(2,VM_atan2);
1285         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1286 }
1287
1288 /*
1289 =========
1290 VM_tan
1291 float   tan(float)
1292 =========
1293 */
1294 void VM_tan (void)
1295 {
1296         VM_SAFEPARMCOUNT(1,VM_tan);
1297         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1298 }
1299
1300 /*
1301 =================
1302 VM_randomvec
1303
1304 Returns a vector of length < 1 and > 0
1305
1306 vector randomvec()
1307 =================
1308 */
1309 void VM_randomvec (void)
1310 {
1311         vec3_t          temp;
1312         //float         length;
1313
1314         VM_SAFEPARMCOUNT(0, VM_randomvec);
1315
1316         //// WTF ??
1317         do
1318         {
1319                 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1320                 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1321                 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1322         }
1323         while (DotProduct(temp, temp) >= 1);
1324         VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1325
1326         /*
1327         temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1328         temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1329         temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1330         // length returned always > 0
1331         length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1332         VectorScale(temp,length, temp);*/
1333         //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1334 }
1335
1336 //=============================================================================
1337
1338 /*
1339 =========
1340 VM_registercvar
1341
1342 float   registercvar (string name, string value, float flags)
1343 =========
1344 */
1345 void VM_registercvar (void)
1346 {
1347         const char *name, *value;
1348         int     flags;
1349
1350         VM_SAFEPARMCOUNT(3,VM_registercvar);
1351
1352         name = PRVM_G_STRING(OFS_PARM0);
1353         value = PRVM_G_STRING(OFS_PARM1);
1354         flags = (int)PRVM_G_FLOAT(OFS_PARM2);
1355         PRVM_G_FLOAT(OFS_RETURN) = 0;
1356
1357         if(flags > CVAR_MAXFLAGSVAL)
1358                 return;
1359
1360 // first check to see if it has already been defined
1361         if (Cvar_FindVar (name))
1362                 return;
1363
1364 // check for overlap with a command
1365         if (Cmd_Exists (name))
1366         {
1367                 VM_Warning("VM_registercvar: %s is a command\n", name);
1368                 return;
1369         }
1370
1371         Cvar_Get(name, value, flags);
1372
1373         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1374 }
1375
1376 /*
1377 =================
1378 VM_min
1379
1380 returns the minimum of two supplied floats
1381
1382 float min(float a, float b, ...[float])
1383 =================
1384 */
1385 void VM_min (void)
1386 {
1387         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1388         if (prog->argc == 2)
1389                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1390         else if (prog->argc >= 3)
1391         {
1392                 int i;
1393                 float f = PRVM_G_FLOAT(OFS_PARM0);
1394                 for (i = 1;i < prog->argc;i++)
1395                         if (PRVM_G_FLOAT((OFS_PARM0+i*3)) < f)
1396                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1397                 PRVM_G_FLOAT(OFS_RETURN) = f;
1398         }
1399         else
1400                 PRVM_ERROR("VM_min: %s must supply at least 2 floats", PRVM_NAME);
1401 }
1402
1403 /*
1404 =================
1405 VM_max
1406
1407 returns the maximum of two supplied floats
1408
1409 float   max(float a, float b, ...[float])
1410 =================
1411 */
1412 void VM_max (void)
1413 {
1414         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1415         if (prog->argc == 2)
1416                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1417         else if (prog->argc >= 3)
1418         {
1419                 int i;
1420                 float f = PRVM_G_FLOAT(OFS_PARM0);
1421                 for (i = 1;i < prog->argc;i++)
1422                         if (PRVM_G_FLOAT((OFS_PARM0+i*3)) > f)
1423                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1424                 PRVM_G_FLOAT(OFS_RETURN) = f;
1425         }
1426         else
1427                 PRVM_ERROR("VM_max: %s must supply at least 2 floats", PRVM_NAME);
1428 }
1429
1430 /*
1431 =================
1432 VM_bound
1433
1434 returns number bounded by supplied range
1435
1436 float   bound(float min, float value, float max)
1437 =================
1438 */
1439 void VM_bound (void)
1440 {
1441         VM_SAFEPARMCOUNT(3,VM_bound);
1442         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1443 }
1444
1445 /*
1446 =================
1447 VM_pow
1448
1449 returns a raised to power b
1450
1451 float   pow(float a, float b)
1452 =================
1453 */
1454 void VM_pow (void)
1455 {
1456         VM_SAFEPARMCOUNT(2,VM_pow);
1457         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1458 }
1459
1460 /*
1461 =================
1462 VM_copyentity
1463
1464 copies data from one entity to another
1465
1466 copyentity(entity src, entity dst)
1467 =================
1468 */
1469 void VM_copyentity (void)
1470 {
1471         prvm_edict_t *in, *out;
1472         VM_SAFEPARMCOUNT(2,VM_copyentity);
1473         in = PRVM_G_EDICT(OFS_PARM0);
1474         out = PRVM_G_EDICT(OFS_PARM1);
1475         memcpy(out->fields.vp, in->fields.vp, prog->progs->entityfields * 4);
1476 }
1477
1478 /*
1479 =================
1480 VM_setcolor
1481
1482 sets the color of a client and broadcasts the update to all connected clients
1483
1484 setcolor(clientent, value)
1485 =================
1486 */
1487 /*void PF_setcolor (void)
1488 {
1489         client_t *client;
1490         int entnum, i;
1491         prvm_eval_t *val;
1492
1493         entnum = PRVM_G_EDICTNUM(OFS_PARM0);
1494         i = PRVM_G_FLOAT(OFS_PARM1);
1495
1496         if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active)
1497         {
1498                 Con_Print("tried to setcolor a non-client\n");
1499                 return;
1500         }
1501
1502         client = svs.clients + entnum-1;
1503         if ((val = PRVM_GETEDICTFIELDVALUE(client->edict, eval_clientcolors)))
1504                 val->_float = i;
1505         client->colors = i;
1506         client->old_colors = i;
1507         client->edict->fields.server->team = (i & 15) + 1;
1508
1509         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
1510         MSG_WriteByte (&sv.reliable_datagram, entnum - 1);
1511         MSG_WriteByte (&sv.reliable_datagram, i);
1512 }*/
1513
1514 void VM_Files_Init(void)
1515 {
1516         int i;
1517         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1518                 prog->openfiles[i] = NULL;
1519 }
1520
1521 void VM_Files_CloseAll(void)
1522 {
1523         int i;
1524         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1525         {
1526                 if (prog->openfiles[i])
1527                         FS_Close(prog->openfiles[i]);
1528                 prog->openfiles[i] = NULL;
1529         }
1530 }
1531
1532 qfile_t *VM_GetFileHandle( int index )
1533 {
1534         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1535         {
1536                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1537                 return NULL;
1538         }
1539         if (prog->openfiles[index] == NULL)
1540         {
1541                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1542                 return NULL;
1543         }
1544         return prog->openfiles[index];
1545 }
1546
1547 /*
1548 =========
1549 VM_fopen
1550
1551 float   fopen(string filename, float mode)
1552 =========
1553 */
1554 // float(string filename, float mode) fopen = #110;
1555 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1556 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1557 void VM_fopen(void)
1558 {
1559         int filenum, mode;
1560         const char *modestring, *filename;
1561
1562         VM_SAFEPARMCOUNT(2,VM_fopen);
1563
1564         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1565                 if (prog->openfiles[filenum] == NULL)
1566                         break;
1567         if (filenum >= PRVM_MAX_OPENFILES)
1568         {
1569                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1570                 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENFILES);
1571                 return;
1572         }
1573         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1574         switch(mode)
1575         {
1576         case 0: // FILE_READ
1577                 modestring = "rb";
1578                 break;
1579         case 1: // FILE_APPEND
1580                 modestring = "ab";
1581                 break;
1582         case 2: // FILE_WRITE
1583                 modestring = "wb";
1584                 break;
1585         default:
1586                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1587                 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1588                 return;
1589         }
1590         filename = PRVM_G_STRING(OFS_PARM0);
1591
1592         prog->openfiles[filenum] = FS_Open(va("data/%s", filename), modestring, false, false);
1593         if (prog->openfiles[filenum] == NULL && mode == 0)
1594                 prog->openfiles[filenum] = FS_Open(va("%s", filename), modestring, false, false);
1595
1596         if (prog->openfiles[filenum] == NULL)
1597         {
1598                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1599                 if (developer.integer >= 100)
1600                         VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1601         }
1602         else
1603         {
1604                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1605                 if (developer.integer >= 100)
1606                         Con_Printf("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1607         }
1608 }
1609
1610 /*
1611 =========
1612 VM_fclose
1613
1614 fclose(float fhandle)
1615 =========
1616 */
1617 //void(float fhandle) fclose = #111; // closes a file
1618 void VM_fclose(void)
1619 {
1620         int filenum;
1621
1622         VM_SAFEPARMCOUNT(1,VM_fclose);
1623
1624         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1625         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1626         {
1627                 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1628                 return;
1629         }
1630         if (prog->openfiles[filenum] == NULL)
1631         {
1632                 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1633                 return;
1634         }
1635         FS_Close(prog->openfiles[filenum]);
1636         prog->openfiles[filenum] = NULL;
1637         if (developer.integer >= 100)
1638                 Con_Printf("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1639 }
1640
1641 /*
1642 =========
1643 VM_fgets
1644
1645 string  fgets(float fhandle)
1646 =========
1647 */
1648 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1649 void VM_fgets(void)
1650 {
1651         int c, end;
1652         char string[VM_STRINGTEMP_LENGTH];
1653         int filenum;
1654
1655         VM_SAFEPARMCOUNT(1,VM_fgets);
1656
1657         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1658         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1659         {
1660                 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1661                 return;
1662         }
1663         if (prog->openfiles[filenum] == NULL)
1664         {
1665                 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1666                 return;
1667         }
1668         end = 0;
1669         for (;;)
1670         {
1671                 c = FS_Getc(prog->openfiles[filenum]);
1672                 if (c == '\r' || c == '\n' || c < 0)
1673                         break;
1674                 if (end < VM_STRINGTEMP_LENGTH - 1)
1675                         string[end++] = c;
1676         }
1677         string[end] = 0;
1678         // remove \n following \r
1679         if (c == '\r')
1680         {
1681                 c = FS_Getc(prog->openfiles[filenum]);
1682                 if (c != '\n')
1683                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1684         }
1685         if (developer.integer >= 100)
1686                 Con_Printf("fgets: %s: %s\n", PRVM_NAME, string);
1687         if (c >= 0 || end)
1688                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
1689         else
1690                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1691 }
1692
1693 /*
1694 =========
1695 VM_fputs
1696
1697 fputs(float fhandle, string s)
1698 =========
1699 */
1700 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1701 void VM_fputs(void)
1702 {
1703         int stringlength;
1704         char string[VM_STRINGTEMP_LENGTH];
1705         int filenum;
1706
1707         VM_SAFEPARMCOUNT(2,VM_fputs);
1708
1709         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1710         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1711         {
1712                 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1713                 return;
1714         }
1715         if (prog->openfiles[filenum] == NULL)
1716         {
1717                 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1718                 return;
1719         }
1720         VM_VarString(1, string, sizeof(string));
1721         if ((stringlength = (int)strlen(string)))
1722                 FS_Write(prog->openfiles[filenum], string, stringlength);
1723         if (developer.integer >= 100)
1724                 Con_Printf("fputs: %s: %s\n", PRVM_NAME, string);
1725 }
1726
1727 /*
1728 =========
1729 VM_strlen
1730
1731 float   strlen(string s)
1732 =========
1733 */
1734 //float(string s) strlen = #114; // returns how many characters are in a string
1735 void VM_strlen(void)
1736 {
1737         VM_SAFEPARMCOUNT(1,VM_strlen);
1738
1739         PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
1740 }
1741
1742 // DRESK - Decolorized String
1743 /*
1744 =========
1745 VM_strdecolorize
1746
1747 string  strdecolorize(string s)
1748 =========
1749 */
1750 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
1751 void VM_strdecolorize(void)
1752 {
1753         char szNewString[VM_STRINGTEMP_LENGTH];
1754         const char *szString;
1755         size_t nCnt;
1756         int nPos;
1757         int nFillPos;
1758         int bFinished;
1759                 nPos = 0;
1760                 nFillPos = 0;
1761                 nCnt = 0;
1762                 bFinished = 0;
1763
1764         // Prepare Strings
1765         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
1766         szString = PRVM_G_STRING(OFS_PARM0);
1767
1768         while(!bFinished)
1769         { // Traverse through String
1770                 if( szString[nPos] == '\n' || szString[nPos] == '\r' || szString[nPos] <= 0)
1771                 { // String End Found
1772                         szNewString[nFillPos++] = szString[nPos];
1773                         bFinished = 1;
1774                 }
1775                 else
1776                 if( szString[nPos] == STRING_COLOR_TAG)
1777                 { // Color Code Located
1778                         if( szString[nPos + 1] == STRING_COLOR_TAG)
1779                         { // Valid Characters to Include
1780                                 szNewString[nFillPos++] = szString[nPos];
1781                                 nPos = nPos + 1;
1782                                 szNewString[nFillPos++] = szString[nPos];
1783                         }
1784                         else
1785                         if( szString[nPos + 1] >= '0' && szString[nPos + 1] <= '9' )
1786                         { // Color Code Found; Increment Position
1787                                 nPos = nPos + 1;
1788                         }
1789                         else
1790                         { // Unknown Color Code; Include
1791                                 szNewString[nFillPos++] = szString[nPos];
1792                                 nPos = nPos + 1;
1793                         }
1794                 }
1795                 else
1796                         // Include Character
1797                         szNewString[nFillPos++] = szString[nPos];
1798
1799                         // Increment Position
1800                         nPos = nPos + 1;
1801         }
1802
1803         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
1804 }
1805
1806 // DRESK - String Length (not counting color codes)
1807 /*
1808 =========
1809 VM_strlennocol
1810
1811 float   strlennocol(string s)
1812 =========
1813 */
1814 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
1815 // For example, ^2Dresk returns a length of 5
1816 void VM_strlennocol(void)
1817 {
1818         const char *szString;
1819         size_t nCnt;
1820         int nPos;
1821         int bFinished;
1822                 nPos = 0;
1823                 nCnt = 0;
1824                 bFinished = 0;
1825
1826         VM_SAFEPARMCOUNT(1,VM_strlennocol);
1827
1828         szString = PRVM_G_STRING(OFS_PARM0);
1829
1830         while(!bFinished)
1831         { // Count Characters
1832                 // SV_BroadcastPrintf("Position '%d'; Character '%c'; Length '%d'\n", nPos, szString[nPos], nCnt);
1833
1834                 if( szString[nPos] == '\n' || szString[nPos] == '\r' || szString[nPos] <= 0)
1835                 { // String End Found
1836                         // SV_BroadcastPrintf("Found End of String at '%d'\n", nPos);
1837                         bFinished = 1;
1838                 }
1839                 else
1840                 if( szString[nPos] == STRING_COLOR_TAG)
1841                 { // Color Code Located
1842                         if( szString[nPos + 1] == STRING_COLOR_TAG)
1843                         { // Increment Length; Skip Color Code
1844                                 nCnt = nCnt + 1;
1845                                 nPos = nPos + 1;
1846                         }
1847                         else
1848                         if( szString[nPos + 1] >= '0' && szString[nPos + 1] <= '9' )
1849                         { // Color Code Found; Increment Position
1850                                 // SV_BroadcastPrintf("Found Color Codes at '%d'\n", nPos);
1851                                 nPos = nPos + 1;
1852                         }
1853                         else
1854                         { // Unknown Color Code; Increment Length!
1855                                 nPos = nPos + 1;
1856                                 nCnt = nCnt + 1;
1857                         }
1858                 }
1859                 else
1860                         // Increment String Length
1861                         nCnt = nCnt + 1;
1862
1863                 // Increment Position
1864                 nPos = nPos + 1;
1865         }
1866         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
1867 }
1868
1869 /*
1870 =========
1871 VM_strcat
1872
1873 string strcat(string,string,...[string])
1874 =========
1875 */
1876 //string(string s1, string s2) strcat = #115;
1877 // concatenates two strings (for example "abc", "def" would return "abcdef")
1878 // and returns as a tempstring
1879 void VM_strcat(void)
1880 {
1881         char s[VM_STRINGTEMP_LENGTH];
1882
1883         if(prog->argc < 1)
1884                 PRVM_ERROR("VM_strcat wrong parameter count (min. 1 expected ) !");
1885
1886         VM_VarString(0, s, sizeof(s));
1887         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
1888 }
1889
1890 /*
1891 =========
1892 VM_substring
1893
1894 string  substring(string s, float start, float length)
1895 =========
1896 */
1897 // string(string s, float start, float length) substring = #116;
1898 // returns a section of a string as a tempstring
1899 void VM_substring(void)
1900 {
1901         int i, start, length;
1902         const char *s;
1903         char string[VM_STRINGTEMP_LENGTH];
1904
1905         VM_SAFEPARMCOUNT(3,VM_substring);
1906
1907         s = PRVM_G_STRING(OFS_PARM0);
1908         start = (int)PRVM_G_FLOAT(OFS_PARM1);
1909         length = (int)PRVM_G_FLOAT(OFS_PARM2);
1910         for (i = 0;i < start && *s;i++, s++);
1911         for (i = 0;i < (int)sizeof(string) - 1 && *s && i < length;i++, s++)
1912                 string[i] = *s;
1913         string[i] = 0;
1914         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
1915 }
1916
1917 /*
1918 =========
1919 VM_stov
1920
1921 vector  stov(string s)
1922 =========
1923 */
1924 //vector(string s) stov = #117; // returns vector value from a string
1925 void VM_stov(void)
1926 {
1927         char string[VM_STRINGTEMP_LENGTH];
1928
1929         VM_SAFEPARMCOUNT(1,VM_stov);
1930
1931         VM_VarString(0, string, sizeof(string));
1932         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
1933 }
1934
1935 /*
1936 =========
1937 VM_strzone
1938
1939 string  strzone(string s)
1940 =========
1941 */
1942 //string(string s, ...) strzone = #118; // makes a copy of a string into the string zone and returns it, this is often used to keep around a tempstring for longer periods of time (tempstrings are replaced often)
1943 void VM_strzone(void)
1944 {
1945         char *out;
1946         char string[VM_STRINGTEMP_LENGTH];
1947         size_t alloclen;
1948
1949         VM_SAFEPARMCOUNT(1,VM_strzone);
1950
1951         VM_VarString(0, string, sizeof(string));
1952         alloclen = strlen(string) + 1;
1953         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
1954         memcpy(out, string, alloclen);
1955 }
1956
1957 /*
1958 =========
1959 VM_strunzone
1960
1961 strunzone(string s)
1962 =========
1963 */
1964 //void(string s) strunzone = #119; // removes a copy of a string from the string zone (you can not use that string again or it may crash!!!)
1965 void VM_strunzone(void)
1966 {
1967         VM_SAFEPARMCOUNT(1,VM_strunzone);
1968         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
1969 }
1970
1971 /*
1972 =========
1973 VM_command (used by client and menu)
1974
1975 clientcommand(float client, string s) (for client and menu)
1976 =========
1977 */
1978 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
1979 //this function originally written by KrimZon, made shorter by LordHavoc
1980 void VM_clcommand (void)
1981 {
1982         client_t *temp_client;
1983         int i;
1984
1985         VM_SAFEPARMCOUNT(2,VM_clcommand);
1986
1987         i = (int)PRVM_G_FLOAT(OFS_PARM0);
1988         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
1989         {
1990                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
1991                 return;
1992         }
1993
1994         temp_client = host_client;
1995         host_client = svs.clients + i;
1996         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
1997         host_client = temp_client;
1998 }
1999
2000
2001 /*
2002 =========
2003 VM_tokenize
2004
2005 float tokenize(string s)
2006 =========
2007 */
2008 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2009 //this function originally written by KrimZon, made shorter by LordHavoc
2010 //20040203: rewritten by LordHavoc (no longer uses allocations)
2011 int num_tokens = 0;
2012 int tokens[256];
2013 void VM_tokenize (void)
2014 {
2015         const char *p;
2016 #if 0
2017         size_t pos = 0;
2018         char tokenbuf[MAX_INPUTLINE];
2019         size_t tokenlen;
2020 #endif
2021
2022         VM_SAFEPARMCOUNT(1,VM_tokenize);
2023
2024         p = PRVM_G_STRING(OFS_PARM0);
2025
2026         num_tokens = 0;
2027         while(COM_ParseToken(&p, false))
2028         {
2029                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2030                         break;
2031 #if 0
2032                 tokenlen = strlen(com_token) + 1;
2033                 if (pos + tokenlen > sizeof(tokenbuf))
2034                         break;
2035                 tokens[num_tokens++] = PRVM_SetEngineString(tokenbuf + pos);
2036                 memcpy(tokenbuf + pos, com_token, tokenlen);
2037                 pos += tokenlen;
2038 #else
2039                 tokens[num_tokens++] = PRVM_SetTempString(com_token);
2040 #endif
2041         }
2042
2043         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2044 }
2045
2046 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2047 //this function originally written by KrimZon, made shorter by LordHavoc
2048 void VM_argv (void)
2049 {
2050         int token_num;
2051
2052         VM_SAFEPARMCOUNT(1,VM_argv);
2053
2054         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2055
2056         if (token_num >= 0 && token_num < num_tokens)
2057                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2058         else
2059                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2060 }
2061
2062 /*
2063 //void(entity e, entity tagentity, string tagname) setattachment = #443; // attachs e to a tag on tagentity (note: use "" to attach to entity origin/angles instead of a tag)
2064 void PF_setattachment (void)
2065 {
2066         prvm_edict_t *e = PRVM_G_EDICT(OFS_PARM0);
2067         prvm_edict_t *tagentity = PRVM_G_EDICT(OFS_PARM1);
2068         char *tagname = PRVM_G_STRING(OFS_PARM2);
2069         prvm_eval_t *v;
2070         int i, modelindex;
2071         model_t *model;
2072
2073         if (tagentity == NULL)
2074                 tagentity = prog->edicts;
2075
2076         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_entity);
2077         if (v)
2078                 fields.server->edict = PRVM_EDICT_TO_PROG(tagentity);
2079
2080         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_index);
2081         if (v)
2082                 fields.server->_float = 0;
2083         if (tagentity != NULL && tagentity != prog->edicts && tagname && tagname[0])
2084         {
2085                 modelindex = (int)tagentity->fields.server->modelindex;
2086                 if (modelindex >= 0 && modelindex < MAX_MODELS)
2087                 {
2088                         model = sv.models[modelindex];
2089                         if (model->data_overridetagnamesforskin && (unsigned int)tagentity->fields.server->skin < (unsigned int)model->numskins && model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].num_overridetagnames)
2090                                 for (i = 0;i < model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].num_overridetagnames;i++)
2091                                         if (!strcmp(tagname, model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].data_overridetagnames[i].name))
2092                                                 fields.server->_float = i + 1;
2093                         // FIXME: use a model function to get tag info (need to handle skeletal)
2094                         if (fields.server->_float == 0 && model->num_tags)
2095                                 for (i = 0;i < model->num_tags;i++)
2096                                         if (!strcmp(tagname, model->data_tags[i].name))
2097                                                 fields.server->_float = i + 1;
2098                         if (fields.server->_float == 0)
2099                                 Con_DPrintf("setattachment(edict %i, edict %i, string \"%s\"): tried to find tag named \"%s\" on entity %i (model \"%s\") but could not find it\n", PRVM_NUM_FOR_EDICT(e), PRVM_NUM_FOR_EDICT(tagentity), tagname, tagname, PRVM_NUM_FOR_EDICT(tagentity), model->name);
2100                 }
2101                 else
2102                         Con_DPrintf("setattachment(edict %i, edict %i, string \"%s\"): tried to find tag named \"%s\" on entity %i but it has no model\n", PRVM_NUM_FOR_EDICT(e), PRVM_NUM_FOR_EDICT(tagentity), tagname, tagname, PRVM_NUM_FOR_EDICT(tagentity));
2103         }
2104 }*/
2105
2106 /*
2107 =========
2108 VM_isserver
2109
2110 float   isserver()
2111 =========
2112 */
2113 void VM_isserver(void)
2114 {
2115         VM_SAFEPARMCOUNT(0,VM_serverstate);
2116
2117         PRVM_G_FLOAT(OFS_RETURN) = sv.active;
2118 }
2119
2120 /*
2121 =========
2122 VM_clientcount
2123
2124 float   clientcount()
2125 =========
2126 */
2127 void VM_clientcount(void)
2128 {
2129         VM_SAFEPARMCOUNT(0,VM_clientcount);
2130
2131         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2132 }
2133
2134 /*
2135 =========
2136 VM_clientstate
2137
2138 float   clientstate()
2139 =========
2140 */
2141 void VM_clientstate(void)
2142 {
2143         VM_SAFEPARMCOUNT(0,VM_clientstate);
2144
2145         PRVM_G_FLOAT(OFS_RETURN) = cls.state;
2146 }
2147
2148 /*
2149 =========
2150 VM_getostype
2151
2152 float   getostype(void)
2153 =========
2154 */ // not used at the moment -> not included in the common list
2155 void VM_getostype(void)
2156 {
2157         VM_SAFEPARMCOUNT(0,VM_getostype);
2158
2159         /*
2160         OS_WINDOWS
2161         OS_LINUX
2162         OS_MAC - not supported
2163         */
2164
2165 #ifdef WIN32
2166         PRVM_G_FLOAT(OFS_RETURN) = 0;
2167 #elif defined(MACOSX)
2168         PRVM_G_FLOAT(OFS_RETURN) = 2;
2169 #else
2170         PRVM_G_FLOAT(OFS_RETURN) = 1;
2171 #endif
2172 }
2173
2174 /*
2175 =========
2176 VM_getmousepos
2177
2178 vector  getmousepos()
2179 =========
2180 */
2181 void VM_getmousepos(void)
2182 {
2183
2184         VM_SAFEPARMCOUNT(0,VM_getmousepos);
2185
2186         PRVM_G_VECTOR(OFS_RETURN)[0] = in_mouse_x * vid_conwidth.integer / vid.width;
2187         PRVM_G_VECTOR(OFS_RETURN)[1] = in_mouse_y * vid_conheight.integer / vid.height;
2188         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2189 }
2190
2191 /*
2192 =========
2193 VM_gettime
2194
2195 float   gettime(void)
2196 =========
2197 */
2198 void VM_gettime(void)
2199 {
2200         VM_SAFEPARMCOUNT(0,VM_gettime);
2201
2202         PRVM_G_FLOAT(OFS_RETURN) = (float) *prog->time;
2203 }
2204
2205 /*
2206 =========
2207 VM_loadfromdata
2208
2209 loadfromdata(string data)
2210 =========
2211 */
2212 void VM_loadfromdata(void)
2213 {
2214         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2215
2216         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2217 }
2218
2219 /*
2220 ========================
2221 VM_parseentitydata
2222
2223 parseentitydata(entity ent, string data)
2224 ========================
2225 */
2226 void VM_parseentitydata(void)
2227 {
2228         prvm_edict_t *ent;
2229         const char *data;
2230
2231         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2232
2233     // get edict and test it
2234         ent = PRVM_G_EDICT(OFS_PARM0);
2235         if (ent->priv.required->free)
2236                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2237
2238         data = PRVM_G_STRING(OFS_PARM1);
2239
2240     // parse the opening brace
2241         if (!COM_ParseTokenConsole(&data) || com_token[0] != '{' )
2242                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2243
2244         PRVM_ED_ParseEdict (data, ent);
2245 }
2246
2247 /*
2248 =========
2249 VM_loadfromfile
2250
2251 loadfromfile(string file)
2252 =========
2253 */
2254 void VM_loadfromfile(void)
2255 {
2256         const char *filename;
2257         char *data;
2258
2259         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
2260
2261         filename = PRVM_G_STRING(OFS_PARM0);
2262         if (FS_CheckNastyPath(filename, false))
2263         {
2264                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2265                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
2266                 return;
2267         }
2268
2269         // not conform with VM_fopen
2270         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
2271         if (data == NULL)
2272                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2273
2274         PRVM_ED_LoadFromFile(data);
2275
2276         if(data)
2277                 Mem_Free(data);
2278 }
2279
2280
2281 /*
2282 =========
2283 VM_modulo
2284
2285 float   mod(float val, float m)
2286 =========
2287 */
2288 void VM_modulo(void)
2289 {
2290         int val, m;
2291         VM_SAFEPARMCOUNT(2,VM_module);
2292
2293         val = (int) PRVM_G_FLOAT(OFS_PARM0);
2294         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
2295
2296         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
2297 }
2298
2299 void VM_Search_Init(void)
2300 {
2301         int i;
2302         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
2303                 prog->opensearches[i] = NULL;
2304 }
2305
2306 void VM_Search_Reset(void)
2307 {
2308         int i;
2309         // reset the fssearch list
2310         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
2311         {
2312                 if(prog->opensearches[i])
2313                         FS_FreeSearch(prog->opensearches[i]);
2314                 prog->opensearches[i] = NULL;
2315         }
2316 }
2317
2318 /*
2319 =========
2320 VM_search_begin
2321
2322 float search_begin(string pattern, float caseinsensitive, float quiet)
2323 =========
2324 */
2325 void VM_search_begin(void)
2326 {
2327         int handle;
2328         const char *pattern;
2329         int caseinsens, quiet;
2330
2331         VM_SAFEPARMCOUNT(3, VM_search_begin);
2332
2333         pattern = PRVM_G_STRING(OFS_PARM0);
2334
2335         VM_CheckEmptyString(pattern);
2336
2337         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
2338         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
2339
2340         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
2341                 if(!prog->opensearches[handle])
2342                         break;
2343
2344         if(handle >= PRVM_MAX_OPENSEARCHES)
2345         {
2346                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2347                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
2348                 return;
2349         }
2350
2351         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
2352                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2353         else
2354                 PRVM_G_FLOAT(OFS_RETURN) = handle;
2355 }
2356
2357 /*
2358 =========
2359 VM_search_end
2360
2361 void    search_end(float handle)
2362 =========
2363 */
2364 void VM_search_end(void)
2365 {
2366         int handle;
2367         VM_SAFEPARMCOUNT(1, VM_search_end);
2368
2369         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2370
2371         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2372         {
2373                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
2374                 return;
2375         }
2376         if(prog->opensearches[handle] == NULL)
2377         {
2378                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
2379                 return;
2380         }
2381
2382         FS_FreeSearch(prog->opensearches[handle]);
2383         prog->opensearches[handle] = NULL;
2384 }
2385
2386 /*
2387 =========
2388 VM_search_getsize
2389
2390 float   search_getsize(float handle)
2391 =========
2392 */
2393 void VM_search_getsize(void)
2394 {
2395         int handle;
2396         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
2397
2398         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2399
2400         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2401         {
2402                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
2403                 return;
2404         }
2405         if(prog->opensearches[handle] == NULL)
2406         {
2407                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
2408                 return;
2409         }
2410
2411         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
2412 }
2413
2414 /*
2415 =========
2416 VM_search_getfilename
2417
2418 string  search_getfilename(float handle, float num)
2419 =========
2420 */
2421 void VM_search_getfilename(void)
2422 {
2423         int handle, filenum;
2424         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
2425
2426         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2427         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
2428
2429         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2430         {
2431                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
2432                 return;
2433         }
2434         if(prog->opensearches[handle] == NULL)
2435         {
2436                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
2437                 return;
2438         }
2439         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
2440         {
2441                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
2442                 return;
2443         }
2444
2445         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog->opensearches[handle]->filenames[filenum]);
2446 }
2447
2448 /*
2449 =========
2450 VM_chr
2451
2452 string  chr(float ascii)
2453 =========
2454 */
2455 void VM_chr(void)
2456 {
2457         char tmp[2];
2458         VM_SAFEPARMCOUNT(1, VM_chr);
2459
2460         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
2461         tmp[1] = 0;
2462
2463         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
2464 }
2465
2466 //=============================================================================
2467 // Draw builtins (client & menu)
2468
2469 /*
2470 =========
2471 VM_iscachedpic
2472
2473 float   iscachedpic(string pic)
2474 =========
2475 */
2476 void VM_iscachedpic(void)
2477 {
2478         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
2479
2480         // drawq hasnt such a function, thus always return true
2481         PRVM_G_FLOAT(OFS_RETURN) = false;
2482 }
2483
2484 /*
2485 =========
2486 VM_precache_pic
2487
2488 string  precache_pic(string pic)
2489 =========
2490 */
2491 void VM_precache_pic(void)
2492 {
2493         const char      *s;
2494
2495         VM_SAFEPARMCOUNT(1, VM_precache_pic);
2496
2497         s = PRVM_G_STRING(OFS_PARM0);
2498         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
2499         VM_CheckEmptyString (s);
2500
2501         // AK Draw_CachePic is supposed to always return a valid pointer
2502         if( Draw_CachePic(s, false)->tex == r_texture_notexture )
2503                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2504 }
2505
2506 /*
2507 =========
2508 VM_freepic
2509
2510 freepic(string s)
2511 =========
2512 */
2513 void VM_freepic(void)
2514 {
2515         const char *s;
2516
2517         VM_SAFEPARMCOUNT(1,VM_freepic);
2518
2519         s = PRVM_G_STRING(OFS_PARM0);
2520         VM_CheckEmptyString (s);
2521
2522         Draw_FreePic(s);
2523 }
2524
2525 /*
2526 =========
2527 VM_drawcharacter
2528
2529 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
2530 =========
2531 */
2532 void VM_drawcharacter(void)
2533 {
2534         float *pos,*scale,*rgb;
2535         char   character;
2536         int flag;
2537         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
2538
2539         character = (char) PRVM_G_FLOAT(OFS_PARM1);
2540         if(character == 0)
2541         {
2542                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2543                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
2544                 return;
2545         }
2546
2547         pos = PRVM_G_VECTOR(OFS_PARM0);
2548         scale = PRVM_G_VECTOR(OFS_PARM2);
2549         rgb = PRVM_G_VECTOR(OFS_PARM3);
2550         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2551
2552         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2553         {
2554                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2555                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2556                 return;
2557         }
2558
2559         if(pos[2] || scale[2])
2560                 Con_Printf("VM_drawcharacter: z value%c from %s discarded\n",(pos[2] && scale[2]) ? 's' : 0,((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
2561
2562         if(!scale[0] || !scale[1])
2563         {
2564                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2565                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2566                 return;
2567         }
2568
2569         DrawQ_String (pos[0], pos[1], &character, 1, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2570         PRVM_G_FLOAT(OFS_RETURN) = 1;
2571 }
2572
2573 /*
2574 =========
2575 VM_drawstring
2576
2577 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
2578 =========
2579 */
2580 void VM_drawstring(void)
2581 {
2582         float *pos,*scale,*rgb;
2583         const char  *string;
2584         int flag;
2585         VM_SAFEPARMCOUNT(6,VM_drawstring);
2586
2587         string = PRVM_G_STRING(OFS_PARM1);
2588         pos = PRVM_G_VECTOR(OFS_PARM0);
2589         scale = PRVM_G_VECTOR(OFS_PARM2);
2590         rgb = PRVM_G_VECTOR(OFS_PARM3);
2591         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2592
2593         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2594         {
2595                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2596                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2597                 return;
2598         }
2599
2600         if(!scale[0] || !scale[1])
2601         {
2602                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2603                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2604                 return;
2605         }
2606
2607         if(pos[2] || scale[2])
2608                 Con_Printf("VM_drawstring: z value%s from %s discarded\n",(pos[2] && scale[2]) ? "s" : " ",((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
2609
2610         DrawQ_String (pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2611         PRVM_G_FLOAT(OFS_RETURN) = 1;
2612 }
2613 /*
2614 =========
2615 VM_drawpic
2616
2617 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
2618 =========
2619 */
2620 void VM_drawpic(void)
2621 {
2622         const char *picname;
2623         float *size, *pos, *rgb;
2624         int flag;
2625
2626         VM_SAFEPARMCOUNT(6,VM_drawpic);
2627
2628         picname = PRVM_G_STRING(OFS_PARM1);
2629         VM_CheckEmptyString (picname);
2630
2631         // is pic cached ? no function yet for that
2632         if(!1)
2633         {
2634                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2635                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
2636                 return;
2637         }
2638
2639         pos = PRVM_G_VECTOR(OFS_PARM0);
2640         size = PRVM_G_VECTOR(OFS_PARM2);
2641         rgb = PRVM_G_VECTOR(OFS_PARM3);
2642         flag = (int) PRVM_G_FLOAT(OFS_PARM5);
2643
2644         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2645         {
2646                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2647                 VM_Warning("VM_drawpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2648                 return;
2649         }
2650
2651         if(pos[2] || size[2])
2652                 Con_Printf("VM_drawpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
2653
2654         DrawQ_Pic(pos[0], pos[1], Draw_CachePic(picname, true), size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2655         PRVM_G_FLOAT(OFS_RETURN) = 1;
2656 }
2657
2658 /*
2659 =========
2660 VM_drawfill
2661
2662 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
2663 =========
2664 */
2665 void VM_drawfill(void)
2666 {
2667         float *size, *pos, *rgb;
2668         int flag;
2669
2670         VM_SAFEPARMCOUNT(5,VM_drawfill);
2671
2672
2673         pos = PRVM_G_VECTOR(OFS_PARM0);
2674         size = PRVM_G_VECTOR(OFS_PARM1);
2675         rgb = PRVM_G_VECTOR(OFS_PARM2);
2676         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
2677
2678         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2679         {
2680                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2681                 VM_Warning("VM_drawfill: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2682                 return;
2683         }
2684
2685         if(pos[2] || size[2])
2686                 Con_Printf("VM_drawfill: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
2687
2688         DrawQ_Pic(pos[0], pos[1], NULL, size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
2689         PRVM_G_FLOAT(OFS_RETURN) = 1;
2690 }
2691
2692 /*
2693 =========
2694 VM_drawsetcliparea
2695
2696 drawsetcliparea(float x, float y, float width, float height)
2697 =========
2698 */
2699 void VM_drawsetcliparea(void)
2700 {
2701         float x,y,w,h;
2702         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
2703
2704         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
2705         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
2706         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
2707         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
2708
2709         DrawQ_SetClipArea(x, y, w, h);
2710 }
2711
2712 /*
2713 =========
2714 VM_drawresetcliparea
2715
2716 drawresetcliparea()
2717 =========
2718 */
2719 void VM_drawresetcliparea(void)
2720 {
2721         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
2722
2723         DrawQ_ResetClipArea();
2724 }
2725
2726 /*
2727 =========
2728 VM_getimagesize
2729
2730 vector  getimagesize(string pic)
2731 =========
2732 */
2733 void VM_getimagesize(void)
2734 {
2735         const char *p;
2736         cachepic_t *pic;
2737
2738         VM_SAFEPARMCOUNT(1,VM_getimagesize);
2739
2740         p = PRVM_G_STRING(OFS_PARM0);
2741         VM_CheckEmptyString (p);
2742
2743         pic = Draw_CachePic (p, false);
2744
2745         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
2746         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
2747         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2748 }
2749
2750 /*
2751 =========
2752 VM_keynumtostring
2753
2754 string keynumtostring(float keynum)
2755 =========
2756 */
2757 void VM_keynumtostring (void)
2758 {
2759         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
2760
2761         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0)));
2762 }
2763
2764 /*
2765 =========
2766 VM_stringtokeynum
2767
2768 float stringtokeynum(string key)
2769 =========
2770 */
2771 void VM_stringtokeynum (void)
2772 {
2773         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
2774
2775         PRVM_G_INT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
2776 }
2777
2778 // CL_Video interface functions
2779
2780 /*
2781 ========================
2782 VM_cin_open
2783
2784 float cin_open(string file, string name)
2785 ========================
2786 */
2787 void VM_cin_open( void )
2788 {
2789         const char *file;
2790         const char *name;
2791
2792         VM_SAFEPARMCOUNT( 2, VM_cin_open );
2793
2794         file = PRVM_G_STRING( OFS_PARM0 );
2795         name = PRVM_G_STRING( OFS_PARM1 );
2796
2797         VM_CheckEmptyString( file );
2798     VM_CheckEmptyString( name );
2799
2800         if( CL_OpenVideo( file, name, MENUOWNER ) )
2801                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
2802         else
2803                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2804 }
2805
2806 /*
2807 ========================
2808 VM_cin_close
2809
2810 void cin_close(string name)
2811 ========================
2812 */
2813 void VM_cin_close( void )
2814 {
2815         const char *name;
2816
2817         VM_SAFEPARMCOUNT( 1, VM_cin_close );
2818
2819         name = PRVM_G_STRING( OFS_PARM0 );
2820         VM_CheckEmptyString( name );
2821
2822         CL_CloseVideo( CL_GetVideoByName( name ) );
2823 }
2824
2825 /*
2826 ========================
2827 VM_cin_setstate
2828 void cin_setstate(string name, float type)
2829 ========================
2830 */
2831 void VM_cin_setstate( void )
2832 {
2833         const char *name;
2834         clvideostate_t  state;
2835         clvideo_t               *video;
2836
2837         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
2838
2839         name = PRVM_G_STRING( OFS_PARM0 );
2840         VM_CheckEmptyString( name );
2841
2842         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
2843
2844         video = CL_GetVideoByName( name );
2845         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
2846                 CL_SetVideoState( video, state );
2847 }
2848
2849 /*
2850 ========================
2851 VM_cin_getstate
2852
2853 float cin_getstate(string name)
2854 ========================
2855 */
2856 void VM_cin_getstate( void )
2857 {
2858         const char *name;
2859         clvideo_t               *video;
2860
2861         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
2862
2863         name = PRVM_G_STRING( OFS_PARM0 );
2864         VM_CheckEmptyString( name );
2865
2866         video = CL_GetVideoByName( name );
2867         if( video )
2868                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
2869         else
2870                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2871 }
2872
2873 /*
2874 ========================
2875 VM_cin_restart
2876
2877 void cin_restart(string name)
2878 ========================
2879 */
2880 void VM_cin_restart( void )
2881 {
2882         const char *name;
2883         clvideo_t               *video;
2884
2885         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
2886
2887         name = PRVM_G_STRING( OFS_PARM0 );
2888         VM_CheckEmptyString( name );
2889
2890         video = CL_GetVideoByName( name );
2891         if( video )
2892                 CL_RestartVideo( video );
2893 }
2894
2895 /*
2896 ==============
2897 VM_vectorvectors
2898
2899 Writes new values for v_forward, v_up, and v_right based on the given forward vector
2900 vectorvectors(vector, vector)
2901 ==============
2902 */
2903 void VM_vectorvectors (void)
2904 {
2905         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), prog->globals.server->v_forward);
2906         VectorVectors(prog->globals.server->v_forward, prog->globals.server->v_right, prog->globals.server->v_up);
2907 }
2908
2909 /*
2910 ========================
2911 VM_drawline
2912
2913 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
2914 ========================
2915 */
2916 void VM_drawline (void)
2917 {
2918         float   *c1, *c2, *rgb;
2919         float   alpha, width;
2920         unsigned char   flags;
2921
2922         VM_SAFEPARMCOUNT(6, VM_drawline);
2923         width   = PRVM_G_FLOAT(OFS_PARM0);
2924         c1              = PRVM_G_VECTOR(OFS_PARM1);
2925         c2              = PRVM_G_VECTOR(OFS_PARM2);
2926         rgb             = PRVM_G_VECTOR(OFS_PARM3);
2927         alpha   = PRVM_G_FLOAT(OFS_PARM4);
2928         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
2929         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
2930 }
2931
2932 //====================
2933 //QC POLYGON functions
2934 //====================
2935
2936 typedef struct
2937 {
2938         rtexture_t              *tex;
2939         float                   data[36];       //[515]: enough for polygons
2940         unsigned char                   flags;  //[515]: + VM_POLYGON_2D and VM_POLYGON_FL4V flags
2941 }vm_polygon_t;
2942
2943 //static float                  vm_polygon_linewidth = 1;
2944 static mempool_t                *vm_polygons_pool = NULL;
2945 static unsigned char                    vm_current_vertices = 0;
2946 static qboolean                 vm_polygons_initialized = false;
2947 static vm_polygon_t             *vm_polygons = NULL;
2948 static unsigned long    vm_polygons_num = 0, vm_drawpolygons_num = 0;   //[515]: ok long on 64bit ?
2949 static qboolean                 vm_polygonbegin = false;        //[515]: for "no-crap-on-the-screen" check
2950 #define VM_DEFPOLYNUM 64        //[515]: enough for default ?
2951
2952 #define VM_POLYGON_FL3V         16      //more than 2 vertices (used only for lines)
2953 #define VM_POLYGON_FLLINES      32
2954 #define VM_POLYGON_FL2D         64
2955 #define VM_POLYGON_FL4V         128     //4 vertices
2956
2957 void VM_InitPolygons (void)
2958 {
2959         vm_polygons_pool = Mem_AllocPool("VMPOLY", 0, NULL);
2960         vm_polygons = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2961         memset(vm_polygons, 0, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2962         vm_polygons_num = VM_DEFPOLYNUM;
2963         vm_drawpolygons_num = 0;
2964         vm_polygonbegin = false;
2965         vm_polygons_initialized = true;
2966 }
2967
2968 void VM_DrawPolygonCallback (const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2969 {
2970         int surfacelistindex;
2971         // LordHavoc: FIXME: this is stupid code
2972         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
2973         {
2974                 const vm_polygon_t      *p = &vm_polygons[surfacelist[surfacelistindex]];
2975                 int                                     flags = p->flags & 0x0f;
2976
2977                 if(flags == DRAWFLAG_ADDITIVE)
2978                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2979                 else if(flags == DRAWFLAG_MODULATE)
2980                         GL_BlendFunc(GL_DST_COLOR, GL_ZERO);
2981                 else if(flags == DRAWFLAG_2XMODULATE)
2982                         GL_BlendFunc(GL_DST_COLOR,GL_SRC_COLOR);
2983                 else
2984                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2985
2986                 R_Mesh_TexBind(0, R_GetTexture(p->tex));
2987
2988                 CHECKGLERROR
2989                 //[515]: is speed is max ?
2990                 if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
2991                 {
2992                         qglLineWidth(p->data[13]);CHECKGLERROR
2993                         qglBegin(GL_LINE_LOOP);
2994                                 qglTexCoord1f   (p->data[12]);
2995                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
2996                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
2997
2998                                 qglTexCoord1f   (p->data[14]);
2999                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
3000                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
3001
3002                                 if(p->flags & VM_POLYGON_FL3V)
3003                                 {
3004                                         qglTexCoord1f   (p->data[16]);
3005                                         qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
3006                                         qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
3007
3008                                         if(p->flags & VM_POLYGON_FL4V)
3009                                         {
3010                                                 qglTexCoord1f   (p->data[18]);
3011                                                 qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
3012                                                 qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
3013                                         }
3014                                 }
3015                         qglEnd();
3016                         CHECKGLERROR
3017                 }
3018                 else
3019                 {
3020                         qglBegin(GL_POLYGON);
3021                                 qglTexCoord2f   (p->data[12], p->data[13]);
3022                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
3023                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
3024
3025                                 qglTexCoord2f   (p->data[14], p->data[15]);
3026                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
3027                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
3028
3029                                 qglTexCoord2f   (p->data[16], p->data[17]);
3030                                 qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
3031                                 qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
3032
3033                                 if(p->flags & VM_POLYGON_FL4V)
3034                                 {
3035                                         qglTexCoord2f   (p->data[18], p->data[19]);
3036                                         qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
3037                                         qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
3038                                 }
3039                         qglEnd();
3040                         CHECKGLERROR
3041                 }
3042         }
3043 }
3044
3045 void VM_AddPolygonTo2DScene (vm_polygon_t *p)
3046 {
3047         drawqueuemesh_t mesh;
3048         static int              picelements[6] = {0, 1, 2, 0, 2, 3};
3049
3050         mesh.texture = p->tex;
3051         mesh.data_element3i = picelements;
3052         mesh.data_vertex3f = p->data;
3053         mesh.data_texcoord2f = p->data + 12;
3054         mesh.data_color4f = p->data + 20;
3055         if(p->flags & VM_POLYGON_FL4V)
3056         {
3057                 mesh.num_vertices = 4;
3058                 mesh.num_triangles = 2;
3059         }
3060         else
3061         {
3062                 mesh.num_vertices = 3;
3063                 mesh.num_triangles = 1;
3064         }
3065         if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
3066                 DrawQ_LineLoop (&mesh, (p->flags&0x0f));
3067         else
3068                 DrawQ_Mesh (&mesh, (p->flags&0x0f));
3069 }
3070
3071 //void(string texturename, float flag, float 2d, float lines) R_BeginPolygon
3072 void VM_R_PolygonBegin (void)
3073 {
3074         vm_polygon_t    *p;
3075         const char              *picname;
3076         if(prog->argc < 2)
3077                 VM_SAFEPARMCOUNT(2, VM_R_PolygonBegin);
3078
3079         if(!vm_polygons_initialized)
3080                 VM_InitPolygons();
3081         if(vm_polygonbegin)
3082         {
3083                 VM_Warning("VM_R_PolygonBegin: called twice without VM_R_PolygonEnd after first\n");
3084                 return;
3085         }
3086         if(vm_drawpolygons_num >= vm_polygons_num)
3087         {
3088                 p = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3089                 memset(p, 0, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3090                 memcpy(p, vm_polygons, vm_polygons_num * sizeof(vm_polygon_t));
3091                 Mem_Free(vm_polygons);
3092                 vm_polygons = p;
3093                 vm_polygons_num *= 2;
3094         }
3095         p = &vm_polygons[vm_drawpolygons_num];
3096         picname = PRVM_G_STRING(OFS_PARM0);
3097         if(picname[0])
3098                 p->tex = Draw_CachePic(picname, true)->tex;
3099         else
3100                 p->tex = r_texture_white;
3101         p->flags = (unsigned char)PRVM_G_FLOAT(OFS_PARM1);
3102         vm_current_vertices = 0;
3103         vm_polygonbegin = true;
3104         if(prog->argc >= 3)
3105         {
3106                 if(PRVM_G_FLOAT(OFS_PARM2))
3107                         p->flags |= VM_POLYGON_FL2D;
3108                 if(prog->argc >= 4 && PRVM_G_FLOAT(OFS_PARM3))
3109                 {
3110                         p->data[13] = PRVM_G_FLOAT(OFS_PARM3);  //[515]: linewidth
3111                         p->flags |= VM_POLYGON_FLLINES;
3112                 }
3113         }
3114 }
3115
3116 //void(vector org, vector texcoords, vector rgb, float alpha) R_PolygonVertex
3117 void VM_R_PolygonVertex (void)
3118 {
3119         float                   *coords, *tx, *rgb, alpha;
3120         vm_polygon_t    *p;
3121         VM_SAFEPARMCOUNT(4, VM_R_PolygonVertex);
3122
3123         if(!vm_polygonbegin)
3124         {
3125                 VM_Warning("VM_R_PolygonVertex: VM_R_PolygonBegin wasn't called\n");
3126                 return;
3127         }
3128         coords  = PRVM_G_VECTOR(OFS_PARM0);
3129         tx              = PRVM_G_VECTOR(OFS_PARM1);
3130         rgb             = PRVM_G_VECTOR(OFS_PARM2);
3131         alpha = PRVM_G_FLOAT(OFS_PARM3);
3132
3133         p = &vm_polygons[vm_drawpolygons_num];
3134         if(vm_current_vertices > 4)
3135         {
3136                 VM_Warning("VM_R_PolygonVertex: may have 4 vertices max\n");
3137                 return;
3138         }
3139
3140         p->data[vm_current_vertices*3]          = coords[0];
3141         p->data[1+vm_current_vertices*3]        = coords[1];
3142         p->data[2+vm_current_vertices*3]        = coords[2];
3143
3144         p->data[12+vm_current_vertices*2]       = tx[0];
3145         if(!(p->flags & VM_POLYGON_FLLINES))
3146                 p->data[13+vm_current_vertices*2]       = tx[1];
3147
3148         p->data[20+vm_current_vertices*4]       = rgb[0];
3149         p->data[21+vm_current_vertices*4]       = rgb[1];
3150         p->data[22+vm_current_vertices*4]       = rgb[2];
3151         p->data[23+vm_current_vertices*4]       = alpha;
3152
3153         vm_current_vertices++;
3154         if(vm_current_vertices == 4)
3155                 p->flags |= VM_POLYGON_FL4V;
3156         else
3157                 if(vm_current_vertices == 3)
3158                         p->flags |= VM_POLYGON_FL3V;
3159 }
3160
3161 //void() R_EndPolygon
3162 void VM_R_PolygonEnd (void)
3163 {
3164         if(!vm_polygonbegin)
3165         {
3166                 VM_Warning("VM_R_PolygonEnd: VM_R_PolygonBegin wasn't called\n");
3167                 return;
3168         }
3169         vm_polygonbegin = false;
3170         if(vm_current_vertices > 2 || (vm_current_vertices >= 2 && vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FLLINES))
3171         {
3172                 if(vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FL2D)    //[515]: don't use qcpolygons memory if 2D
3173                         VM_AddPolygonTo2DScene(&vm_polygons[vm_drawpolygons_num]);
3174                 else
3175                         vm_drawpolygons_num++;
3176         }
3177         else
3178                 VM_Warning("VM_R_PolygonEnd: %i vertices isn't a good choice\n", vm_current_vertices);
3179 }
3180
3181 void VM_AddPolygonsToMeshQueue (void)
3182 {
3183         int i;
3184         if(!vm_drawpolygons_num)
3185                 return;
3186         R_Mesh_Matrix(&identitymatrix);
3187         GL_CullFace(GL_NONE);
3188         for(i = 0;i < (int)vm_drawpolygons_num;i++)
3189                 VM_DrawPolygonCallback(NULL, NULL, 1, &i);
3190         vm_drawpolygons_num = 0;
3191 }
3192
3193 void Debug_PolygonBegin(const char *picname, int flags, qboolean draw2d, float linewidth)
3194 {
3195         vm_polygon_t    *p;
3196
3197         if(!vm_polygons_initialized)
3198                 VM_InitPolygons();
3199         if(vm_polygonbegin)
3200         {
3201                 Con_Printf("Debug_PolygonBegin: called twice without Debug_PolygonEnd after first\n");
3202                 return;
3203         }
3204         // limit polygons to a vaguely sane amount, beyond this each one just
3205         // replaces the last one
3206         vm_drawpolygons_num = min(vm_drawpolygons_num, (1<<20)-1);
3207         if(vm_drawpolygons_num >= vm_polygons_num)
3208         {
3209                 p = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3210                 memset(p, 0, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3211                 memcpy(p, vm_polygons, vm_polygons_num * sizeof(vm_polygon_t));
3212                 Mem_Free(vm_polygons);
3213                 vm_polygons = p;
3214                 vm_polygons_num *= 2;
3215         }
3216         p = &vm_polygons[vm_drawpolygons_num];
3217         if(picname && picname[0])
3218                 p->tex = Draw_CachePic(picname, true)->tex;
3219         else
3220                 p->tex = r_texture_white;
3221         p->flags = flags;
3222         vm_current_vertices = 0;
3223         vm_polygonbegin = true;
3224         if(draw2d)
3225                 p->flags |= VM_POLYGON_FL2D;
3226         if(linewidth)
3227         {
3228                 p->data[13] = linewidth;        //[515]: linewidth
3229                 p->flags |= VM_POLYGON_FLLINES;
3230         }
3231 }
3232
3233 void Debug_PolygonVertex(float x, float y, float z, float s, float t, float r, float g, float b, float a)
3234 {
3235         vm_polygon_t    *p;
3236
3237         if(!vm_polygonbegin)
3238         {
3239                 Con_Printf("Debug_PolygonVertex: Debug_PolygonBegin wasn't called\n");
3240                 return;
3241         }
3242
3243         p = &vm_polygons[vm_drawpolygons_num];
3244         if(vm_current_vertices > 4)
3245         {
3246                 Con_Printf("Debug_PolygonVertex: may have 4 vertices max\n");
3247                 return;
3248         }
3249
3250         p->data[vm_current_vertices*3]          = x;
3251         p->data[1+vm_current_vertices*3]        = y;
3252         p->data[2+vm_current_vertices*3]        = z;
3253
3254         p->data[12+vm_current_vertices*2]       = s;
3255         if(!(p->flags & VM_POLYGON_FLLINES))
3256                 p->data[13+vm_current_vertices*2]       = t;
3257
3258         p->data[20+vm_current_vertices*4]       = r;
3259         p->data[21+vm_current_vertices*4]       = g;
3260         p->data[22+vm_current_vertices*4]       = b;
3261         p->data[23+vm_current_vertices*4]       = a;
3262
3263         vm_current_vertices++;
3264         if(vm_current_vertices == 4)
3265                 p->flags |= VM_POLYGON_FL4V;
3266         else
3267                 if(vm_current_vertices == 3)
3268                         p->flags |= VM_POLYGON_FL3V;
3269 }
3270
3271 void Debug_PolygonEnd(void)
3272 {
3273         if(!vm_polygonbegin)
3274         {
3275                 Con_Printf("Debug_PolygonEnd: Debug_PolygonBegin wasn't called\n");
3276                 return;
3277         }
3278         vm_polygonbegin = false;
3279         if(vm_current_vertices > 2 || (vm_current_vertices >= 2 && vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FLLINES))
3280         {
3281                 if(vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FL2D)    //[515]: don't use qcpolygons memory if 2D
3282                         VM_AddPolygonTo2DScene(&vm_polygons[vm_drawpolygons_num]);
3283                 else
3284                         vm_drawpolygons_num++;
3285         }
3286         else
3287                 Con_Printf("Debug_PolygonEnd: %i vertices isn't a good choice\n", vm_current_vertices);
3288 }
3289
3290
3291
3292
3293
3294 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3295 void VM_bitshift (void)
3296 {
3297         int n1, n2;
3298         VM_SAFEPARMCOUNT(2, VM_bitshift);
3299
3300         n1 = (int)fabs((int)PRVM_G_FLOAT(OFS_PARM0));
3301         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
3302         if(!n1)
3303                 PRVM_G_FLOAT(OFS_RETURN) = n1;
3304         else
3305         if(n2 < 0)
3306                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3307         else
3308                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3309 }
3310
3311 ////////////////////////////////////////
3312 // AltString functions
3313 ////////////////////////////////////////
3314
3315 /*
3316 ========================
3317 VM_altstr_count
3318
3319 float altstr_count(string)
3320 ========================
3321 */
3322 void VM_altstr_count( void )
3323 {
3324         const char *altstr, *pos;
3325         int     count;
3326
3327         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3328
3329         altstr = PRVM_G_STRING( OFS_PARM0 );
3330         //VM_CheckEmptyString( altstr );
3331
3332         for( count = 0, pos = altstr ; *pos ; pos++ ) {
3333                 if( *pos == '\\' ) {
3334                         if( !*++pos ) {
3335                                 break;
3336                         }
3337                 } else if( *pos == '\'' ) {
3338                         count++;
3339                 }
3340         }
3341
3342         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
3343 }
3344
3345 /*
3346 ========================
3347 VM_altstr_prepare
3348
3349 string altstr_prepare(string)
3350 ========================
3351 */
3352 void VM_altstr_prepare( void )
3353 {
3354         char *out;
3355         const char *instr, *in;
3356         int size;
3357         char outstr[VM_STRINGTEMP_LENGTH];
3358
3359         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3360
3361         instr = PRVM_G_STRING( OFS_PARM0 );
3362
3363         for( out = outstr, in = instr, size = sizeof(outstr) - 1 ; size && *in ; size--, in++, out++ )
3364                 if( *in == '\'' ) {
3365                         *out++ = '\\';
3366                         *out = '\'';
3367                         size--;
3368                 } else
3369                         *out = *in;
3370         *out = 0;
3371
3372         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
3373 }
3374
3375 /*
3376 ========================
3377 VM_altstr_get
3378
3379 string altstr_get(string, float)
3380 ========================
3381 */
3382 void VM_altstr_get( void )
3383 {
3384         const char *altstr, *pos;
3385         char *out;
3386         int count, size;
3387         char outstr[VM_STRINGTEMP_LENGTH];
3388
3389         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3390
3391         altstr = PRVM_G_STRING( OFS_PARM0 );
3392
3393         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3394         count = count * 2 + 1;
3395
3396         for( pos = altstr ; *pos && count ; pos++ )
3397                 if( *pos == '\\' ) {
3398                         if( !*++pos )
3399                                 break;
3400                 } else if( *pos == '\'' )
3401                         count--;
3402
3403         if( !*pos ) {
3404                 PRVM_G_INT( OFS_RETURN ) = 0;
3405                 return;
3406         }
3407
3408         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
3409                 if( *pos == '\\' ) {
3410                         if( !*++pos )
3411                                 break;
3412                         *out = *pos;
3413                         size--;
3414                 } else if( *pos == '\'' )
3415                         break;
3416                 else
3417                         *out = *pos;
3418
3419         *out = 0;
3420         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
3421 }
3422
3423 /*
3424 ========================
3425 VM_altstr_set
3426
3427 string altstr_set(string altstr, float num, string set)
3428 ========================
3429 */
3430 void VM_altstr_set( void )
3431 {
3432     int num;
3433         const char *altstr, *str;
3434         const char *in;
3435         char *out;
3436         char outstr[VM_STRINGTEMP_LENGTH];
3437
3438         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3439
3440         altstr = PRVM_G_STRING( OFS_PARM0 );
3441
3442         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3443
3444         str = PRVM_G_STRING( OFS_PARM2 );
3445
3446         out = outstr;
3447         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3448                 if( *in == '\\' ) {
3449                         if( !*++in ) {
3450                                 break;
3451                         }
3452                 } else if( *in == '\'' ) {
3453                         num--;
3454                 }
3455
3456         // copy set in
3457         for( ; *str; *out++ = *str++ );
3458         // now jump over the old content
3459         for( ; *in ; in++ )
3460                 if( *in == '\'' || (*in == '\\' && !*++in) )
3461                         break;
3462
3463         strlcpy(out, in, outstr + sizeof(outstr) - out);
3464         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
3465 }
3466
3467 /*
3468 ========================
3469 VM_altstr_ins
3470 insert after num
3471 string  altstr_ins(string altstr, float num, string set)
3472 ========================
3473 */
3474 void VM_altstr_ins(void)
3475 {
3476         int num;
3477         const char *setstr;
3478         const char *set;
3479         const char *instr;
3480         const char *in;
3481         char *out;
3482         char outstr[VM_STRINGTEMP_LENGTH];
3483
3484         in = instr = PRVM_G_STRING( OFS_PARM0 );
3485         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3486         set = setstr = PRVM_G_STRING( OFS_PARM2 );
3487
3488         out = outstr;
3489         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3490                 if( *in == '\\' ) {
3491                         if( !*++in ) {
3492                                 break;
3493                         }
3494                 } else if( *in == '\'' ) {
3495                         num--;
3496                 }
3497
3498         *out++ = '\'';
3499         for( ; *set ; *out++ = *set++ );
3500         *out++ = '\'';
3501
3502         strlcpy(out, in, outstr + sizeof(outstr) - out);
3503         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
3504 }
3505
3506
3507 ////////////////////////////////////////
3508 // BufString functions
3509 ////////////////////////////////////////
3510 //[515]: string buffers support
3511 #define MAX_QCSTR_BUFFERS 128
3512 #define MAX_QCSTR_STRINGS 1024
3513
3514 typedef struct
3515 {
3516         int             num_strings;
3517         char    *strings[MAX_QCSTR_STRINGS];
3518 }qcstrbuffer_t;
3519
3520 static qcstrbuffer_t    *qcstringbuffers[MAX_QCSTR_BUFFERS];
3521 static int                              num_qcstringbuffers;
3522 static int                              buf_sortpower;
3523
3524 #define BUFSTR_BUFFER(a) (a>=MAX_QCSTR_BUFFERS) ? NULL : (qcstringbuffers[a])
3525 #define BUFSTR_ISFREE(a) (a<MAX_QCSTR_BUFFERS&&qcstringbuffers[a]&&qcstringbuffers[a]->num_strings<=0) ? 1 : 0
3526
3527 static int BufStr_FindFreeBuffer (void)
3528 {
3529         int     i;
3530         if(num_qcstringbuffers == MAX_QCSTR_BUFFERS)
3531                 return -1;
3532         for(i=0;i<MAX_QCSTR_BUFFERS;i++)
3533                 if(!qcstringbuffers[i])
3534                 {
3535                         qcstringbuffers[i] = (qcstrbuffer_t *)Z_Malloc(sizeof(qcstrbuffer_t));
3536                         memset(qcstringbuffers[i], 0, sizeof(qcstrbuffer_t));
3537                         return i;
3538                 }
3539         return -1;
3540 }
3541
3542 static void BufStr_ClearBuffer (int index)
3543 {
3544         qcstrbuffer_t   *b = qcstringbuffers[index];
3545         int                             i;
3546
3547         if(b)
3548         {
3549                 if(b->num_strings > 0)
3550                 {
3551                         for(i=0;i<b->num_strings;i++)
3552                                 if(b->strings[i])
3553                                         Z_Free(b->strings[i]);
3554                         num_qcstringbuffers--;
3555                 }
3556                 Z_Free(qcstringbuffers[index]);
3557                 qcstringbuffers[index] = NULL;
3558         }
3559 }
3560
3561 static int BufStr_FindFreeString (qcstrbuffer_t *b)
3562 {
3563         int                             i;
3564         for(i=0;i<b->num_strings;i++)
3565                 if(!b->strings[i] || !b->strings[i][0])
3566                         return i;
3567         if(i == MAX_QCSTR_STRINGS)      return -1;
3568         else                                            return i;
3569 }
3570
3571 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3572 {
3573         const char *a, *b;
3574         a = *((const char **) in1);
3575         b = *((const char **) in2);
3576         if(!a[0])       return 1;
3577         if(!b[0])       return -1;
3578         return strncmp(a, b, buf_sortpower);
3579 }
3580
3581 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3582 {
3583         const char *a, *b;
3584         a = *((const char **) in1);
3585         b = *((const char **) in2);
3586         if(!a[0])       return 1;
3587         if(!b[0])       return -1;
3588         return strncmp(b, a, buf_sortpower);
3589 }
3590
3591 #ifdef REMOVETHIS
3592 static void VM_BufStr_Init (void)
3593 {
3594         memset(qcstringbuffers, 0, sizeof(qcstringbuffers));
3595         num_qcstringbuffers = 0;
3596 }
3597
3598 static void VM_BufStr_ShutDown (void)
3599 {
3600         int i;
3601         for(i=0;i<MAX_QCSTR_BUFFERS && num_qcstringbuffers;i++)
3602                 BufStr_ClearBuffer(i);
3603 }
3604 #endif
3605
3606 /*
3607 ========================
3608 VM_buf_create
3609 creates new buffer, and returns it's index, returns -1 if failed
3610 float buf_create(void) = #460;
3611 ========================
3612 */
3613 void VM_buf_create (void)
3614 {
3615         int i;
3616         VM_SAFEPARMCOUNT(0, VM_buf_create);
3617         i = BufStr_FindFreeBuffer();
3618         if(i >= 0)
3619                 num_qcstringbuffers++;
3620         //else
3621                 //Con_Printf("VM_buf_create: buffers overflow in %s\n", PRVM_NAME);
3622         PRVM_G_FLOAT(OFS_RETURN) = i;
3623 }
3624
3625 /*
3626 ========================
3627 VM_buf_del
3628 deletes buffer and all strings in it
3629 void buf_del(float bufhandle) = #461;
3630 ========================
3631 */
3632 void VM_buf_del (void)
3633 {
3634         VM_SAFEPARMCOUNT(1, VM_buf_del);
3635         if(BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0)))
3636                 BufStr_ClearBuffer((int)PRVM_G_FLOAT(OFS_PARM0));
3637         else
3638         {
3639                 VM_Warning("VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3640                 return;
3641         }
3642 }
3643
3644 /*
3645 ========================
3646 VM_buf_getsize
3647 how many strings are stored in buffer
3648 float buf_getsize(float bufhandle) = #462;
3649 ========================
3650 */
3651 void VM_buf_getsize (void)
3652 {
3653         qcstrbuffer_t   *b;
3654         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
3655
3656         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3657         if(!b)
3658         {
3659                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3660                 VM_Warning("VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3661                 return;
3662         }
3663         else
3664                 PRVM_G_FLOAT(OFS_RETURN) = b->num_strings;
3665 }
3666
3667 /*
3668 ========================
3669 VM_buf_copy
3670 copy all content from one buffer to another, make sure it exists
3671 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
3672 ========================
3673 */
3674 void VM_buf_copy (void)
3675 {
3676         qcstrbuffer_t   *b1, *b2;
3677         int                             i;
3678         VM_SAFEPARMCOUNT(2, VM_buf_copy);
3679
3680         b1 = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3681         if(!b1)
3682         {
3683                 VM_Warning("VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3684                 return;
3685         }
3686         i = (int)PRVM_G_FLOAT(OFS_PARM1);
3687         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
3688         {
3689                 VM_Warning("VM_buf_copy: source == destination (%i) in %s\n", i, PRVM_NAME);
3690                 return;
3691         }
3692         b2 = BUFSTR_BUFFER(i);
3693         if(!b2)
3694         {
3695                 VM_Warning("VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
3696                 return;
3697         }
3698
3699         BufStr_ClearBuffer(i);
3700         qcstringbuffers[i] = (qcstrbuffer_t *)Z_Malloc(sizeof(qcstrbuffer_t));
3701         memset(qcstringbuffers[i], 0, sizeof(qcstrbuffer_t));
3702         b2->num_strings = b1->num_strings;
3703
3704         for(i=0;i<b1->num_strings;i++)
3705                 if(b1->strings[i] && b1->strings[i][0])
3706                 {
3707                         size_t stringlen;
3708                         stringlen = strlen(b1->strings[i]) + 1;
3709                         b2->strings[i] = (char *)Z_Malloc(stringlen);
3710                         if(!b2->strings[i])
3711                         {
3712                                 VM_Warning("VM_buf_copy: not enough memory for buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
3713                                 break;
3714                         }
3715                         memcpy(b2->strings[i], b1->strings[i], stringlen);
3716                 }
3717 }
3718
3719 /*
3720 ========================
3721 VM_buf_sort
3722 sort buffer by beginnings of strings (sortpower defaults it's lenght)
3723 "backward == TRUE" means that sorting goes upside-down
3724 void buf_sort(float bufhandle, float sortpower, float backward) = #464;
3725 ========================
3726 */
3727 void VM_buf_sort (void)
3728 {
3729         qcstrbuffer_t   *b;
3730         int                             i;
3731         VM_SAFEPARMCOUNT(3, VM_buf_sort);
3732
3733         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3734         if(!b)
3735         {
3736                 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3737                 return;
3738         }
3739         if(b->num_strings <= 0)
3740         {
3741                 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3742                 return;
3743         }
3744         buf_sortpower = (int)PRVM_G_FLOAT(OFS_PARM1);
3745         if(buf_sortpower <= 0)
3746                 buf_sortpower = 99999999;
3747
3748         if(!PRVM_G_FLOAT(OFS_PARM2))
3749                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsUP);
3750         else
3751                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
3752
3753         for(i=b->num_strings-1;i>=0;i--)        //[515]: delete empty lines
3754                 if(b->strings)
3755                 {
3756                         if(b->strings[i][0])
3757                                 break;
3758                         else
3759                         {
3760                                 Z_Free(b->strings[i]);
3761                                 --b->num_strings;
3762                                 b->strings[i] = NULL;
3763                         }
3764                 }
3765                 else
3766                         --b->num_strings;
3767 }
3768
3769 /*
3770 ========================
3771 VM_buf_implode
3772 concantenates all buffer string into one with "glue" separator and returns it as tempstring
3773 string buf_implode(float bufhandle, string glue) = #465;
3774 ========================
3775 */
3776 void VM_buf_implode (void)
3777 {
3778         qcstrbuffer_t   *b;
3779         char                    k[VM_STRINGTEMP_LENGTH];
3780         const char              *sep;
3781         int                             i;
3782         size_t                  l;
3783         VM_SAFEPARMCOUNT(2, VM_buf_implode);
3784
3785         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3786         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3787         if(!b)
3788         {
3789                 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3790                 return;
3791         }
3792         if(!b->num_strings)
3793                 return;
3794         sep = PRVM_G_STRING(OFS_PARM1);
3795         k[0] = 0;
3796         for(l=i=0;i<b->num_strings;i++)
3797                 if(b->strings[i])
3798                 {
3799                         l += (i > 0 ? strlen(sep) : 0) + strlen(b->strings[i]);
3800                         if (l >= sizeof(k) - 1)
3801                                 break;
3802                         strlcat(k, sep, sizeof(k));
3803                         strlcat(k, b->strings[i], sizeof(k));
3804                 }
3805         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(k);
3806 }
3807
3808 /*
3809 ========================
3810 VM_bufstr_get
3811 get a string from buffer, returns tempstring, dont str_unzone it!
3812 string bufstr_get(float bufhandle, float string_index) = #465;
3813 ========================
3814 */
3815 void VM_bufstr_get (void)
3816 {
3817         qcstrbuffer_t   *b;
3818         int                             strindex;
3819         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
3820
3821         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3822         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3823         if(!b)
3824         {
3825                 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3826                 return;
3827         }
3828         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3829         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3830         {
3831                 VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3832                 return;
3833         }
3834         if(b->num_strings <= strindex)
3835                 return;
3836         if(b->strings[strindex])
3837                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(b->strings[strindex]);
3838 }
3839
3840 /*
3841 ========================
3842 VM_bufstr_set
3843 copies a string into selected slot of buffer
3844 void bufstr_set(float bufhandle, float string_index, string str) = #466;
3845 ========================
3846 */
3847 void VM_bufstr_set (void)
3848 {
3849         int                             bufindex, strindex;
3850         qcstrbuffer_t   *b;
3851         const char              *news;
3852         size_t                  alloclen;
3853
3854         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
3855
3856         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3857         b = BUFSTR_BUFFER(bufindex);
3858         if(!b)
3859         {
3860                 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3861                 return;
3862         }
3863         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3864         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3865         {
3866                 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3867                 return;
3868         }
3869         news = PRVM_G_STRING(OFS_PARM2);
3870         if(b->strings[strindex])
3871                 Z_Free(b->strings[strindex]);
3872         alloclen = strlen(news) + 1;
3873         b->strings[strindex] = (char *)Z_Malloc(alloclen);
3874         memcpy(b->strings[strindex], news, alloclen);
3875 }
3876
3877 /*
3878 ========================
3879 VM_bufstr_add
3880 adds string to buffer in nearest free slot and returns it
3881 "order == TRUE" means that string will be added after last "full" slot
3882 float bufstr_add(float bufhandle, string str, float order) = #467;
3883 ========================
3884 */
3885 void VM_bufstr_add (void)
3886 {
3887         int                             bufindex, order, strindex;
3888         qcstrbuffer_t   *b;
3889         const char              *string;
3890         size_t                  alloclen;
3891
3892         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
3893
3894         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3895         b = BUFSTR_BUFFER(bufindex);
3896         PRVM_G_FLOAT(OFS_RETURN) = -1;
3897         if(!b)
3898         {
3899                 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3900                 return;
3901         }
3902         string = PRVM_G_STRING(OFS_PARM1);
3903         order = (int)PRVM_G_FLOAT(OFS_PARM2);
3904         if(order)
3905                 strindex = b->num_strings;
3906         else
3907         {
3908                 strindex = BufStr_FindFreeString(b);
3909                 if(strindex < 0)
3910                 {
3911                         VM_Warning("VM_bufstr_add: buffer %i has no free string slots in %s\n", bufindex, PRVM_NAME);
3912                         return;
3913                 }
3914         }
3915
3916         while(b->num_strings <= strindex)
3917         {
3918                 if(b->num_strings == MAX_QCSTR_STRINGS)
3919                 {
3920                         VM_Warning("VM_bufstr_add: buffer %i has no free string slots in %s\n", bufindex, PRVM_NAME);
3921                         return;
3922                 }
3923                 b->strings[b->num_strings] = NULL;
3924                 b->num_strings++;
3925         }
3926         if(b->strings[strindex])
3927                 Z_Free(b->strings[strindex]);
3928         alloclen = strlen(string) + 1;
3929         b->strings[strindex] = (char *)Z_Malloc(alloclen);
3930         memcpy(b->strings[strindex], string, alloclen);
3931         PRVM_G_FLOAT(OFS_RETURN) = strindex;
3932 }
3933
3934 /*
3935 ========================
3936 VM_bufstr_free
3937 delete string from buffer
3938 void bufstr_free(float bufhandle, float string_index) = #468;
3939 ========================
3940 */
3941 void VM_bufstr_free (void)
3942 {
3943         int                             i;
3944         qcstrbuffer_t   *b;
3945         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
3946
3947         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3948         if(!b)
3949         {
3950                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3951                 return;
3952         }
3953         i = (int)PRVM_G_FLOAT(OFS_PARM1);
3954         if(i < 0 || i > MAX_QCSTR_STRINGS)
3955         {
3956                 VM_Warning("VM_bufstr_free: invalid string index %i used in %s\n", i, PRVM_NAME);
3957                 return;
3958         }
3959         if(b->strings[i])
3960                 Z_Free(b->strings[i]);
3961         b->strings[i] = NULL;
3962         if(i+1 == b->num_strings)
3963                 --b->num_strings;
3964 }
3965
3966 //=============
3967
3968 void VM_Cmd_Init(void)
3969 {
3970         // only init the stuff for the current prog
3971         VM_Files_Init();
3972         VM_Search_Init();
3973 //      VM_BufStr_Init();
3974         if(vm_polygons_initialized)
3975         {
3976                 Mem_FreePool(&vm_polygons_pool);
3977                 vm_polygons_initialized = false;
3978         }
3979 }
3980
3981 void VM_Cmd_Reset(void)
3982 {
3983         CL_PurgeOwner( MENUOWNER );
3984         VM_Search_Reset();
3985         VM_Files_CloseAll();
3986 //      VM_BufStr_ShutDown();
3987         if(vm_polygons_initialized)
3988         {
3989                 Mem_FreePool(&vm_polygons_pool);
3990                 vm_polygons_initialized = false;
3991         }
3992 }
3993