]> icculus.org git repositories - divverent/darkplaces.git/blob - prvm_cmds.c
extresponse: make svqc receive only those on the server socket, and csqc/menuqc only...
[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 "quakedef.h"
8
9 #include "prvm_cmds.h"
10 #include "libcurl.h"
11 #include <time.h>
12
13 extern cvar_t prvm_backtraceforwarnings;
14
15 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
16 void VM_Warning(const char *fmt, ...)
17 {
18         va_list argptr;
19         char msg[MAX_INPUTLINE];
20         static double recursive = -1;
21
22         va_start(argptr,fmt);
23         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
24         va_end(argptr);
25
26         Con_Print(msg);
27
28         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
29         if(prvm_backtraceforwarnings.integer && recursive != realtime) // NOTE: this compares to the time, just in case if PRVM_PrintState causes a Host_Error and keeps recursive set
30         {
31                 recursive = realtime;
32                 PRVM_PrintState();
33                 recursive = -1;
34         }
35 }
36
37
38 //============================================================================
39 // Common
40
41 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
42 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
43 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
44 // TODO: will this war ever end? [2007-01-23 LordHavoc]
45
46 void VM_CheckEmptyString (const char *s)
47 {
48         if (ISWHITESPACE(s[0]))
49                 PRVM_ERROR ("%s: Bad string", PRVM_NAME);
50 }
51
52 //============================================================================
53 //BUILT-IN FUNCTIONS
54
55 void VM_VarString(int first, char *out, int outlength)
56 {
57         int i;
58         const char *s;
59         char *outend;
60
61         outend = out + outlength - 1;
62         for (i = first;i < prog->argc && out < outend;i++)
63         {
64                 s = PRVM_G_STRING((OFS_PARM0+i*3));
65                 while (out < outend && *s)
66                         *out++ = *s++;
67         }
68         *out++ = 0;
69 }
70
71 /*
72 =================
73 VM_checkextension
74
75 returns true if the extension is supported by the server
76
77 checkextension(extensionname)
78 =================
79 */
80
81 // kind of helper function
82 static qboolean checkextension(const char *name)
83 {
84         int len;
85         char *e, *start;
86         len = (int)strlen(name);
87
88         for (e = prog->extensionstring;*e;e++)
89         {
90                 while (*e == ' ')
91                         e++;
92                 if (!*e)
93                         break;
94                 start = e;
95                 while (*e && *e != ' ')
96                         e++;
97                 if ((e - start) == len && !strncasecmp(start, name, len))
98                         return true;
99         }
100         return false;
101 }
102
103 void VM_checkextension (void)
104 {
105         VM_SAFEPARMCOUNT(1,VM_checkextension);
106
107         PRVM_G_FLOAT(OFS_RETURN) = checkextension(PRVM_G_STRING(OFS_PARM0));
108 }
109
110 /*
111 =================
112 VM_error
113
114 This is a TERMINAL error, which will kill off the entire prog.
115 Dumps self.
116
117 error(value)
118 =================
119 */
120 void VM_error (void)
121 {
122         prvm_edict_t    *ed;
123         char string[VM_STRINGTEMP_LENGTH];
124
125         VM_VarString(0, string, sizeof(string));
126         Con_Printf("======%s ERROR in %s:\n%s\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
127         if (prog->globaloffsets.self >= 0)
128         {
129                 ed = PRVM_PROG_TO_EDICT(PRVM_GLOBALFIELDVALUE(prog->globaloffsets.self)->edict);
130                 PRVM_ED_Print(ed, NULL);
131         }
132
133         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);
134 }
135
136 /*
137 =================
138 VM_objerror
139
140 Dumps out self, then an error message.  The program is aborted and self is
141 removed, but the level can continue.
142
143 objerror(value)
144 =================
145 */
146 void VM_objerror (void)
147 {
148         prvm_edict_t    *ed;
149         char string[VM_STRINGTEMP_LENGTH];
150
151         VM_VarString(0, string, sizeof(string));
152         Con_Printf("======OBJECT ERROR======\n"); // , PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
153         if (prog->globaloffsets.self >= 0)
154         {
155                 ed = PRVM_PROG_TO_EDICT(PRVM_GLOBALFIELDVALUE(prog->globaloffsets.self)->edict);
156                 PRVM_ED_Print(ed, NULL);
157
158                 PRVM_ED_Free (ed);
159         }
160         else
161                 // objerror has to display the object fields -> else call
162                 PRVM_ERROR ("VM_objecterror: self not defined !");
163         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);
164 }
165
166 /*
167 =================
168 VM_print
169
170 print to console
171
172 print(...[string])
173 =================
174 */
175 void VM_print (void)
176 {
177         char string[VM_STRINGTEMP_LENGTH];
178
179         VM_VarString(0, string, sizeof(string));
180         Con_Print(string);
181 }
182
183 /*
184 =================
185 VM_bprint
186
187 broadcast print to everyone on server
188
189 bprint(...[string])
190 =================
191 */
192 void VM_bprint (void)
193 {
194         char string[VM_STRINGTEMP_LENGTH];
195
196         if(!sv.active)
197         {
198                 VM_Warning("VM_bprint: game is not server(%s) !\n", PRVM_NAME);
199                 return;
200         }
201
202         VM_VarString(0, string, sizeof(string));
203         SV_BroadcastPrint(string);
204 }
205
206 /*
207 =================
208 VM_sprint (menu & client but only if server.active == true)
209
210 single print to a specific client
211
212 sprint(float clientnum,...[string])
213 =================
214 */
215 void VM_sprint (void)
216 {
217         client_t        *client;
218         int                     clientnum;
219         char string[VM_STRINGTEMP_LENGTH];
220
221         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
222
223         //find client for this entity
224         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
225         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
226         {
227                 VM_Warning("VM_sprint: %s: invalid client or server is not active !\n", PRVM_NAME);
228                 return;
229         }
230
231         client = svs.clients + clientnum;
232         if (!client->netconnection)
233                 return;
234
235         VM_VarString(1, string, sizeof(string));
236         MSG_WriteChar(&client->netconnection->message,svc_print);
237         MSG_WriteString(&client->netconnection->message, string);
238 }
239
240 /*
241 =================
242 VM_centerprint
243
244 single print to the screen
245
246 centerprint(value)
247 =================
248 */
249 void VM_centerprint (void)
250 {
251         char string[VM_STRINGTEMP_LENGTH];
252
253         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
254         VM_VarString(0, string, sizeof(string));
255         SCR_CenterPrint(string);
256 }
257
258 /*
259 =================
260 VM_normalize
261
262 vector normalize(vector)
263 =================
264 */
265 void VM_normalize (void)
266 {
267         float   *value1;
268         vec3_t  newvalue;
269         double  f;
270
271         VM_SAFEPARMCOUNT(1,VM_normalize);
272
273         value1 = PRVM_G_VECTOR(OFS_PARM0);
274
275         f = VectorLength2(value1);
276         if (f)
277         {
278                 f = 1.0 / sqrt(f);
279                 VectorScale(value1, f, newvalue);
280         }
281         else
282                 VectorClear(newvalue);
283
284         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
285 }
286
287 /*
288 =================
289 VM_vlen
290
291 scalar vlen(vector)
292 =================
293 */
294 void VM_vlen (void)
295 {
296         VM_SAFEPARMCOUNT(1,VM_vlen);
297         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
298 }
299
300 /*
301 =================
302 VM_vectoyaw
303
304 float vectoyaw(vector)
305 =================
306 */
307 void VM_vectoyaw (void)
308 {
309         float   *value1;
310         float   yaw;
311
312         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
313
314         value1 = PRVM_G_VECTOR(OFS_PARM0);
315
316         if (value1[1] == 0 && value1[0] == 0)
317                 yaw = 0;
318         else
319         {
320                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
321                 if (yaw < 0)
322                         yaw += 360;
323         }
324
325         PRVM_G_FLOAT(OFS_RETURN) = yaw;
326 }
327
328
329 /*
330 =================
331 VM_vectoangles
332
333 vector vectoangles(vector[, vector])
334 =================
335 */
336 void VM_vectoangles (void)
337 {
338         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
339
340         AnglesFromVectors(PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_PARM0), prog->argc >= 2 ? PRVM_G_VECTOR(OFS_PARM1) : NULL, true);
341 }
342
343 /*
344 =================
345 VM_random
346
347 Returns a number from 0<= num < 1
348
349 float random()
350 =================
351 */
352 void VM_random (void)
353 {
354         VM_SAFEPARMCOUNT(0,VM_random);
355
356         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
357 }
358
359 /*
360 =========
361 VM_localsound
362
363 localsound(string sample)
364 =========
365 */
366 void VM_localsound(void)
367 {
368         const char *s;
369
370         VM_SAFEPARMCOUNT(1,VM_localsound);
371
372         s = PRVM_G_STRING(OFS_PARM0);
373
374         if(!S_LocalSound (s))
375         {
376                 PRVM_G_FLOAT(OFS_RETURN) = -4;
377                 VM_Warning("VM_localsound: Failed to play %s for %s !\n", s, PRVM_NAME);
378                 return;
379         }
380
381         PRVM_G_FLOAT(OFS_RETURN) = 1;
382 }
383
384 /*
385 =================
386 VM_break
387
388 break()
389 =================
390 */
391 void VM_break (void)
392 {
393         PRVM_ERROR ("%s: break statement", PRVM_NAME);
394 }
395
396 //============================================================================
397
398 /*
399 =================
400 VM_localcmd
401
402 Sends text over to the client's execution buffer
403
404 [localcmd (string, ...) or]
405 cmd (string, ...)
406 =================
407 */
408 void VM_localcmd (void)
409 {
410         char string[VM_STRINGTEMP_LENGTH];
411         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
412         VM_VarString(0, string, sizeof(string));
413         Cbuf_AddText(string);
414 }
415
416 static qboolean PRVM_Cvar_ReadOk(const char *string)
417 {
418         cvar_t *cvar;
419         cvar = Cvar_FindVar(string);
420         return ((cvar) && ((cvar->flags & CVAR_PRIVATE) == 0));
421 }
422
423 /*
424 =================
425 VM_cvar
426
427 float cvar (string)
428 =================
429 */
430 void VM_cvar (void)
431 {
432         char string[VM_STRINGTEMP_LENGTH];
433         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
434         VM_VarString(0, string, sizeof(string));
435         VM_CheckEmptyString(string);
436         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(string) ? Cvar_VariableValue(string) : 0;
437 }
438
439 /*
440 =================
441 VM_cvar
442
443 float cvar_type (string)
444 float CVAR_TYPEFLAG_EXISTS = 1;
445 float CVAR_TYPEFLAG_SAVED = 2;
446 float CVAR_TYPEFLAG_PRIVATE = 4;
447 float CVAR_TYPEFLAG_ENGINE = 8;
448 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
449 float CVAR_TYPEFLAG_READONLY = 32;
450 =================
451 */
452 void VM_cvar_type (void)
453 {
454         char string[VM_STRINGTEMP_LENGTH];
455         cvar_t *cvar;
456         int ret;
457
458         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
459         VM_VarString(0, string, sizeof(string));
460         VM_CheckEmptyString(string);
461         cvar = Cvar_FindVar(string);
462
463
464         if(!cvar)
465         {
466                 PRVM_G_FLOAT(OFS_RETURN) = 0;
467                 return; // CVAR_TYPE_NONE
468         }
469
470         ret = 1; // CVAR_EXISTS
471         if(cvar->flags & CVAR_SAVE)
472                 ret |= 2; // CVAR_TYPE_SAVED
473         if(cvar->flags & CVAR_PRIVATE)
474                 ret |= 4; // CVAR_TYPE_PRIVATE
475         if(!(cvar->flags & CVAR_ALLOCATED))
476                 ret |= 8; // CVAR_TYPE_ENGINE
477         if(cvar->description != cvar_dummy_description)
478                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
479         if(cvar->flags & CVAR_READONLY)
480                 ret |= 32; // CVAR_TYPE_READONLY
481         
482         PRVM_G_FLOAT(OFS_RETURN) = ret;
483 }
484
485 /*
486 =================
487 VM_cvar_string
488
489 const string    VM_cvar_string (string, ...)
490 =================
491 */
492 void VM_cvar_string(void)
493 {
494         char string[VM_STRINGTEMP_LENGTH];
495         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
496         VM_VarString(0, string, sizeof(string));
497         VM_CheckEmptyString(string);
498         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_Cvar_ReadOk(string) ? Cvar_VariableString(string) : "");
499 }
500
501
502 /*
503 ========================
504 VM_cvar_defstring
505
506 const string    VM_cvar_defstring (string, ...)
507 ========================
508 */
509 void VM_cvar_defstring (void)
510 {
511         char string[VM_STRINGTEMP_LENGTH];
512         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
513         VM_VarString(0, string, sizeof(string));
514         VM_CheckEmptyString(string);
515         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDefString(string));
516 }
517
518 /*
519 ========================
520 VM_cvar_defstring
521
522 const string    VM_cvar_description (string, ...)
523 ========================
524 */
525 void VM_cvar_description (void)
526 {
527         char string[VM_STRINGTEMP_LENGTH];
528         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
529         VM_VarString(0, string, sizeof(string));
530         VM_CheckEmptyString(string);
531         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDescription(string));
532 }
533 /*
534 =================
535 VM_cvar_set
536
537 void cvar_set (string,string, ...)
538 =================
539 */
540 void VM_cvar_set (void)
541 {
542         const char *name;
543         char string[VM_STRINGTEMP_LENGTH];
544         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
545         VM_VarString(1, string, sizeof(string));
546         name = PRVM_G_STRING(OFS_PARM0);
547         VM_CheckEmptyString(name);
548         Cvar_Set(name, string);
549 }
550
551 /*
552 =========
553 VM_dprint
554
555 dprint(...[string])
556 =========
557 */
558 void VM_dprint (void)
559 {
560         char string[VM_STRINGTEMP_LENGTH];
561         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
562         if (developer.integer)
563         {
564                 VM_VarString(0, string, sizeof(string));
565 #if 1
566                 Con_Printf("%s", string);
567 #else
568                 Con_Printf("%s: %s", PRVM_NAME, string);
569 #endif
570         }
571 }
572
573 /*
574 =========
575 VM_ftos
576
577 string  ftos(float)
578 =========
579 */
580
581 void VM_ftos (void)
582 {
583         float v;
584         char s[128];
585
586         VM_SAFEPARMCOUNT(1, VM_ftos);
587
588         v = PRVM_G_FLOAT(OFS_PARM0);
589
590         if ((float)((int)v) == v)
591                 dpsnprintf(s, sizeof(s), "%i", (int)v);
592         else
593                 dpsnprintf(s, sizeof(s), "%f", v);
594         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
595 }
596
597 /*
598 =========
599 VM_fabs
600
601 float   fabs(float)
602 =========
603 */
604
605 void VM_fabs (void)
606 {
607         float   v;
608
609         VM_SAFEPARMCOUNT(1,VM_fabs);
610
611         v = PRVM_G_FLOAT(OFS_PARM0);
612         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
613 }
614
615 /*
616 =========
617 VM_vtos
618
619 string  vtos(vector)
620 =========
621 */
622
623 void VM_vtos (void)
624 {
625         char s[512];
626
627         VM_SAFEPARMCOUNT(1,VM_vtos);
628
629         dpsnprintf (s, sizeof(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]);
630         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
631 }
632
633 /*
634 =========
635 VM_etos
636
637 string  etos(entity)
638 =========
639 */
640
641 void VM_etos (void)
642 {
643         char s[128];
644
645         VM_SAFEPARMCOUNT(1, VM_etos);
646
647         dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
648         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
649 }
650
651 /*
652 =========
653 VM_stof
654
655 float stof(...[string])
656 =========
657 */
658 void VM_stof(void)
659 {
660         char string[VM_STRINGTEMP_LENGTH];
661         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
662         VM_VarString(0, string, sizeof(string));
663         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
664 }
665
666 /*
667 ========================
668 VM_itof
669
670 float itof(intt ent)
671 ========================
672 */
673 void VM_itof(void)
674 {
675         VM_SAFEPARMCOUNT(1, VM_itof);
676         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
677 }
678
679 /*
680 ========================
681 VM_ftoe
682
683 entity ftoe(float num)
684 ========================
685 */
686 void VM_ftoe(void)
687 {
688         int ent;
689         VM_SAFEPARMCOUNT(1, VM_ftoe);
690
691         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
692         if (ent < 0 || ent >= MAX_EDICTS || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
693                 ent = 0; // return world instead of a free or invalid entity
694
695         PRVM_G_INT(OFS_RETURN) = ent;
696 }
697
698 /*
699 ========================
700 VM_etof
701
702 float etof(entity ent)
703 ========================
704 */
705 void VM_etof(void)
706 {
707         VM_SAFEPARMCOUNT(1, VM_etof);
708         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
709 }
710
711 /*
712 =========
713 VM_strftime
714
715 string strftime(float uselocaltime, string[, string ...])
716 =========
717 */
718 void VM_strftime(void)
719 {
720         time_t t;
721 #if _MSC_VER >= 1400
722         struct tm tm;
723         int tmresult;
724 #else
725         struct tm *tm;
726 #endif
727         char fmt[VM_STRINGTEMP_LENGTH];
728         char result[VM_STRINGTEMP_LENGTH];
729         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
730         VM_VarString(1, fmt, sizeof(fmt));
731         t = time(NULL);
732 #if _MSC_VER >= 1400
733         if (PRVM_G_FLOAT(OFS_PARM0))
734                 tmresult = localtime_s(&tm, &t);
735         else
736                 tmresult = gmtime_s(&tm, &t);
737         if (!tmresult)
738 #else
739         if (PRVM_G_FLOAT(OFS_PARM0))
740                 tm = localtime(&t);
741         else
742                 tm = gmtime(&t);
743         if (!tm)
744 #endif
745         {
746                 PRVM_G_INT(OFS_RETURN) = 0;
747                 return;
748         }
749 #if _MSC_VER >= 1400
750         strftime(result, sizeof(result), fmt, &tm);
751 #else
752         strftime(result, sizeof(result), fmt, tm);
753 #endif
754         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(result);
755 }
756
757 /*
758 =========
759 VM_spawn
760
761 entity spawn()
762 =========
763 */
764
765 void VM_spawn (void)
766 {
767         prvm_edict_t    *ed;
768         VM_SAFEPARMCOUNT(0, VM_spawn);
769         prog->xfunction->builtinsprofile += 20;
770         ed = PRVM_ED_Alloc();
771         VM_RETURN_EDICT(ed);
772 }
773
774 /*
775 =========
776 VM_remove
777
778 remove(entity e)
779 =========
780 */
781
782 void VM_remove (void)
783 {
784         prvm_edict_t    *ed;
785         prog->xfunction->builtinsprofile += 20;
786
787         VM_SAFEPARMCOUNT(1, VM_remove);
788
789         ed = PRVM_G_EDICT(OFS_PARM0);
790         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
791         {
792                 if (developer.integer >= 1)
793                         VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
794         }
795         else if( ed->priv.required->free )
796         {
797                 if (developer.integer >= 1)
798                         VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
799         }
800         else
801                 PRVM_ED_Free (ed);
802 }
803
804 /*
805 =========
806 VM_find
807
808 entity  find(entity start, .string field, string match)
809 =========
810 */
811
812 void VM_find (void)
813 {
814         int             e;
815         int             f;
816         const char      *s, *t;
817         prvm_edict_t    *ed;
818
819         VM_SAFEPARMCOUNT(3,VM_find);
820
821         e = PRVM_G_EDICTNUM(OFS_PARM0);
822         f = PRVM_G_INT(OFS_PARM1);
823         s = PRVM_G_STRING(OFS_PARM2);
824
825         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
826         // expects it to find all the monsters, so we must be careful to support
827         // searching for ""
828
829         for (e++ ; e < prog->num_edicts ; e++)
830         {
831                 prog->xfunction->builtinsprofile++;
832                 ed = PRVM_EDICT_NUM(e);
833                 if (ed->priv.required->free)
834                         continue;
835                 t = PRVM_E_STRING(ed,f);
836                 if (!t)
837                         t = "";
838                 if (!strcmp(t,s))
839                 {
840                         VM_RETURN_EDICT(ed);
841                         return;
842                 }
843         }
844
845         VM_RETURN_EDICT(prog->edicts);
846 }
847
848 /*
849 =========
850 VM_findfloat
851
852   entity        findfloat(entity start, .float field, float match)
853   entity        findentity(entity start, .entity field, entity match)
854 =========
855 */
856 // LordHavoc: added this for searching float, int, and entity reference fields
857 void VM_findfloat (void)
858 {
859         int             e;
860         int             f;
861         float   s;
862         prvm_edict_t    *ed;
863
864         VM_SAFEPARMCOUNT(3,VM_findfloat);
865
866         e = PRVM_G_EDICTNUM(OFS_PARM0);
867         f = PRVM_G_INT(OFS_PARM1);
868         s = PRVM_G_FLOAT(OFS_PARM2);
869
870         for (e++ ; e < prog->num_edicts ; e++)
871         {
872                 prog->xfunction->builtinsprofile++;
873                 ed = PRVM_EDICT_NUM(e);
874                 if (ed->priv.required->free)
875                         continue;
876                 if (PRVM_E_FLOAT(ed,f) == s)
877                 {
878                         VM_RETURN_EDICT(ed);
879                         return;
880                 }
881         }
882
883         VM_RETURN_EDICT(prog->edicts);
884 }
885
886 /*
887 =========
888 VM_findchain
889
890 entity  findchain(.string field, string match)
891 =========
892 */
893 // chained search for strings in entity fields
894 // entity(.string field, string match) findchain = #402;
895 void VM_findchain (void)
896 {
897         int             i;
898         int             f;
899         const char      *s, *t;
900         prvm_edict_t    *ent, *chain;
901         int chainfield;
902
903         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
904
905         if(prog->argc == 3)
906                 chainfield = PRVM_G_INT(OFS_PARM2);
907         else
908                 chainfield = prog->fieldoffsets.chain;
909         if (chainfield < 0)
910                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
911
912         chain = prog->edicts;
913
914         f = PRVM_G_INT(OFS_PARM0);
915         s = PRVM_G_STRING(OFS_PARM1);
916
917         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
918         // expects it to find all the monsters, so we must be careful to support
919         // searching for ""
920
921         ent = PRVM_NEXT_EDICT(prog->edicts);
922         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
923         {
924                 prog->xfunction->builtinsprofile++;
925                 if (ent->priv.required->free)
926                         continue;
927                 t = PRVM_E_STRING(ent,f);
928                 if (!t)
929                         t = "";
930                 if (strcmp(t,s))
931                         continue;
932
933                 PRVM_EDICTFIELDVALUE(ent,chainfield)->edict = PRVM_NUM_FOR_EDICT(chain);
934                 chain = ent;
935         }
936
937         VM_RETURN_EDICT(chain);
938 }
939
940 /*
941 =========
942 VM_findchainfloat
943
944 entity  findchainfloat(.string field, float match)
945 entity  findchainentity(.string field, entity match)
946 =========
947 */
948 // LordHavoc: chained search for float, int, and entity reference fields
949 // entity(.string field, float match) findchainfloat = #403;
950 void VM_findchainfloat (void)
951 {
952         int             i;
953         int             f;
954         float   s;
955         prvm_edict_t    *ent, *chain;
956         int chainfield;
957
958         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
959
960         if(prog->argc == 3)
961                 chainfield = PRVM_G_INT(OFS_PARM2);
962         else
963                 chainfield = prog->fieldoffsets.chain;
964         if (chainfield < 0)
965                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
966
967         chain = (prvm_edict_t *)prog->edicts;
968
969         f = PRVM_G_INT(OFS_PARM0);
970         s = PRVM_G_FLOAT(OFS_PARM1);
971
972         ent = PRVM_NEXT_EDICT(prog->edicts);
973         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
974         {
975                 prog->xfunction->builtinsprofile++;
976                 if (ent->priv.required->free)
977                         continue;
978                 if (PRVM_E_FLOAT(ent,f) != s)
979                         continue;
980
981                 PRVM_EDICTFIELDVALUE(ent,chainfield)->edict = PRVM_EDICT_TO_PROG(chain);
982                 chain = ent;
983         }
984
985         VM_RETURN_EDICT(chain);
986 }
987
988 /*
989 ========================
990 VM_findflags
991
992 entity  findflags(entity start, .float field, float match)
993 ========================
994 */
995 // LordHavoc: search for flags in float fields
996 void VM_findflags (void)
997 {
998         int             e;
999         int             f;
1000         int             s;
1001         prvm_edict_t    *ed;
1002
1003         VM_SAFEPARMCOUNT(3, VM_findflags);
1004
1005
1006         e = PRVM_G_EDICTNUM(OFS_PARM0);
1007         f = PRVM_G_INT(OFS_PARM1);
1008         s = (int)PRVM_G_FLOAT(OFS_PARM2);
1009
1010         for (e++ ; e < prog->num_edicts ; e++)
1011         {
1012                 prog->xfunction->builtinsprofile++;
1013                 ed = PRVM_EDICT_NUM(e);
1014                 if (ed->priv.required->free)
1015                         continue;
1016                 if (!PRVM_E_FLOAT(ed,f))
1017                         continue;
1018                 if ((int)PRVM_E_FLOAT(ed,f) & s)
1019                 {
1020                         VM_RETURN_EDICT(ed);
1021                         return;
1022                 }
1023         }
1024
1025         VM_RETURN_EDICT(prog->edicts);
1026 }
1027
1028 /*
1029 ========================
1030 VM_findchainflags
1031
1032 entity  findchainflags(.float field, float match)
1033 ========================
1034 */
1035 // LordHavoc: chained search for flags in float fields
1036 void VM_findchainflags (void)
1037 {
1038         int             i;
1039         int             f;
1040         int             s;
1041         prvm_edict_t    *ent, *chain;
1042         int chainfield;
1043
1044         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1045
1046         if(prog->argc == 3)
1047                 chainfield = PRVM_G_INT(OFS_PARM2);
1048         else
1049                 chainfield = prog->fieldoffsets.chain;
1050         if (chainfield < 0)
1051                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1052
1053         chain = (prvm_edict_t *)prog->edicts;
1054
1055         f = PRVM_G_INT(OFS_PARM0);
1056         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1057
1058         ent = PRVM_NEXT_EDICT(prog->edicts);
1059         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1060         {
1061                 prog->xfunction->builtinsprofile++;
1062                 if (ent->priv.required->free)
1063                         continue;
1064                 if (!PRVM_E_FLOAT(ent,f))
1065                         continue;
1066                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1067                         continue;
1068
1069                 PRVM_EDICTFIELDVALUE(ent,chainfield)->edict = PRVM_EDICT_TO_PROG(chain);
1070                 chain = ent;
1071         }
1072
1073         VM_RETURN_EDICT(chain);
1074 }
1075
1076 /*
1077 =========
1078 VM_precache_sound
1079
1080 string  precache_sound (string sample)
1081 =========
1082 */
1083 void VM_precache_sound (void)
1084 {
1085         const char *s;
1086
1087         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1088
1089         s = PRVM_G_STRING(OFS_PARM0);
1090         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1091         VM_CheckEmptyString(s);
1092
1093         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1094         {
1095                 VM_Warning("VM_precache_sound: Failed to load %s for %s\n", s, PRVM_NAME);
1096                 return;
1097         }
1098 }
1099
1100 /*
1101 =================
1102 VM_precache_file
1103
1104 returns the same string as output
1105
1106 does nothing, only used by qcc to build .pak archives
1107 =================
1108 */
1109 void VM_precache_file (void)
1110 {
1111         VM_SAFEPARMCOUNT(1,VM_precache_file);
1112         // precache_file is only used to copy files with qcc, it does nothing
1113         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1114 }
1115
1116 /*
1117 =========
1118 VM_coredump
1119
1120 coredump()
1121 =========
1122 */
1123 void VM_coredump (void)
1124 {
1125         VM_SAFEPARMCOUNT(0,VM_coredump);
1126
1127         Cbuf_AddText("prvm_edicts ");
1128         Cbuf_AddText(PRVM_NAME);
1129         Cbuf_AddText("\n");
1130 }
1131
1132 /*
1133 =========
1134 VM_stackdump
1135
1136 stackdump()
1137 =========
1138 */
1139 void PRVM_StackTrace(void);
1140 void VM_stackdump (void)
1141 {
1142         VM_SAFEPARMCOUNT(0, VM_stackdump);
1143
1144         PRVM_StackTrace();
1145 }
1146
1147 /*
1148 =========
1149 VM_crash
1150
1151 crash()
1152 =========
1153 */
1154
1155 void VM_crash(void)
1156 {
1157         VM_SAFEPARMCOUNT(0, VM_crash);
1158
1159         PRVM_ERROR("Crash called by %s",PRVM_NAME);
1160 }
1161
1162 /*
1163 =========
1164 VM_traceon
1165
1166 traceon()
1167 =========
1168 */
1169 void VM_traceon (void)
1170 {
1171         VM_SAFEPARMCOUNT(0,VM_traceon);
1172
1173         prog->trace = true;
1174 }
1175
1176 /*
1177 =========
1178 VM_traceoff
1179
1180 traceoff()
1181 =========
1182 */
1183 void VM_traceoff (void)
1184 {
1185         VM_SAFEPARMCOUNT(0,VM_traceoff);
1186
1187         prog->trace = false;
1188 }
1189
1190 /*
1191 =========
1192 VM_eprint
1193
1194 eprint(entity e)
1195 =========
1196 */
1197 void VM_eprint (void)
1198 {
1199         VM_SAFEPARMCOUNT(1,VM_eprint);
1200
1201         PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1202 }
1203
1204 /*
1205 =========
1206 VM_rint
1207
1208 float   rint(float)
1209 =========
1210 */
1211 void VM_rint (void)
1212 {
1213         float f;
1214         VM_SAFEPARMCOUNT(1,VM_rint);
1215
1216         f = PRVM_G_FLOAT(OFS_PARM0);
1217         if (f > 0)
1218                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1219         else
1220                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1221 }
1222
1223 /*
1224 =========
1225 VM_floor
1226
1227 float   floor(float)
1228 =========
1229 */
1230 void VM_floor (void)
1231 {
1232         VM_SAFEPARMCOUNT(1,VM_floor);
1233
1234         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1235 }
1236
1237 /*
1238 =========
1239 VM_ceil
1240
1241 float   ceil(float)
1242 =========
1243 */
1244 void VM_ceil (void)
1245 {
1246         VM_SAFEPARMCOUNT(1,VM_ceil);
1247
1248         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1249 }
1250
1251
1252 /*
1253 =============
1254 VM_nextent
1255
1256 entity  nextent(entity)
1257 =============
1258 */
1259 void VM_nextent (void)
1260 {
1261         int             i;
1262         prvm_edict_t    *ent;
1263
1264         VM_SAFEPARMCOUNT(1, VM_nextent);
1265
1266         i = PRVM_G_EDICTNUM(OFS_PARM0);
1267         while (1)
1268         {
1269                 prog->xfunction->builtinsprofile++;
1270                 i++;
1271                 if (i == prog->num_edicts)
1272                 {
1273                         VM_RETURN_EDICT(prog->edicts);
1274                         return;
1275                 }
1276                 ent = PRVM_EDICT_NUM(i);
1277                 if (!ent->priv.required->free)
1278                 {
1279                         VM_RETURN_EDICT(ent);
1280                         return;
1281                 }
1282         }
1283 }
1284
1285 //=============================================================================
1286
1287 /*
1288 ==============
1289 VM_changelevel
1290 server and menu
1291
1292 changelevel(string map)
1293 ==============
1294 */
1295 void VM_changelevel (void)
1296 {
1297         VM_SAFEPARMCOUNT(1, VM_changelevel);
1298
1299         if(!sv.active)
1300         {
1301                 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1302                 return;
1303         }
1304
1305 // make sure we don't issue two changelevels
1306         if (svs.changelevel_issued)
1307                 return;
1308         svs.changelevel_issued = true;
1309
1310         Cbuf_AddText (va("changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1311 }
1312
1313 /*
1314 =========
1315 VM_sin
1316
1317 float   sin(float)
1318 =========
1319 */
1320 void VM_sin (void)
1321 {
1322         VM_SAFEPARMCOUNT(1,VM_sin);
1323         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1324 }
1325
1326 /*
1327 =========
1328 VM_cos
1329 float   cos(float)
1330 =========
1331 */
1332 void VM_cos (void)
1333 {
1334         VM_SAFEPARMCOUNT(1,VM_cos);
1335         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1336 }
1337
1338 /*
1339 =========
1340 VM_sqrt
1341
1342 float   sqrt(float)
1343 =========
1344 */
1345 void VM_sqrt (void)
1346 {
1347         VM_SAFEPARMCOUNT(1,VM_sqrt);
1348         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1349 }
1350
1351 /*
1352 =========
1353 VM_asin
1354
1355 float   asin(float)
1356 =========
1357 */
1358 void VM_asin (void)
1359 {
1360         VM_SAFEPARMCOUNT(1,VM_asin);
1361         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1362 }
1363
1364 /*
1365 =========
1366 VM_acos
1367 float   acos(float)
1368 =========
1369 */
1370 void VM_acos (void)
1371 {
1372         VM_SAFEPARMCOUNT(1,VM_acos);
1373         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1374 }
1375
1376 /*
1377 =========
1378 VM_atan
1379 float   atan(float)
1380 =========
1381 */
1382 void VM_atan (void)
1383 {
1384         VM_SAFEPARMCOUNT(1,VM_atan);
1385         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1386 }
1387
1388 /*
1389 =========
1390 VM_atan2
1391 float   atan2(float,float)
1392 =========
1393 */
1394 void VM_atan2 (void)
1395 {
1396         VM_SAFEPARMCOUNT(2,VM_atan2);
1397         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1398 }
1399
1400 /*
1401 =========
1402 VM_tan
1403 float   tan(float)
1404 =========
1405 */
1406 void VM_tan (void)
1407 {
1408         VM_SAFEPARMCOUNT(1,VM_tan);
1409         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1410 }
1411
1412 /*
1413 =================
1414 VM_randomvec
1415
1416 Returns a vector of length < 1 and > 0
1417
1418 vector randomvec()
1419 =================
1420 */
1421 void VM_randomvec (void)
1422 {
1423         vec3_t          temp;
1424         //float         length;
1425
1426         VM_SAFEPARMCOUNT(0, VM_randomvec);
1427
1428         //// WTF ??
1429         do
1430         {
1431                 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1432                 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1433                 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1434         }
1435         while (DotProduct(temp, temp) >= 1);
1436         VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1437
1438         /*
1439         temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1440         temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1441         temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1442         // length returned always > 0
1443         length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1444         VectorScale(temp,length, temp);*/
1445         //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1446 }
1447
1448 //=============================================================================
1449
1450 /*
1451 =========
1452 VM_registercvar
1453
1454 float   registercvar (string name, string value[, float flags])
1455 =========
1456 */
1457 void VM_registercvar (void)
1458 {
1459         const char *name, *value;
1460         int     flags;
1461
1462         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1463
1464         name = PRVM_G_STRING(OFS_PARM0);
1465         value = PRVM_G_STRING(OFS_PARM1);
1466         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1467         PRVM_G_FLOAT(OFS_RETURN) = 0;
1468
1469         if(flags > CVAR_MAXFLAGSVAL)
1470                 return;
1471
1472 // first check to see if it has already been defined
1473         if (Cvar_FindVar (name))
1474                 return;
1475
1476 // check for overlap with a command
1477         if (Cmd_Exists (name))
1478         {
1479                 VM_Warning("VM_registercvar: %s is a command\n", name);
1480                 return;
1481         }
1482
1483         Cvar_Get(name, value, flags, NULL);
1484
1485         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1486 }
1487
1488
1489 /*
1490 =================
1491 VM_min
1492
1493 returns the minimum of two supplied floats
1494
1495 float min(float a, float b, ...[float])
1496 =================
1497 */
1498 void VM_min (void)
1499 {
1500         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1501         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1502         if (prog->argc >= 3)
1503         {
1504                 int i;
1505                 float f = PRVM_G_FLOAT(OFS_PARM0);
1506                 for (i = 1;i < prog->argc;i++)
1507                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1508                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1509                 PRVM_G_FLOAT(OFS_RETURN) = f;
1510         }
1511         else
1512                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1513 }
1514
1515 /*
1516 =================
1517 VM_max
1518
1519 returns the maximum of two supplied floats
1520
1521 float   max(float a, float b, ...[float])
1522 =================
1523 */
1524 void VM_max (void)
1525 {
1526         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1527         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1528         if (prog->argc >= 3)
1529         {
1530                 int i;
1531                 float f = PRVM_G_FLOAT(OFS_PARM0);
1532                 for (i = 1;i < prog->argc;i++)
1533                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1534                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1535                 PRVM_G_FLOAT(OFS_RETURN) = f;
1536         }
1537         else
1538                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1539 }
1540
1541 /*
1542 =================
1543 VM_bound
1544
1545 returns number bounded by supplied range
1546
1547 float   bound(float min, float value, float max)
1548 =================
1549 */
1550 void VM_bound (void)
1551 {
1552         VM_SAFEPARMCOUNT(3,VM_bound);
1553         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1554 }
1555
1556 /*
1557 =================
1558 VM_pow
1559
1560 returns a raised to power b
1561
1562 float   pow(float a, float b)
1563 =================
1564 */
1565 void VM_pow (void)
1566 {
1567         VM_SAFEPARMCOUNT(2,VM_pow);
1568         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1569 }
1570
1571 void VM_log (void)
1572 {
1573         VM_SAFEPARMCOUNT(1,VM_log);
1574         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1575 }
1576
1577 void VM_Files_Init(void)
1578 {
1579         int i;
1580         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1581                 prog->openfiles[i] = NULL;
1582 }
1583
1584 void VM_Files_CloseAll(void)
1585 {
1586         int i;
1587         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1588         {
1589                 if (prog->openfiles[i])
1590                         FS_Close(prog->openfiles[i]);
1591                 prog->openfiles[i] = NULL;
1592         }
1593 }
1594
1595 static qfile_t *VM_GetFileHandle( int index )
1596 {
1597         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1598         {
1599                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1600                 return NULL;
1601         }
1602         if (prog->openfiles[index] == NULL)
1603         {
1604                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1605                 return NULL;
1606         }
1607         return prog->openfiles[index];
1608 }
1609
1610 /*
1611 =========
1612 VM_fopen
1613
1614 float   fopen(string filename, float mode)
1615 =========
1616 */
1617 // float(string filename, float mode) fopen = #110;
1618 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1619 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1620 void VM_fopen(void)
1621 {
1622         int filenum, mode;
1623         const char *modestring, *filename;
1624
1625         VM_SAFEPARMCOUNT(2,VM_fopen);
1626
1627         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1628                 if (prog->openfiles[filenum] == NULL)
1629                         break;
1630         if (filenum >= PRVM_MAX_OPENFILES)
1631         {
1632                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1633                 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENFILES);
1634                 return;
1635         }
1636         filename = PRVM_G_STRING(OFS_PARM0);
1637         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1638         switch(mode)
1639         {
1640         case 0: // FILE_READ
1641                 modestring = "rb";
1642                 prog->openfiles[filenum] = FS_OpenVirtualFile(va("data/%s", filename), false);
1643                 if (prog->openfiles[filenum] == NULL)
1644                         prog->openfiles[filenum] = FS_OpenVirtualFile(va("%s", filename), false);
1645                 break;
1646         case 1: // FILE_APPEND
1647                 modestring = "a";
1648                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1649                 break;
1650         case 2: // FILE_WRITE
1651                 modestring = "w";
1652                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1653                 break;
1654         default:
1655                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1656                 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1657                 return;
1658         }
1659
1660         if (prog->openfiles[filenum] == NULL)
1661         {
1662                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1663                 if (developer.integer >= 100)
1664                         VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1665         }
1666         else
1667         {
1668                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1669                 if (developer.integer >= 100)
1670                         Con_Printf("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1671                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin();
1672         }
1673 }
1674
1675 /*
1676 =========
1677 VM_fclose
1678
1679 fclose(float fhandle)
1680 =========
1681 */
1682 //void(float fhandle) fclose = #111; // closes a file
1683 void VM_fclose(void)
1684 {
1685         int filenum;
1686
1687         VM_SAFEPARMCOUNT(1,VM_fclose);
1688
1689         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1690         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1691         {
1692                 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1693                 return;
1694         }
1695         if (prog->openfiles[filenum] == NULL)
1696         {
1697                 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1698                 return;
1699         }
1700         FS_Close(prog->openfiles[filenum]);
1701         prog->openfiles[filenum] = NULL;
1702         if(prog->openfiles_origin[filenum])
1703                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1704         if (developer.integer >= 100)
1705                 Con_Printf("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1706 }
1707
1708 /*
1709 =========
1710 VM_fgets
1711
1712 string  fgets(float fhandle)
1713 =========
1714 */
1715 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1716 void VM_fgets(void)
1717 {
1718         int c, end;
1719         char string[VM_STRINGTEMP_LENGTH];
1720         int filenum;
1721
1722         VM_SAFEPARMCOUNT(1,VM_fgets);
1723
1724         // set the return value regardless of any possible errors
1725         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1726
1727         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1728         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1729         {
1730                 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1731                 return;
1732         }
1733         if (prog->openfiles[filenum] == NULL)
1734         {
1735                 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1736                 return;
1737         }
1738         end = 0;
1739         for (;;)
1740         {
1741                 c = FS_Getc(prog->openfiles[filenum]);
1742                 if (c == '\r' || c == '\n' || c < 0)
1743                         break;
1744                 if (end < VM_STRINGTEMP_LENGTH - 1)
1745                         string[end++] = c;
1746         }
1747         string[end] = 0;
1748         // remove \n following \r
1749         if (c == '\r')
1750         {
1751                 c = FS_Getc(prog->openfiles[filenum]);
1752                 if (c != '\n')
1753                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1754         }
1755         if (developer.integer >= 100)
1756                 Con_Printf("fgets: %s: %s\n", PRVM_NAME, string);
1757         if (c >= 0 || end)
1758                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
1759 }
1760
1761 /*
1762 =========
1763 VM_fputs
1764
1765 fputs(float fhandle, string s)
1766 =========
1767 */
1768 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1769 void VM_fputs(void)
1770 {
1771         int stringlength;
1772         char string[VM_STRINGTEMP_LENGTH];
1773         int filenum;
1774
1775         VM_SAFEPARMCOUNT(2,VM_fputs);
1776
1777         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1778         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1779         {
1780                 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1781                 return;
1782         }
1783         if (prog->openfiles[filenum] == NULL)
1784         {
1785                 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1786                 return;
1787         }
1788         VM_VarString(1, string, sizeof(string));
1789         if ((stringlength = (int)strlen(string)))
1790                 FS_Write(prog->openfiles[filenum], string, stringlength);
1791         if (developer.integer >= 100)
1792                 Con_Printf("fputs: %s: %s\n", PRVM_NAME, string);
1793 }
1794
1795 /*
1796 =========
1797 VM_writetofile
1798
1799         writetofile(float fhandle, entity ent)
1800 =========
1801 */
1802 void VM_writetofile(void)
1803 {
1804         prvm_edict_t * ent;
1805         qfile_t *file;
1806
1807         VM_SAFEPARMCOUNT(2, VM_writetofile);
1808
1809         file = VM_GetFileHandle( (int)PRVM_G_FLOAT(OFS_PARM0) );
1810         if( !file )
1811         {
1812                 VM_Warning("VM_writetofile: invalid or closed file handle\n");
1813                 return;
1814         }
1815
1816         ent = PRVM_G_EDICT(OFS_PARM1);
1817         if(ent->priv.required->free)
1818         {
1819                 VM_Warning("VM_writetofile: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
1820                 return;
1821         }
1822
1823         PRVM_ED_Write (file, ent);
1824 }
1825
1826 // KrimZon - DP_QC_ENTITYDATA
1827 /*
1828 =========
1829 VM_numentityfields
1830
1831 float() numentityfields
1832 Return the number of entity fields - NOT offsets
1833 =========
1834 */
1835 void VM_numentityfields(void)
1836 {
1837         PRVM_G_FLOAT(OFS_RETURN) = prog->progs->numfielddefs;
1838 }
1839
1840 // KrimZon - DP_QC_ENTITYDATA
1841 /*
1842 =========
1843 VM_entityfieldname
1844
1845 string(float fieldnum) entityfieldname
1846 Return name of the specified field as a string, or empty if the field is invalid (warning)
1847 =========
1848 */
1849 void VM_entityfieldname(void)
1850 {
1851         ddef_t *d;
1852         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
1853         
1854         if (i < 0 || i >= prog->progs->numfielddefs)
1855         {
1856         VM_Warning("VM_entityfieldname: %s: field index out of bounds\n", PRVM_NAME);
1857         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
1858                 return;
1859         }
1860         
1861         d = &prog->fielddefs[i];
1862         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
1863 }
1864
1865 // KrimZon - DP_QC_ENTITYDATA
1866 /*
1867 =========
1868 VM_entityfieldtype
1869
1870 float(float fieldnum) entityfieldtype
1871 =========
1872 */
1873 void VM_entityfieldtype(void)
1874 {
1875         ddef_t *d;
1876         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
1877         
1878         if (i < 0 || i >= prog->progs->numfielddefs)
1879         {
1880                 VM_Warning("VM_entityfieldtype: %s: field index out of bounds\n", PRVM_NAME);
1881                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
1882                 return;
1883         }
1884         
1885         d = &prog->fielddefs[i];
1886         PRVM_G_FLOAT(OFS_RETURN) = (float)d->type;
1887 }
1888
1889 // KrimZon - DP_QC_ENTITYDATA
1890 /*
1891 =========
1892 VM_getentityfieldstring
1893
1894 string(float fieldnum, entity ent) getentityfieldstring
1895 =========
1896 */
1897 void VM_getentityfieldstring(void)
1898 {
1899         // put the data into a string
1900         ddef_t *d;
1901         int type, j;
1902         int *v;
1903         prvm_edict_t * ent;
1904         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
1905         
1906         if (i < 0 || i >= prog->progs->numfielddefs)
1907         {
1908         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
1909                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
1910                 return;
1911         }
1912         
1913         d = &prog->fielddefs[i];
1914         
1915         // get the entity
1916         ent = PRVM_G_EDICT(OFS_PARM1);
1917         if(ent->priv.required->free)
1918         {
1919                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
1920                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
1921                 return;
1922         }
1923         v = (int *)((char *)ent->fields.vp + d->ofs*4);
1924         
1925         // if it's 0 or blank, return an empty string
1926         type = d->type & ~DEF_SAVEGLOBAL;
1927         for (j=0 ; j<prvm_type_size[type] ; j++)
1928                 if (v[j])
1929                         break;
1930         if (j == prvm_type_size[type])
1931         {
1932                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
1933                 return;
1934         }
1935                 
1936         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_UglyValueString((etype_t)d->type, (prvm_eval_t *)v));
1937 }
1938
1939 // KrimZon - DP_QC_ENTITYDATA
1940 /*
1941 =========
1942 VM_putentityfieldstring
1943
1944 float(float fieldnum, entity ent, string s) putentityfieldstring
1945 =========
1946 */
1947 void VM_putentityfieldstring(void)
1948 {
1949         ddef_t *d;
1950         prvm_edict_t * ent;
1951         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
1952
1953         if (i < 0 || i >= prog->progs->numfielddefs)
1954         {
1955         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
1956                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
1957                 return;
1958         }
1959
1960         d = &prog->fielddefs[i];
1961
1962         // get the entity
1963         ent = PRVM_G_EDICT(OFS_PARM1);
1964         if(ent->priv.required->free)
1965         {
1966                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
1967                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
1968                 return;
1969         }
1970
1971         // parse the string into the value
1972         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
1973 }
1974
1975 /*
1976 =========
1977 VM_strlen
1978
1979 float   strlen(string s)
1980 =========
1981 */
1982 //float(string s) strlen = #114; // returns how many characters are in a string
1983 void VM_strlen(void)
1984 {
1985         VM_SAFEPARMCOUNT(1,VM_strlen);
1986
1987         PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
1988 }
1989
1990 // DRESK - Decolorized String
1991 /*
1992 =========
1993 VM_strdecolorize
1994
1995 string  strdecolorize(string s)
1996 =========
1997 */
1998 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
1999 void VM_strdecolorize(void)
2000 {
2001         char szNewString[VM_STRINGTEMP_LENGTH];
2002         const char *szString;
2003
2004         // Prepare Strings
2005         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2006         szString = PRVM_G_STRING(OFS_PARM0);
2007         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
2008         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2009 }
2010
2011 // DRESK - String Length (not counting color codes)
2012 /*
2013 =========
2014 VM_strlennocol
2015
2016 float   strlennocol(string s)
2017 =========
2018 */
2019 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2020 // For example, ^2Dresk returns a length of 5
2021 void VM_strlennocol(void)
2022 {
2023         const char *szString;
2024         int nCnt;
2025
2026         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2027
2028         szString = PRVM_G_STRING(OFS_PARM0);
2029
2030         nCnt = COM_StringLengthNoColors(szString, 0, NULL);
2031
2032         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2033 }
2034
2035 // DRESK - String to Uppercase and Lowercase
2036 /*
2037 =========
2038 VM_strtolower
2039
2040 string  strtolower(string s)
2041 =========
2042 */
2043 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2044 void VM_strtolower(void)
2045 {
2046         char szNewString[VM_STRINGTEMP_LENGTH];
2047         const char *szString;
2048
2049         // Prepare Strings
2050         VM_SAFEPARMCOUNT(1,VM_strtolower);
2051         szString = PRVM_G_STRING(OFS_PARM0);
2052
2053         COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2054
2055         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2056 }
2057
2058 /*
2059 =========
2060 VM_strtoupper
2061
2062 string  strtoupper(string s)
2063 =========
2064 */
2065 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2066 void VM_strtoupper(void)
2067 {
2068         char szNewString[VM_STRINGTEMP_LENGTH];
2069         const char *szString;
2070
2071         // Prepare Strings
2072         VM_SAFEPARMCOUNT(1,VM_strtoupper);
2073         szString = PRVM_G_STRING(OFS_PARM0);
2074
2075         COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2076
2077         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2078 }
2079
2080 /*
2081 =========
2082 VM_strcat
2083
2084 string strcat(string,string,...[string])
2085 =========
2086 */
2087 //string(string s1, string s2) strcat = #115;
2088 // concatenates two strings (for example "abc", "def" would return "abcdef")
2089 // and returns as a tempstring
2090 void VM_strcat(void)
2091 {
2092         char s[VM_STRINGTEMP_LENGTH];
2093         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2094
2095         VM_VarString(0, s, sizeof(s));
2096         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
2097 }
2098
2099 /*
2100 =========
2101 VM_substring
2102
2103 string  substring(string s, float start, float length)
2104 =========
2105 */
2106 // string(string s, float start, float length) substring = #116;
2107 // returns a section of a string as a tempstring
2108 void VM_substring(void)
2109 {
2110         int start, length, slength, maxlen;
2111         const char *s;
2112         char string[VM_STRINGTEMP_LENGTH];
2113
2114         VM_SAFEPARMCOUNT(3,VM_substring);
2115
2116         s = PRVM_G_STRING(OFS_PARM0);
2117         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2118         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2119         slength = strlen(s);
2120
2121         if (start < 0) // FTE_STRINGS feature
2122                 start += slength;
2123         start = bound(0, start, slength);
2124
2125         if (length < 0) // FTE_STRINGS feature
2126                 length += slength - start + 1;
2127         maxlen = min((int)sizeof(string) - 1, slength - start);
2128         length = bound(0, length, maxlen);
2129
2130         memcpy(string, s + start, length);
2131         string[length] = 0;
2132         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2133 }
2134
2135 /*
2136 =========
2137 VM_strreplace
2138
2139 string(string search, string replace, string subject) strreplace = #484;
2140 =========
2141 */
2142 // replaces all occurrences of search with replace in the string subject, and returns the result
2143 void VM_strreplace(void)
2144 {
2145         int i, j, si;
2146         const char *search, *replace, *subject;
2147         char string[VM_STRINGTEMP_LENGTH];
2148         int search_len, replace_len, subject_len;
2149
2150         VM_SAFEPARMCOUNT(3,VM_strreplace);
2151
2152         search = PRVM_G_STRING(OFS_PARM0);
2153         replace = PRVM_G_STRING(OFS_PARM1);
2154         subject = PRVM_G_STRING(OFS_PARM2);
2155
2156         search_len = (int)strlen(search);
2157         replace_len = (int)strlen(replace);
2158         subject_len = (int)strlen(subject);
2159
2160         si = 0;
2161         for (i = 0; i < subject_len; i++)
2162         {
2163                 for (j = 0; j < search_len && i+j < subject_len; j++)
2164                         if (subject[i+j] != search[j])
2165                                 break;
2166                 if (j == search_len || i+j == subject_len)
2167                 {
2168                 // found it at offset 'i'
2169                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2170                                 string[si++] = replace[j];
2171                         i += search_len - 1;
2172                 }
2173                 else
2174                 {
2175                 // not found
2176                         if (si < (int)sizeof(string) - 1)
2177                                 string[si++] = subject[i];
2178                 }
2179         }
2180         string[si] = '\0';
2181
2182         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2183 }
2184
2185 /*
2186 =========
2187 VM_strireplace
2188
2189 string(string search, string replace, string subject) strireplace = #485;
2190 =========
2191 */
2192 // case-insensitive version of strreplace
2193 void VM_strireplace(void)
2194 {
2195         int i, j, si;
2196         const char *search, *replace, *subject;
2197         char string[VM_STRINGTEMP_LENGTH];
2198         int search_len, replace_len, subject_len;
2199
2200         VM_SAFEPARMCOUNT(3,VM_strreplace);
2201
2202         search = PRVM_G_STRING(OFS_PARM0);
2203         replace = PRVM_G_STRING(OFS_PARM1);
2204         subject = PRVM_G_STRING(OFS_PARM2);
2205
2206         search_len = (int)strlen(search);
2207         replace_len = (int)strlen(replace);
2208         subject_len = (int)strlen(subject);
2209
2210         si = 0;
2211         for (i = 0; i < subject_len; i++)
2212         {
2213                 for (j = 0; j < search_len && i+j < subject_len; j++)
2214                         if (tolower(subject[i+j]) != tolower(search[j]))
2215                                 break;
2216                 if (j == search_len || i+j == subject_len)
2217                 {
2218                 // found it at offset 'i'
2219                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2220                                 string[si++] = replace[j];
2221                         i += search_len - 1;
2222                 }
2223                 else
2224                 {
2225                 // not found
2226                         if (si < (int)sizeof(string) - 1)
2227                                 string[si++] = subject[i];
2228                 }
2229         }
2230         string[si] = '\0';
2231
2232         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2233 }
2234
2235 /*
2236 =========
2237 VM_stov
2238
2239 vector  stov(string s)
2240 =========
2241 */
2242 //vector(string s) stov = #117; // returns vector value from a string
2243 void VM_stov(void)
2244 {
2245         char string[VM_STRINGTEMP_LENGTH];
2246
2247         VM_SAFEPARMCOUNT(1,VM_stov);
2248
2249         VM_VarString(0, string, sizeof(string));
2250         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2251 }
2252
2253 /*
2254 =========
2255 VM_strzone
2256
2257 string  strzone(string s)
2258 =========
2259 */
2260 //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)
2261 void VM_strzone(void)
2262 {
2263         char *out;
2264         char string[VM_STRINGTEMP_LENGTH];
2265         size_t alloclen;
2266
2267         VM_SAFEPARMCOUNT(1,VM_strzone);
2268
2269         VM_VarString(0, string, sizeof(string));
2270         alloclen = strlen(string) + 1;
2271         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
2272         memcpy(out, string, alloclen);
2273 }
2274
2275 /*
2276 =========
2277 VM_strunzone
2278
2279 strunzone(string s)
2280 =========
2281 */
2282 //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!!!)
2283 void VM_strunzone(void)
2284 {
2285         VM_SAFEPARMCOUNT(1,VM_strunzone);
2286         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
2287 }
2288
2289 /*
2290 =========
2291 VM_command (used by client and menu)
2292
2293 clientcommand(float client, string s) (for client and menu)
2294 =========
2295 */
2296 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
2297 //this function originally written by KrimZon, made shorter by LordHavoc
2298 void VM_clcommand (void)
2299 {
2300         client_t *temp_client;
2301         int i;
2302
2303         VM_SAFEPARMCOUNT(2,VM_clcommand);
2304
2305         i = (int)PRVM_G_FLOAT(OFS_PARM0);
2306         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
2307         {
2308                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
2309                 return;
2310         }
2311
2312         temp_client = host_client;
2313         host_client = svs.clients + i;
2314         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
2315         host_client = temp_client;
2316 }
2317
2318
2319 /*
2320 =========
2321 VM_tokenize
2322
2323 float tokenize(string s)
2324 =========
2325 */
2326 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2327 //this function originally written by KrimZon, made shorter by LordHavoc
2328 //20040203: rewritten by LordHavoc (no longer uses allocations)
2329 static int num_tokens = 0;
2330 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2331 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2332 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2333 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2334 void VM_tokenize (void)
2335 {
2336         const char *p;
2337
2338         VM_SAFEPARMCOUNT(1,VM_tokenize);
2339
2340         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2341         p = tokenize_string;
2342
2343         num_tokens = 0;
2344         for(;;)
2345         {
2346                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2347                         break;
2348
2349                 // skip whitespace here to find token start pos
2350                 while(*p && ISWHITESPACE(*p))
2351                         ++p;
2352
2353                 tokens_startpos[num_tokens] = p - tokenize_string;
2354                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2355                         break;
2356                 tokens_endpos[num_tokens] = p - tokenize_string;
2357                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2358                 ++num_tokens;
2359         }
2360
2361         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2362 }
2363
2364 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2365 void VM_tokenize_console (void)
2366 {
2367         const char *p;
2368
2369         VM_SAFEPARMCOUNT(1,VM_tokenize);
2370
2371         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2372         p = tokenize_string;
2373
2374         num_tokens = 0;
2375         for(;;)
2376         {
2377                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2378                         break;
2379
2380                 // skip whitespace here to find token start pos
2381                 while(*p && ISWHITESPACE(*p))
2382                         ++p;
2383
2384                 tokens_startpos[num_tokens] = p - tokenize_string;
2385                 if(!COM_ParseToken_Console(&p))
2386                         break;
2387                 tokens_endpos[num_tokens] = p - tokenize_string;
2388                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2389                 ++num_tokens;
2390         }
2391
2392         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2393 }
2394
2395 /*
2396 =========
2397 VM_tokenizebyseparator
2398
2399 float tokenizebyseparator(string s, string separator1, ...)
2400 =========
2401 */
2402 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2403 //this function returns the token preceding each instance of a separator (of
2404 //which there can be multiple), and the text following the last separator
2405 //useful for parsing certain kinds of data like IP addresses
2406 //example:
2407 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2408 //returns 4 and the tokens "10" "1" "2" "3".
2409 void VM_tokenizebyseparator (void)
2410 {
2411         int j, k;
2412         int numseparators;
2413         int separatorlen[7];
2414         const char *separators[7];
2415         const char *p, *p0;
2416         const char *token;
2417         char tokentext[MAX_INPUTLINE];
2418
2419         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2420
2421         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2422         p = tokenize_string;
2423
2424         numseparators = 0;
2425         for (j = 1;j < prog->argc;j++)
2426         {
2427                 // skip any blank separator strings
2428                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2429                 if (!s[0])
2430                         continue;
2431                 separators[numseparators] = s;
2432                 separatorlen[numseparators] = strlen(s);
2433                 numseparators++;
2434         }
2435
2436         num_tokens = 0;
2437         j = 0;
2438
2439         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2440         {
2441                 token = tokentext + j;
2442                 tokens_startpos[num_tokens] = p - tokenize_string;
2443                 p0 = p;
2444                 while (*p)
2445                 {
2446                         for (k = 0;k < numseparators;k++)
2447                         {
2448                                 if (!strncmp(p, separators[k], separatorlen[k]))
2449                                 {
2450                                         p += separatorlen[k];
2451                                         break;
2452                                 }
2453                         }
2454                         if (k < numseparators)
2455                                 break;
2456                         if (j < (int)sizeof(tokentext)-1)
2457                                 tokentext[j++] = *p;
2458                         p++;
2459                         p0 = p;
2460                 }
2461                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2462                 if (j >= (int)sizeof(tokentext))
2463                         break;
2464                 tokentext[j++] = 0;
2465                 tokens[num_tokens++] = PRVM_SetTempString(token);
2466                 if (!*p)
2467                         break;
2468         }
2469
2470         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2471 }
2472
2473 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2474 //this function originally written by KrimZon, made shorter by LordHavoc
2475 void VM_argv (void)
2476 {
2477         int token_num;
2478
2479         VM_SAFEPARMCOUNT(1,VM_argv);
2480
2481         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2482
2483         if(token_num < 0)
2484                 token_num += num_tokens;
2485
2486         if (token_num >= 0 && token_num < num_tokens)
2487                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2488         else
2489                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2490 }
2491
2492 //float(float n) argv_start_index = #515; // returns the start index of a token
2493 void VM_argv_start_index (void)
2494 {
2495         int token_num;
2496
2497         VM_SAFEPARMCOUNT(1,VM_argv);
2498
2499         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2500
2501         if(token_num < 0)
2502                 token_num += num_tokens;
2503
2504         if (token_num >= 0 && token_num < num_tokens)
2505                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2506         else
2507                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2508 }
2509
2510 //float(float n) argv_end_index = #516; // returns the end index of a token
2511 void VM_argv_end_index (void)
2512 {
2513         int token_num;
2514
2515         VM_SAFEPARMCOUNT(1,VM_argv);
2516
2517         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2518
2519         if(token_num < 0)
2520                 token_num += num_tokens;
2521
2522         if (token_num >= 0 && token_num < num_tokens)
2523                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2524         else
2525                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2526 }
2527
2528 /*
2529 =========
2530 VM_isserver
2531
2532 float   isserver()
2533 =========
2534 */
2535 void VM_isserver(void)
2536 {
2537         VM_SAFEPARMCOUNT(0,VM_serverstate);
2538
2539         PRVM_G_FLOAT(OFS_RETURN) = sv.active && (svs.maxclients > 1 || cls.state == ca_dedicated);
2540 }
2541
2542 /*
2543 =========
2544 VM_clientcount
2545
2546 float   clientcount()
2547 =========
2548 */
2549 void VM_clientcount(void)
2550 {
2551         VM_SAFEPARMCOUNT(0,VM_clientcount);
2552
2553         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2554 }
2555
2556 /*
2557 =========
2558 VM_clientstate
2559
2560 float   clientstate()
2561 =========
2562 */
2563 void VM_clientstate(void)
2564 {
2565         VM_SAFEPARMCOUNT(0,VM_clientstate);
2566
2567
2568         switch( cls.state ) {
2569                 case ca_uninitialized:
2570                 case ca_dedicated:
2571                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2572                         break;
2573                 case ca_disconnected:
2574                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2575                         break;
2576                 case ca_connected:
2577                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2578                         break;
2579                 default:
2580                         // should never be reached!
2581                         break;
2582         }
2583 }
2584
2585 /*
2586 =========
2587 VM_getostype
2588
2589 float   getostype(void)
2590 =========
2591 */ // not used at the moment -> not included in the common list
2592 void VM_getostype(void)
2593 {
2594         VM_SAFEPARMCOUNT(0,VM_getostype);
2595
2596         /*
2597         OS_WINDOWS
2598         OS_LINUX
2599         OS_MAC - not supported
2600         */
2601
2602 #ifdef WIN32
2603         PRVM_G_FLOAT(OFS_RETURN) = 0;
2604 #elif defined(MACOSX)
2605         PRVM_G_FLOAT(OFS_RETURN) = 2;
2606 #else
2607         PRVM_G_FLOAT(OFS_RETURN) = 1;
2608 #endif
2609 }
2610
2611 /*
2612 =========
2613 VM_gettime
2614
2615 float   gettime(void)
2616 =========
2617 */
2618 extern double host_starttime;
2619 float CDAudio_GetPosition(void);
2620 void VM_gettime(void)
2621 {
2622         int timer_index;
2623
2624         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2625
2626         if(prog->argc == 0)
2627         {
2628                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2629         }
2630         else
2631         {
2632                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2633         switch(timer_index)
2634         {
2635             case 0: // GETTIME_FRAMESTART
2636                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2637                 break;
2638             case 1: // GETTIME_REALTIME
2639                 PRVM_G_FLOAT(OFS_RETURN) = (float) Sys_DoubleTime();
2640                 break;
2641             case 2: // GETTIME_HIRES
2642                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - realtime);
2643                 break;
2644             case 3: // GETTIME_UPTIME
2645                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - host_starttime);
2646                 break;
2647             case 4: // GETTIME_CDTRACK
2648                 PRVM_G_FLOAT(OFS_RETURN) = (float) CDAudio_GetPosition();
2649                 break;
2650                         default:
2651                                 VM_Warning("VM_gettime: %s: unsupported timer specified, returning realtime\n", PRVM_NAME);
2652                                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2653                                 break;
2654                 }
2655         }
2656 }
2657
2658 /*
2659 =========
2660 VM_loadfromdata
2661
2662 loadfromdata(string data)
2663 =========
2664 */
2665 void VM_loadfromdata(void)
2666 {
2667         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2668
2669         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2670 }
2671
2672 /*
2673 ========================
2674 VM_parseentitydata
2675
2676 parseentitydata(entity ent, string data)
2677 ========================
2678 */
2679 void VM_parseentitydata(void)
2680 {
2681         prvm_edict_t *ent;
2682         const char *data;
2683
2684         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2685
2686         // get edict and test it
2687         ent = PRVM_G_EDICT(OFS_PARM0);
2688         if (ent->priv.required->free)
2689                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2690
2691         data = PRVM_G_STRING(OFS_PARM1);
2692
2693         // parse the opening brace
2694         if (!COM_ParseToken_Simple(&data, false, false) || com_token[0] != '{' )
2695                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2696
2697         PRVM_ED_ParseEdict (data, ent);
2698 }
2699
2700 /*
2701 =========
2702 VM_loadfromfile
2703
2704 loadfromfile(string file)
2705 =========
2706 */
2707 void VM_loadfromfile(void)
2708 {
2709         const char *filename;
2710         char *data;
2711
2712         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
2713
2714         filename = PRVM_G_STRING(OFS_PARM0);
2715         if (FS_CheckNastyPath(filename, false))
2716         {
2717                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2718                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
2719                 return;
2720         }
2721
2722         // not conform with VM_fopen
2723         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
2724         if (data == NULL)
2725                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2726
2727         PRVM_ED_LoadFromFile(data);
2728
2729         if(data)
2730                 Mem_Free(data);
2731 }
2732
2733
2734 /*
2735 =========
2736 VM_modulo
2737
2738 float   mod(float val, float m)
2739 =========
2740 */
2741 void VM_modulo(void)
2742 {
2743         int val, m;
2744         VM_SAFEPARMCOUNT(2,VM_module);
2745
2746         val = (int) PRVM_G_FLOAT(OFS_PARM0);
2747         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
2748
2749         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
2750 }
2751
2752 void VM_Search_Init(void)
2753 {
2754         int i;
2755         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
2756                 prog->opensearches[i] = NULL;
2757 }
2758
2759 void VM_Search_Reset(void)
2760 {
2761         int i;
2762         // reset the fssearch list
2763         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
2764         {
2765                 if(prog->opensearches[i])
2766                         FS_FreeSearch(prog->opensearches[i]);
2767                 prog->opensearches[i] = NULL;
2768         }
2769 }
2770
2771 /*
2772 =========
2773 VM_search_begin
2774
2775 float search_begin(string pattern, float caseinsensitive, float quiet)
2776 =========
2777 */
2778 void VM_search_begin(void)
2779 {
2780         int handle;
2781         const char *pattern;
2782         int caseinsens, quiet;
2783
2784         VM_SAFEPARMCOUNT(3, VM_search_begin);
2785
2786         pattern = PRVM_G_STRING(OFS_PARM0);
2787
2788         VM_CheckEmptyString(pattern);
2789
2790         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
2791         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
2792
2793         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
2794                 if(!prog->opensearches[handle])
2795                         break;
2796
2797         if(handle >= PRVM_MAX_OPENSEARCHES)
2798         {
2799                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2800                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
2801                 return;
2802         }
2803
2804         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
2805                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2806         else
2807         {
2808                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin();
2809                 PRVM_G_FLOAT(OFS_RETURN) = handle;
2810         }
2811 }
2812
2813 /*
2814 =========
2815 VM_search_end
2816
2817 void    search_end(float handle)
2818 =========
2819 */
2820 void VM_search_end(void)
2821 {
2822         int handle;
2823         VM_SAFEPARMCOUNT(1, VM_search_end);
2824
2825         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2826
2827         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2828         {
2829                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
2830                 return;
2831         }
2832         if(prog->opensearches[handle] == NULL)
2833         {
2834                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
2835                 return;
2836         }
2837
2838         FS_FreeSearch(prog->opensearches[handle]);
2839         prog->opensearches[handle] = NULL;
2840         if(prog->opensearches_origin[handle])
2841                 PRVM_Free((char *)prog->opensearches_origin[handle]);
2842 }
2843
2844 /*
2845 =========
2846 VM_search_getsize
2847
2848 float   search_getsize(float handle)
2849 =========
2850 */
2851 void VM_search_getsize(void)
2852 {
2853         int handle;
2854         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
2855
2856         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2857
2858         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2859         {
2860                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
2861                 return;
2862         }
2863         if(prog->opensearches[handle] == NULL)
2864         {
2865                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
2866                 return;
2867         }
2868
2869         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
2870 }
2871
2872 /*
2873 =========
2874 VM_search_getfilename
2875
2876 string  search_getfilename(float handle, float num)
2877 =========
2878 */
2879 void VM_search_getfilename(void)
2880 {
2881         int handle, filenum;
2882         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
2883
2884         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2885         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
2886
2887         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2888         {
2889                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
2890                 return;
2891         }
2892         if(prog->opensearches[handle] == NULL)
2893         {
2894                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
2895                 return;
2896         }
2897         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
2898         {
2899                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
2900                 return;
2901         }
2902
2903         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog->opensearches[handle]->filenames[filenum]);
2904 }
2905
2906 /*
2907 =========
2908 VM_chr
2909
2910 string  chr(float ascii)
2911 =========
2912 */
2913 void VM_chr(void)
2914 {
2915         char tmp[2];
2916         VM_SAFEPARMCOUNT(1, VM_chr);
2917
2918         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
2919         tmp[1] = 0;
2920
2921         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
2922 }
2923
2924 //=============================================================================
2925 // Draw builtins (client & menu)
2926
2927 /*
2928 =========
2929 VM_iscachedpic
2930
2931 float   iscachedpic(string pic)
2932 =========
2933 */
2934 void VM_iscachedpic(void)
2935 {
2936         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
2937
2938         // drawq hasnt such a function, thus always return true
2939         PRVM_G_FLOAT(OFS_RETURN) = false;
2940 }
2941
2942 /*
2943 =========
2944 VM_precache_pic
2945
2946 string  precache_pic(string pic)
2947 =========
2948 */
2949 void VM_precache_pic(void)
2950 {
2951         const char      *s;
2952
2953         VM_SAFEPARMCOUNT(1, VM_precache_pic);
2954
2955         s = PRVM_G_STRING(OFS_PARM0);
2956         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
2957         VM_CheckEmptyString (s);
2958
2959         // AK Draw_CachePic is supposed to always return a valid pointer
2960         if( Draw_CachePic_Flags(s, CACHEPICFLAG_NOTPERSISTENT)->tex == r_texture_notexture )
2961                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2962 }
2963
2964 /*
2965 =========
2966 VM_freepic
2967
2968 freepic(string s)
2969 =========
2970 */
2971 void VM_freepic(void)
2972 {
2973         const char *s;
2974
2975         VM_SAFEPARMCOUNT(1,VM_freepic);
2976
2977         s = PRVM_G_STRING(OFS_PARM0);
2978         VM_CheckEmptyString (s);
2979
2980         Draw_FreePic(s);
2981 }
2982
2983 dp_font_t *getdrawfont(void)
2984 {
2985         if(prog->globaloffsets.drawfont >= 0)
2986         {
2987                 int f = (int) PRVM_G_FLOAT(prog->globaloffsets.drawfont);
2988                 if(f < 0 || f >= MAX_FONTS)
2989                         return FONT_DEFAULT;
2990                 return &dp_fonts[f];
2991         }
2992         else
2993                 return FONT_DEFAULT;
2994 }
2995
2996 /*
2997 =========
2998 VM_drawcharacter
2999
3000 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
3001 =========
3002 */
3003 void VM_drawcharacter(void)
3004 {
3005         float *pos,*scale,*rgb;
3006         char   character;
3007         int flag;
3008         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
3009
3010         character = (char) PRVM_G_FLOAT(OFS_PARM1);
3011         if(character == 0)
3012         {
3013                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3014                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
3015                 return;
3016         }
3017
3018         pos = PRVM_G_VECTOR(OFS_PARM0);
3019         scale = PRVM_G_VECTOR(OFS_PARM2);
3020         rgb = PRVM_G_VECTOR(OFS_PARM3);
3021         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3022
3023         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3024         {
3025                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3026                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3027                 return;
3028         }
3029
3030         if(pos[2] || scale[2])
3031                 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")));
3032
3033         if(!scale[0] || !scale[1])
3034         {
3035                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3036                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3037                 return;
3038         }
3039
3040         DrawQ_String_Font(pos[0], pos[1], &character, 1, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3041         PRVM_G_FLOAT(OFS_RETURN) = 1;
3042 }
3043
3044 /*
3045 =========
3046 VM_drawstring
3047
3048 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3049 =========
3050 */
3051 void VM_drawstring(void)
3052 {
3053         float *pos,*scale,*rgb;
3054         const char  *string;
3055         int flag;
3056         VM_SAFEPARMCOUNT(6,VM_drawstring);
3057
3058         string = PRVM_G_STRING(OFS_PARM1);
3059         pos = PRVM_G_VECTOR(OFS_PARM0);
3060         scale = PRVM_G_VECTOR(OFS_PARM2);
3061         rgb = PRVM_G_VECTOR(OFS_PARM3);
3062         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3063
3064         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3065         {
3066                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3067                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3068                 return;
3069         }
3070
3071         if(!scale[0] || !scale[1])
3072         {
3073                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3074                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3075                 return;
3076         }
3077
3078         if(pos[2] || scale[2])
3079                 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")));
3080
3081         DrawQ_String_Font(pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3082         PRVM_G_FLOAT(OFS_RETURN) = 1;
3083 }
3084
3085 /*
3086 =========
3087 VM_drawcolorcodedstring
3088
3089 float   drawcolorcodedstring(vector position, string text, vector scale, float alpha, float flag)
3090 =========
3091 */
3092 void VM_drawcolorcodedstring(void)
3093 {
3094         float *pos,*scale;
3095         const char  *string;
3096         int flag,color;
3097         VM_SAFEPARMCOUNT(5,VM_drawstring);
3098
3099         string = PRVM_G_STRING(OFS_PARM1);
3100         pos = PRVM_G_VECTOR(OFS_PARM0);
3101         scale = PRVM_G_VECTOR(OFS_PARM2);
3102         flag = (int)PRVM_G_FLOAT(OFS_PARM4);
3103
3104         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3105         {
3106                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3107                 VM_Warning("VM_drawcolorcodedstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3108                 return;
3109         }
3110
3111         if(!scale[0] || !scale[1])
3112         {
3113                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3114                 VM_Warning("VM_drawcolorcodedstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3115                 return;
3116         }
3117
3118         if(pos[2] || scale[2])
3119                 Con_Printf("VM_drawcolorcodedstring: z value%s from %s discarded\n",(pos[2] && scale[2]) ? "s" : " ",((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
3120
3121         color = -1;
3122         DrawQ_String_Font(pos[0], pos[1], string, 0, scale[0], scale[1], 1, 1, 1, PRVM_G_FLOAT(OFS_PARM3), flag, NULL, false, getdrawfont());
3123         PRVM_G_FLOAT(OFS_RETURN) = 1;
3124 }
3125 /*
3126 =========
3127 VM_stringwidth
3128
3129 float   stringwidth(string text, float allowColorCodes, float size)
3130 =========
3131 */
3132 void VM_stringwidth(void)
3133 {
3134         const char  *string;
3135         float sz, mult; // sz is intended font size so we can later add freetype support, mult is font size multiplier in pixels per character cell
3136         int colors;
3137         VM_SAFEPARMCOUNTRANGE(2,3,VM_drawstring);
3138
3139         if(prog->argc == 3)
3140         {
3141                 mult = sz = PRVM_G_FLOAT(OFS_PARM2);
3142         }
3143         else
3144         {
3145                 sz = 8;
3146                 mult = 1;
3147         }
3148
3149         string = PRVM_G_STRING(OFS_PARM0);
3150         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3151
3152         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth_Font(string, 0, !colors, getdrawfont()) * mult; // 1x1 characters, don't actually draw
3153 }
3154 /*
3155 =========
3156 VM_drawpic
3157
3158 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
3159 =========
3160 */
3161 void VM_drawpic(void)
3162 {
3163         const char *picname;
3164         float *size, *pos, *rgb;
3165         int flag;
3166
3167         VM_SAFEPARMCOUNT(6,VM_drawpic);
3168
3169         picname = PRVM_G_STRING(OFS_PARM1);
3170         VM_CheckEmptyString (picname);
3171
3172         // is pic cached ? no function yet for that
3173         if(!1)
3174         {
3175                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3176                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
3177                 return;
3178         }
3179
3180         pos = PRVM_G_VECTOR(OFS_PARM0);
3181         size = PRVM_G_VECTOR(OFS_PARM2);
3182         rgb = PRVM_G_VECTOR(OFS_PARM3);
3183         flag = (int) PRVM_G_FLOAT(OFS_PARM5);
3184
3185         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3186         {
3187                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3188                 VM_Warning("VM_drawpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3189                 return;
3190         }
3191
3192         if(pos[2] || size[2])
3193                 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")));
3194
3195         DrawQ_Pic(pos[0], pos[1], Draw_CachePic (picname), size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
3196         PRVM_G_FLOAT(OFS_RETURN) = 1;
3197 }
3198 /*
3199 =========
3200 VM_drawrotpic
3201
3202 float   drawrotpic(vector position, string pic, vector size, vector org, float angle, vector rgb, float alpha, float flag)
3203 =========
3204 */
3205 void VM_drawrotpic(void)
3206 {
3207         const char *picname;
3208         float *size, *pos, *org, *rgb;
3209         int flag;
3210
3211         VM_SAFEPARMCOUNT(8,VM_drawrotpic);
3212
3213         picname = PRVM_G_STRING(OFS_PARM1);
3214         VM_CheckEmptyString (picname);
3215
3216         // is pic cached ? no function yet for that
3217         if(!1)
3218         {
3219                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3220                 VM_Warning("VM_drawrotpic: %s: %s not cached !\n", PRVM_NAME, picname);
3221                 return;
3222         }
3223
3224         pos = PRVM_G_VECTOR(OFS_PARM0);
3225         size = PRVM_G_VECTOR(OFS_PARM2);
3226         org = PRVM_G_VECTOR(OFS_PARM3);
3227         rgb = PRVM_G_VECTOR(OFS_PARM5);
3228         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3229
3230         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3231         {
3232                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3233                 VM_Warning("VM_drawrotpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3234                 return;
3235         }
3236
3237         if(pos[2] || size[2] || org[2])
3238                 Con_Printf("VM_drawrotpic: z value from pos/size/org discarded\n");
3239
3240         DrawQ_RotPic(pos[0], pos[1], Draw_CachePic(picname), size[0], size[1], org[0], org[1], PRVM_G_FLOAT(OFS_PARM4), rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM6), flag);
3241         PRVM_G_FLOAT(OFS_RETURN) = 1;
3242 }
3243 /*
3244 =========
3245 VM_drawsubpic
3246
3247 float   drawsubpic(vector position, vector size, string pic, vector srcPos, vector srcSize, vector rgb, float alpha, float flag)
3248
3249 =========
3250 */
3251 void VM_drawsubpic(void)
3252 {
3253         const char *picname;
3254         float *size, *pos, *rgb, *srcPos, *srcSize, alpha;
3255         int flag;
3256
3257         VM_SAFEPARMCOUNT(8,VM_drawsubpic);
3258
3259         picname = PRVM_G_STRING(OFS_PARM2);
3260         VM_CheckEmptyString (picname);
3261
3262         // is pic cached ? no function yet for that
3263         if(!1)
3264         {
3265                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3266                 VM_Warning("VM_drawsubpic: %s: %s not cached !\n", PRVM_NAME, picname);
3267                 return;
3268         }
3269
3270         pos = PRVM_G_VECTOR(OFS_PARM0);
3271         size = PRVM_G_VECTOR(OFS_PARM1);
3272         srcPos = PRVM_G_VECTOR(OFS_PARM3);
3273         srcSize = PRVM_G_VECTOR(OFS_PARM4);
3274         rgb = PRVM_G_VECTOR(OFS_PARM5);
3275         alpha = PRVM_G_FLOAT(OFS_PARM6);
3276         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3277
3278         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3279         {
3280                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3281                 VM_Warning("VM_drawsubpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3282                 return;
3283         }
3284
3285         if(pos[2] || size[2])
3286                 Con_Printf("VM_drawsubpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3287
3288         DrawQ_SuperPic(pos[0], pos[1], Draw_CachePic (picname),
3289                 size[0], size[1],
3290                 srcPos[0],              srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3291                 srcPos[0] + srcSize[0], srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3292                 srcPos[0],              srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3293                 srcPos[0] + srcSize[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3294                 flag);
3295         PRVM_G_FLOAT(OFS_RETURN) = 1;
3296 }
3297
3298 /*
3299 =========
3300 VM_drawfill
3301
3302 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
3303 =========
3304 */
3305 void VM_drawfill(void)
3306 {
3307         float *size, *pos, *rgb;
3308         int flag;
3309
3310         VM_SAFEPARMCOUNT(5,VM_drawfill);
3311
3312
3313         pos = PRVM_G_VECTOR(OFS_PARM0);
3314         size = PRVM_G_VECTOR(OFS_PARM1);
3315         rgb = PRVM_G_VECTOR(OFS_PARM2);
3316         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
3317
3318         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3319         {
3320                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3321                 VM_Warning("VM_drawfill: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3322                 return;
3323         }
3324
3325         if(pos[2] || size[2])
3326                 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")));
3327
3328         DrawQ_Fill(pos[0], pos[1], size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
3329         PRVM_G_FLOAT(OFS_RETURN) = 1;
3330 }
3331
3332 /*
3333 =========
3334 VM_drawsetcliparea
3335
3336 drawsetcliparea(float x, float y, float width, float height)
3337 =========
3338 */
3339 void VM_drawsetcliparea(void)
3340 {
3341         float x,y,w,h;
3342         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
3343
3344         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
3345         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
3346         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
3347         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
3348
3349         DrawQ_SetClipArea(x, y, w, h);
3350 }
3351
3352 /*
3353 =========
3354 VM_drawresetcliparea
3355
3356 drawresetcliparea()
3357 =========
3358 */
3359 void VM_drawresetcliparea(void)
3360 {
3361         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
3362
3363         DrawQ_ResetClipArea();
3364 }
3365
3366 /*
3367 =========
3368 VM_getimagesize
3369
3370 vector  getimagesize(string pic)
3371 =========
3372 */
3373 void VM_getimagesize(void)
3374 {
3375         const char *p;
3376         cachepic_t *pic;
3377
3378         VM_SAFEPARMCOUNT(1,VM_getimagesize);
3379
3380         p = PRVM_G_STRING(OFS_PARM0);
3381         VM_CheckEmptyString (p);
3382
3383         pic = Draw_CachePic_Flags (p, CACHEPICFLAG_NOTPERSISTENT);
3384
3385         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
3386         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
3387         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3388 }
3389
3390 /*
3391 =========
3392 VM_keynumtostring
3393
3394 string keynumtostring(float keynum)
3395 =========
3396 */
3397 void VM_keynumtostring (void)
3398 {
3399         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3400
3401         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0)));
3402 }
3403
3404 /*
3405 =========
3406 VM_findkeysforcommand
3407
3408 string  findkeysforcommand(string command)
3409
3410 the returned string is an altstring
3411 =========
3412 */
3413 #define NUMKEYS 5 // TODO: merge the constant in keys.c with this one somewhen
3414
3415 void M_FindKeysForCommand(const char *command, int *keys);
3416 void VM_findkeysforcommand(void)
3417 {
3418         const char *cmd;
3419         char ret[VM_STRINGTEMP_LENGTH];
3420         int keys[NUMKEYS];
3421         int i;
3422
3423         VM_SAFEPARMCOUNT(1, VM_findkeysforcommand);
3424
3425         cmd = PRVM_G_STRING(OFS_PARM0);
3426
3427         VM_CheckEmptyString(cmd);
3428
3429         M_FindKeysForCommand(cmd, keys);
3430
3431         ret[0] = 0;
3432         for(i = 0; i < NUMKEYS; i++)
3433                 strlcat(ret, va(" \'%i\'", keys[i]), sizeof(ret));
3434
3435         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(ret);
3436 }
3437
3438 /*
3439 =========
3440 VM_stringtokeynum
3441
3442 float stringtokeynum(string key)
3443 =========
3444 */
3445 void VM_stringtokeynum (void)
3446 {
3447         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
3448
3449         PRVM_G_INT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3450 }
3451
3452 // CL_Video interface functions
3453
3454 /*
3455 ========================
3456 VM_cin_open
3457
3458 float cin_open(string file, string name)
3459 ========================
3460 */
3461 void VM_cin_open( void )
3462 {
3463         const char *file;
3464         const char *name;
3465
3466         VM_SAFEPARMCOUNT( 2, VM_cin_open );
3467
3468         file = PRVM_G_STRING( OFS_PARM0 );
3469         name = PRVM_G_STRING( OFS_PARM1 );
3470
3471         VM_CheckEmptyString( file );
3472     VM_CheckEmptyString( name );
3473
3474         if( CL_OpenVideo( file, name, MENUOWNER ) )
3475                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
3476         else
3477                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3478 }
3479
3480 /*
3481 ========================
3482 VM_cin_close
3483
3484 void cin_close(string name)
3485 ========================
3486 */
3487 void VM_cin_close( void )
3488 {
3489         const char *name;
3490
3491         VM_SAFEPARMCOUNT( 1, VM_cin_close );
3492
3493         name = PRVM_G_STRING( OFS_PARM0 );
3494         VM_CheckEmptyString( name );
3495
3496         CL_CloseVideo( CL_GetVideoByName( name ) );
3497 }
3498
3499 /*
3500 ========================
3501 VM_cin_setstate
3502 void cin_setstate(string name, float type)
3503 ========================
3504 */
3505 void VM_cin_setstate( void )
3506 {
3507         const char *name;
3508         clvideostate_t  state;
3509         clvideo_t               *video;
3510
3511         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
3512
3513         name = PRVM_G_STRING( OFS_PARM0 );
3514         VM_CheckEmptyString( name );
3515
3516         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
3517
3518         video = CL_GetVideoByName( name );
3519         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
3520                 CL_SetVideoState( video, state );
3521 }
3522
3523 /*
3524 ========================
3525 VM_cin_getstate
3526
3527 float cin_getstate(string name)
3528 ========================
3529 */
3530 void VM_cin_getstate( void )
3531 {
3532         const char *name;
3533         clvideo_t               *video;
3534
3535         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
3536
3537         name = PRVM_G_STRING( OFS_PARM0 );
3538         VM_CheckEmptyString( name );
3539
3540         video = CL_GetVideoByName( name );
3541         if( video )
3542                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
3543         else
3544                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3545 }
3546
3547 /*
3548 ========================
3549 VM_cin_restart
3550
3551 void cin_restart(string name)
3552 ========================
3553 */
3554 void VM_cin_restart( void )
3555 {
3556         const char *name;
3557         clvideo_t               *video;
3558
3559         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
3560
3561         name = PRVM_G_STRING( OFS_PARM0 );
3562         VM_CheckEmptyString( name );
3563
3564         video = CL_GetVideoByName( name );
3565         if( video )
3566                 CL_RestartVideo( video );
3567 }
3568
3569 /*
3570 ========================
3571 VM_Gecko_Init
3572 ========================
3573 */
3574 void VM_Gecko_Init( void ) {
3575         // the prog struct is memset to 0 by Initprog? [12/6/2007 Black]
3576         // FIXME: remove the other _Init functions then, too? [12/6/2007 Black]
3577 }
3578
3579 /*
3580 ========================
3581 VM_Gecko_Destroy
3582 ========================
3583 */
3584 void VM_Gecko_Destroy( void ) {
3585         int i;
3586         for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
3587                 clgecko_t **instance = &prog->opengeckoinstances[ i ];
3588                 if( *instance ) {
3589                         CL_Gecko_DestroyBrowser( *instance );
3590                 }
3591                 *instance = NULL;
3592         }
3593 }
3594
3595 /*
3596 ========================
3597 VM_gecko_create
3598
3599 float[bool] gecko_create( string name )
3600 ========================
3601 */
3602 void VM_gecko_create( void ) {
3603         const char *name;
3604         int i;
3605         clgecko_t *instance;
3606         
3607         VM_SAFEPARMCOUNT( 1, VM_gecko_create );
3608
3609         name = PRVM_G_STRING( OFS_PARM0 );
3610         VM_CheckEmptyString( name );
3611
3612         // find an empty slot for this gecko browser..
3613         for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
3614                 if( prog->opengeckoinstances[ i ] == NULL ) {
3615                         break;
3616                 }
3617         }
3618         if( i == PRVM_MAX_GECKOINSTANCES ) {
3619                         VM_Warning("VM_gecko_create: %s ran out of gecko handles (%i)\n", PRVM_NAME, PRVM_MAX_GECKOINSTANCES);
3620                         PRVM_G_FLOAT( OFS_RETURN ) = 0;
3621                         return;
3622         }
3623
3624         instance = prog->opengeckoinstances[ i ] = CL_Gecko_CreateBrowser( name, PRVM_GetProgNr() );
3625    if( !instance ) {
3626                 // TODO: error handling [12/3/2007 Black]
3627                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3628                 return;
3629         }
3630         PRVM_G_FLOAT( OFS_RETURN ) = 1;
3631 }
3632
3633 /*
3634 ========================
3635 VM_gecko_destroy
3636
3637 void gecko_destroy( string name )
3638 ========================
3639 */
3640 void VM_gecko_destroy( void ) {
3641         const char *name;
3642         clgecko_t *instance;
3643
3644         VM_SAFEPARMCOUNT( 1, VM_gecko_destroy );
3645
3646         name = PRVM_G_STRING( OFS_PARM0 );
3647         VM_CheckEmptyString( name );
3648         instance = CL_Gecko_FindBrowser( name );
3649         if( !instance ) {
3650                 return;
3651         }
3652         CL_Gecko_DestroyBrowser( instance );
3653 }
3654
3655 /*
3656 ========================
3657 VM_gecko_navigate
3658
3659 void gecko_navigate( string name, string URI )
3660 ========================
3661 */
3662 void VM_gecko_navigate( void ) {
3663         const char *name;
3664         const char *URI;
3665         clgecko_t *instance;
3666
3667         VM_SAFEPARMCOUNT( 2, VM_gecko_navigate );
3668
3669         name = PRVM_G_STRING( OFS_PARM0 );
3670         URI = PRVM_G_STRING( OFS_PARM1 );
3671         VM_CheckEmptyString( name );
3672         VM_CheckEmptyString( URI );
3673
3674    instance = CL_Gecko_FindBrowser( name );
3675         if( !instance ) {
3676                 return;
3677         }
3678         CL_Gecko_NavigateToURI( instance, URI );
3679 }
3680
3681 /*
3682 ========================
3683 VM_gecko_keyevent
3684
3685 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
3686 ========================
3687 */
3688 void VM_gecko_keyevent( void ) {
3689         const char *name;
3690         unsigned int key;
3691         clgecko_buttoneventtype_t eventtype;
3692         clgecko_t *instance;
3693
3694         VM_SAFEPARMCOUNT( 3, VM_gecko_keyevent );
3695
3696         name = PRVM_G_STRING( OFS_PARM0 );
3697         VM_CheckEmptyString( name );
3698         key = (unsigned int) PRVM_G_FLOAT( OFS_PARM1 );
3699         switch( (unsigned int) PRVM_G_FLOAT( OFS_PARM2 ) ) {
3700         case 0:
3701                 eventtype = CLG_BET_DOWN;
3702                 break;
3703         case 1:
3704                 eventtype = CLG_BET_UP;
3705                 break;
3706         case 2:
3707                 eventtype = CLG_BET_PRESS;
3708                 break;
3709         case 3:
3710                 eventtype = CLG_BET_DOUBLECLICK;
3711                 break;
3712         default:
3713                 // TODO: console printf? [12/3/2007 Black]
3714                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3715                 return;
3716         }
3717
3718         instance = CL_Gecko_FindBrowser( name );
3719         if( !instance ) {
3720                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3721                 return;
3722         }
3723
3724         PRVM_G_FLOAT( OFS_RETURN ) = (CL_Gecko_Event_Key( instance, (keynum_t) key, eventtype ) == true);
3725 }
3726
3727 /*
3728 ========================
3729 VM_gecko_movemouse
3730
3731 void gecko_mousemove( string name, float x, float y )
3732 ========================
3733 */
3734 void VM_gecko_movemouse( void ) {
3735         const char *name;
3736         float x, y;
3737         clgecko_t *instance;
3738
3739         VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
3740
3741         name = PRVM_G_STRING( OFS_PARM0 );
3742         VM_CheckEmptyString( name );
3743         x = PRVM_G_FLOAT( OFS_PARM1 );
3744         y = PRVM_G_FLOAT( OFS_PARM2 );
3745         
3746         instance = CL_Gecko_FindBrowser( name );
3747         if( !instance ) {
3748                 return;
3749         }
3750         CL_Gecko_Event_CursorMove( instance, x, y );
3751 }
3752
3753
3754 /*
3755 ========================
3756 VM_gecko_resize
3757
3758 void gecko_resize( string name, float w, float h )
3759 ========================
3760 */
3761 void VM_gecko_resize( void ) {
3762         const char *name;
3763         float w, h;
3764         clgecko_t *instance;
3765
3766         VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
3767
3768         name = PRVM_G_STRING( OFS_PARM0 );
3769         VM_CheckEmptyString( name );
3770         w = PRVM_G_FLOAT( OFS_PARM1 );
3771         h = PRVM_G_FLOAT( OFS_PARM2 );
3772         
3773         instance = CL_Gecko_FindBrowser( name );
3774         if( !instance ) {
3775                 return;
3776         }
3777         CL_Gecko_Resize( instance, (int) w, (int) h );
3778 }
3779
3780
3781 /*
3782 ========================
3783 VM_gecko_get_texture_extent
3784
3785 vector gecko_get_texture_extent( string name )
3786 ========================
3787 */
3788 void VM_gecko_get_texture_extent( void ) {
3789         const char *name;
3790         clgecko_t *instance;
3791
3792         VM_SAFEPARMCOUNT( 1, VM_gecko_movemouse );
3793
3794         name = PRVM_G_STRING( OFS_PARM0 );
3795         VM_CheckEmptyString( name );
3796         
3797         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3798         instance = CL_Gecko_FindBrowser( name );
3799         if( !instance ) {
3800                 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
3801                 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
3802                 return;
3803         }
3804         CL_Gecko_GetTextureExtent( instance, 
3805                 PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_RETURN)+1 );
3806 }
3807
3808
3809
3810 /*
3811 ==============
3812 VM_makevectors
3813
3814 Writes new values for v_forward, v_up, and v_right based on angles
3815 void makevectors(vector angle)
3816 ==============
3817 */
3818 void VM_makevectors (void)
3819 {
3820         prvm_eval_t *valforward, *valright, *valup;
3821         valforward = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_forward);
3822         valright = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_right);
3823         valup = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_up);
3824         if (!valforward || !valright || !valup)
3825         {
3826                 VM_Warning("makevectors: could not find v_forward, v_right, or v_up global variables\n");
3827                 return;
3828         }
3829         VM_SAFEPARMCOUNT(1, VM_makevectors);
3830         AngleVectors (PRVM_G_VECTOR(OFS_PARM0), valforward->vector, valright->vector, valup->vector);
3831 }
3832
3833 /*
3834 ==============
3835 VM_vectorvectors
3836
3837 Writes new values for v_forward, v_up, and v_right based on the given forward vector
3838 vectorvectors(vector)
3839 ==============
3840 */
3841 void VM_vectorvectors (void)
3842 {
3843         prvm_eval_t *valforward, *valright, *valup;
3844         valforward = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_forward);
3845         valright = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_right);
3846         valup = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_up);
3847         if (!valforward || !valright || !valup)
3848         {
3849                 VM_Warning("vectorvectors: could not find v_forward, v_right, or v_up global variables\n");
3850                 return;
3851         }
3852         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
3853         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), valforward->vector);
3854         VectorVectors(valforward->vector, valright->vector, valup->vector);
3855 }
3856
3857 /*
3858 ========================
3859 VM_drawline
3860
3861 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
3862 ========================
3863 */
3864 void VM_drawline (void)
3865 {
3866         float   *c1, *c2, *rgb;
3867         float   alpha, width;
3868         unsigned char   flags;
3869
3870         VM_SAFEPARMCOUNT(6, VM_drawline);
3871         width   = PRVM_G_FLOAT(OFS_PARM0);
3872         c1              = PRVM_G_VECTOR(OFS_PARM1);
3873         c2              = PRVM_G_VECTOR(OFS_PARM2);
3874         rgb             = PRVM_G_VECTOR(OFS_PARM3);
3875         alpha   = PRVM_G_FLOAT(OFS_PARM4);
3876         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
3877         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
3878 }
3879
3880 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3881 void VM_bitshift (void)
3882 {
3883         int n1, n2;
3884         VM_SAFEPARMCOUNT(2, VM_bitshift);
3885
3886         n1 = (int)fabs((float)((int)PRVM_G_FLOAT(OFS_PARM0)));
3887         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
3888         if(!n1)
3889                 PRVM_G_FLOAT(OFS_RETURN) = n1;
3890         else
3891         if(n2 < 0)
3892                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3893         else
3894                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3895 }
3896
3897 ////////////////////////////////////////
3898 // AltString functions
3899 ////////////////////////////////////////
3900
3901 /*
3902 ========================
3903 VM_altstr_count
3904
3905 float altstr_count(string)
3906 ========================
3907 */
3908 void VM_altstr_count( void )
3909 {
3910         const char *altstr, *pos;
3911         int     count;
3912
3913         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3914
3915         altstr = PRVM_G_STRING( OFS_PARM0 );
3916         //VM_CheckEmptyString( altstr );
3917
3918         for( count = 0, pos = altstr ; *pos ; pos++ ) {
3919                 if( *pos == '\\' ) {
3920                         if( !*++pos ) {
3921                                 break;
3922                         }
3923                 } else if( *pos == '\'' ) {
3924                         count++;
3925                 }
3926         }
3927
3928         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
3929 }
3930
3931 /*
3932 ========================
3933 VM_altstr_prepare
3934
3935 string altstr_prepare(string)
3936 ========================
3937 */
3938 void VM_altstr_prepare( void )
3939 {
3940         char *out;
3941         const char *instr, *in;
3942         int size;
3943         char outstr[VM_STRINGTEMP_LENGTH];
3944
3945         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3946
3947         instr = PRVM_G_STRING( OFS_PARM0 );
3948
3949         for( out = outstr, in = instr, size = sizeof(outstr) - 1 ; size && *in ; size--, in++, out++ )
3950                 if( *in == '\'' ) {
3951                         *out++ = '\\';
3952                         *out = '\'';
3953                         size--;
3954                 } else
3955                         *out = *in;
3956         *out = 0;
3957
3958         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
3959 }
3960
3961 /*
3962 ========================
3963 VM_altstr_get
3964
3965 string altstr_get(string, float)
3966 ========================
3967 */
3968 void VM_altstr_get( void )
3969 {
3970         const char *altstr, *pos;
3971         char *out;
3972         int count, size;
3973         char outstr[VM_STRINGTEMP_LENGTH];
3974
3975         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3976
3977         altstr = PRVM_G_STRING( OFS_PARM0 );
3978
3979         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3980         count = count * 2 + 1;
3981
3982         for( pos = altstr ; *pos && count ; pos++ )
3983                 if( *pos == '\\' ) {
3984                         if( !*++pos )
3985                                 break;
3986                 } else if( *pos == '\'' )
3987                         count--;
3988
3989         if( !*pos ) {
3990                 PRVM_G_INT( OFS_RETURN ) = 0;
3991                 return;
3992         }
3993
3994         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
3995                 if( *pos == '\\' ) {
3996                         if( !*++pos )
3997                                 break;
3998                         *out = *pos;
3999                         size--;
4000                 } else if( *pos == '\'' )
4001                         break;
4002                 else
4003                         *out = *pos;
4004
4005         *out = 0;
4006         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4007 }
4008
4009 /*
4010 ========================
4011 VM_altstr_set
4012
4013 string altstr_set(string altstr, float num, string set)
4014 ========================
4015 */
4016 void VM_altstr_set( void )
4017 {
4018     int num;
4019         const char *altstr, *str;
4020         const char *in;
4021         char *out;
4022         char outstr[VM_STRINGTEMP_LENGTH];
4023
4024         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
4025
4026         altstr = PRVM_G_STRING( OFS_PARM0 );
4027
4028         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4029
4030         str = PRVM_G_STRING( OFS_PARM2 );
4031
4032         out = outstr;
4033         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
4034                 if( *in == '\\' ) {
4035                         if( !*++in ) {
4036                                 break;
4037                         }
4038                 } else if( *in == '\'' ) {
4039                         num--;
4040                 }
4041
4042         // copy set in
4043         for( ; *str; *out++ = *str++ );
4044         // now jump over the old content
4045         for( ; *in ; in++ )
4046                 if( *in == '\'' || (*in == '\\' && !*++in) )
4047                         break;
4048
4049         strlcpy(out, in, outstr + sizeof(outstr) - out);
4050         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4051 }
4052
4053 /*
4054 ========================
4055 VM_altstr_ins
4056 insert after num
4057 string  altstr_ins(string altstr, float num, string set)
4058 ========================
4059 */
4060 void VM_altstr_ins(void)
4061 {
4062         int num;
4063         const char *setstr;
4064         const char *set;
4065         const char *instr;
4066         const char *in;
4067         char *out;
4068         char outstr[VM_STRINGTEMP_LENGTH];
4069
4070         VM_SAFEPARMCOUNT(3, VM_altstr_ins);
4071
4072         in = instr = PRVM_G_STRING( OFS_PARM0 );
4073         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4074         set = setstr = PRVM_G_STRING( OFS_PARM2 );
4075
4076         out = outstr;
4077         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
4078                 if( *in == '\\' ) {
4079                         if( !*++in ) {
4080                                 break;
4081                         }
4082                 } else if( *in == '\'' ) {
4083                         num--;
4084                 }
4085
4086         *out++ = '\'';
4087         for( ; *set ; *out++ = *set++ );
4088         *out++ = '\'';
4089
4090         strlcpy(out, in, outstr + sizeof(outstr) - out);
4091         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4092 }
4093
4094
4095 ////////////////////////////////////////
4096 // BufString functions
4097 ////////////////////////////////////////
4098 //[515]: string buffers support
4099
4100 static size_t stringbuffers_sortlength;
4101
4102 static void BufStr_Expand(prvm_stringbuffer_t *stringbuffer, int strindex)
4103 {
4104         if (stringbuffer->max_strings <= strindex)
4105         {
4106                 char **oldstrings = stringbuffer->strings;
4107                 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
4108                 while (stringbuffer->max_strings <= strindex)
4109                         stringbuffer->max_strings *= 2;
4110                 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
4111                 if (stringbuffer->num_strings > 0)
4112                         memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
4113                 if (oldstrings)
4114                         Mem_Free(oldstrings);
4115         }
4116 }
4117
4118 static void BufStr_Shrink(prvm_stringbuffer_t *stringbuffer)
4119 {
4120         // reduce num_strings if there are empty string slots at the end
4121         while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
4122                 stringbuffer->num_strings--;
4123
4124         // if empty, free the string pointer array
4125         if (stringbuffer->num_strings == 0)
4126         {
4127                 stringbuffer->max_strings = 0;
4128                 if (stringbuffer->strings)
4129                         Mem_Free(stringbuffer->strings);
4130                 stringbuffer->strings = NULL;
4131         }
4132 }
4133
4134 static int BufStr_SortStringsUP (const void *in1, const void *in2)
4135 {
4136         const char *a, *b;
4137         a = *((const char **) in1);
4138         b = *((const char **) in2);
4139         if(!a[0])       return 1;
4140         if(!b[0])       return -1;
4141         return strncmp(a, b, stringbuffers_sortlength);
4142 }
4143
4144 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
4145 {
4146         const char *a, *b;
4147         a = *((const char **) in1);
4148         b = *((const char **) in2);
4149         if(!a[0])       return 1;
4150         if(!b[0])       return -1;
4151         return strncmp(b, a, stringbuffers_sortlength);
4152 }
4153
4154 /*
4155 ========================
4156 VM_buf_create
4157 creates new buffer, and returns it's index, returns -1 if failed
4158 float buf_create(void) = #460;
4159 ========================
4160 */
4161 void VM_buf_create (void)
4162 {
4163         prvm_stringbuffer_t *stringbuffer;
4164         int i;
4165         VM_SAFEPARMCOUNT(0, VM_buf_create);
4166         stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
4167         for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
4168         stringbuffer->origin = PRVM_AllocationOrigin();
4169         PRVM_G_FLOAT(OFS_RETURN) = i;
4170 }
4171
4172 /*
4173 ========================
4174 VM_buf_del
4175 deletes buffer and all strings in it
4176 void buf_del(float bufhandle) = #461;
4177 ========================
4178 */
4179 void VM_buf_del (void)
4180 {
4181         prvm_stringbuffer_t *stringbuffer;
4182         VM_SAFEPARMCOUNT(1, VM_buf_del);
4183         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4184         if (stringbuffer)
4185         {
4186                 int i;
4187                 for (i = 0;i < stringbuffer->num_strings;i++)
4188                         if (stringbuffer->strings[i])
4189                                 Mem_Free(stringbuffer->strings[i]);
4190                 if (stringbuffer->strings)
4191                         Mem_Free(stringbuffer->strings);
4192                 if(stringbuffer->origin)
4193                         PRVM_Free((char *)stringbuffer->origin);
4194                 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
4195         }
4196         else
4197         {
4198                 VM_Warning("VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4199                 return;
4200         }
4201 }
4202
4203 /*
4204 ========================
4205 VM_buf_getsize
4206 how many strings are stored in buffer
4207 float buf_getsize(float bufhandle) = #462;
4208 ========================
4209 */
4210 void VM_buf_getsize (void)
4211 {
4212         prvm_stringbuffer_t *stringbuffer;
4213         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4214
4215         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4216         if(!stringbuffer)
4217         {
4218                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4219                 VM_Warning("VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4220                 return;
4221         }
4222         else
4223                 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4224 }
4225
4226 /*
4227 ========================
4228 VM_buf_copy
4229 copy all content from one buffer to another, make sure it exists
4230 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4231 ========================
4232 */
4233 void VM_buf_copy (void)
4234 {
4235         prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4236         int i;
4237         VM_SAFEPARMCOUNT(2, VM_buf_copy);
4238
4239         srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4240         if(!srcstringbuffer)
4241         {
4242                 VM_Warning("VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4243                 return;
4244         }
4245         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4246         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4247         {
4248                 VM_Warning("VM_buf_copy: source == destination (%i) in %s\n", i, PRVM_NAME);
4249                 return;
4250         }
4251         dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4252         if(!dststringbuffer)
4253         {
4254                 VM_Warning("VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
4255                 return;
4256         }
4257
4258         for (i = 0;i < dststringbuffer->num_strings;i++)
4259                 if (dststringbuffer->strings[i])
4260                         Mem_Free(dststringbuffer->strings[i]);
4261         if (dststringbuffer->strings)
4262                 Mem_Free(dststringbuffer->strings);
4263         *dststringbuffer = *srcstringbuffer;
4264         if (dststringbuffer->max_strings)
4265                 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4266
4267         for (i = 0;i < dststringbuffer->num_strings;i++)
4268         {
4269                 if (srcstringbuffer->strings[i])
4270                 {
4271                         size_t stringlen;
4272                         stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4273                         dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4274                         memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4275                 }
4276         }
4277 }
4278
4279 /*
4280 ========================
4281 VM_buf_sort
4282 sort buffer by beginnings of strings (cmplength defaults it's length)
4283 "backward == TRUE" means that sorting goes upside-down
4284 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4285 ========================
4286 */
4287 void VM_buf_sort (void)
4288 {
4289         prvm_stringbuffer_t *stringbuffer;
4290         VM_SAFEPARMCOUNT(3, VM_buf_sort);
4291
4292         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4293         if(!stringbuffer)
4294         {
4295                 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4296                 return;
4297         }
4298         if(stringbuffer->num_strings <= 0)
4299         {
4300                 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4301                 return;
4302         }
4303         stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4304         if(stringbuffers_sortlength <= 0)
4305                 stringbuffers_sortlength = 0x7FFFFFFF;
4306
4307         if(!PRVM_G_FLOAT(OFS_PARM2))
4308                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4309         else
4310                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4311
4312         BufStr_Shrink(stringbuffer);
4313 }
4314
4315 /*
4316 ========================
4317 VM_buf_implode
4318 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4319 string buf_implode(float bufhandle, string glue) = #465;
4320 ========================
4321 */
4322 void VM_buf_implode (void)
4323 {
4324         prvm_stringbuffer_t *stringbuffer;
4325         char                    k[VM_STRINGTEMP_LENGTH];
4326         const char              *sep;
4327         int                             i;
4328         size_t                  l;
4329         VM_SAFEPARMCOUNT(2, VM_buf_implode);
4330
4331         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4332         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4333         if(!stringbuffer)
4334         {
4335                 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4336                 return;
4337         }
4338         if(!stringbuffer->num_strings)
4339                 return;
4340         sep = PRVM_G_STRING(OFS_PARM1);
4341         k[0] = 0;
4342         for(l = i = 0;i < stringbuffer->num_strings;i++)
4343         {
4344                 if(stringbuffer->strings[i])
4345                 {
4346                         l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4347                         if (l >= sizeof(k) - 1)
4348                                 break;
4349                         strlcat(k, sep, sizeof(k));
4350                         strlcat(k, stringbuffer->strings[i], sizeof(k));
4351                 }
4352         }
4353         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(k);
4354 }
4355
4356 /*
4357 ========================
4358 VM_bufstr_get
4359 get a string from buffer, returns tempstring, dont str_unzone it!
4360 string bufstr_get(float bufhandle, float string_index) = #465;
4361 ========================
4362 */
4363 void VM_bufstr_get (void)
4364 {
4365         prvm_stringbuffer_t *stringbuffer;
4366         int                             strindex;
4367         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4368
4369         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4370         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4371         if(!stringbuffer)
4372         {
4373                 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4374                 return;
4375         }
4376         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4377         if (strindex < 0)
4378         {
4379                 VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
4380                 return;
4381         }
4382         if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4383                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(stringbuffer->strings[strindex]);
4384 }
4385
4386 /*
4387 ========================
4388 VM_bufstr_set
4389 copies a string into selected slot of buffer
4390 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4391 ========================
4392 */
4393 void VM_bufstr_set (void)
4394 {
4395         int                             strindex;
4396         prvm_stringbuffer_t *stringbuffer;
4397         const char              *news;
4398
4399         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4400
4401         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4402         if(!stringbuffer)
4403         {
4404                 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4405                 return;
4406         }
4407         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4408         if(strindex < 0 || strindex >= 1000000) // huge number of strings
4409         {
4410                 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
4411                 return;
4412         }
4413
4414         BufStr_Expand(stringbuffer, strindex);
4415         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4416
4417         if(stringbuffer->strings[strindex])
4418                 Mem_Free(stringbuffer->strings[strindex]);
4419         stringbuffer->strings[strindex] = NULL;
4420
4421         news = PRVM_G_STRING(OFS_PARM2);
4422         if (news && news[0])
4423         {
4424                 size_t alloclen = strlen(news) + 1;
4425                 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4426                 memcpy(stringbuffer->strings[strindex], news, alloclen);
4427         }
4428
4429         BufStr_Shrink(stringbuffer);
4430 }
4431
4432 /*
4433 ========================
4434 VM_bufstr_add
4435 adds string to buffer in first free slot and returns its index
4436 "order == TRUE" means that string will be added after last "full" slot
4437 float bufstr_add(float bufhandle, string str, float order) = #467;
4438 ========================
4439 */
4440 void VM_bufstr_add (void)
4441 {
4442         int                             order, strindex;
4443         prvm_stringbuffer_t *stringbuffer;
4444         const char              *string;
4445         size_t                  alloclen;
4446
4447         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4448
4449         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4450         PRVM_G_FLOAT(OFS_RETURN) = -1;
4451         if(!stringbuffer)
4452         {
4453                 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4454                 return;
4455         }
4456         string = PRVM_G_STRING(OFS_PARM1);
4457         if(!string || !string[0])
4458         {
4459                 VM_Warning("VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4460                 return;
4461         }
4462         order = (int)PRVM_G_FLOAT(OFS_PARM2);
4463         if(order)
4464                 strindex = stringbuffer->num_strings;
4465         else
4466                 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4467                         if (stringbuffer->strings[strindex] == NULL)
4468                                 break;
4469
4470         BufStr_Expand(stringbuffer, strindex);
4471
4472         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4473         alloclen = strlen(string) + 1;
4474         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4475         memcpy(stringbuffer->strings[strindex], string, alloclen);
4476
4477         PRVM_G_FLOAT(OFS_RETURN) = strindex;
4478 }
4479
4480 /*
4481 ========================
4482 VM_bufstr_free
4483 delete string from buffer
4484 void bufstr_free(float bufhandle, float string_index) = #468;
4485 ========================
4486 */
4487 void VM_bufstr_free (void)
4488 {
4489         int                             i;
4490         prvm_stringbuffer_t     *stringbuffer;
4491         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4492
4493         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4494         if(!stringbuffer)
4495         {
4496                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4497                 return;
4498         }
4499         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4500         if(i < 0)
4501         {
4502                 VM_Warning("VM_bufstr_free: invalid string index %i used in %s\n", i, PRVM_NAME);
4503                 return;
4504         }
4505
4506         if (i < stringbuffer->num_strings)
4507         {
4508                 if(stringbuffer->strings[i])
4509                         Mem_Free(stringbuffer->strings[i]);
4510                 stringbuffer->strings[i] = NULL;
4511         }
4512
4513         BufStr_Shrink(stringbuffer);
4514 }
4515
4516
4517
4518
4519
4520
4521
4522 void VM_buf_cvarlist(void)
4523 {
4524         cvar_t *cvar;
4525         const char *partial, *antipartial;
4526         size_t len, antilen;
4527         size_t alloclen;
4528         qboolean ispattern, antiispattern;
4529         int n;
4530         prvm_stringbuffer_t     *stringbuffer;
4531         VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
4532
4533         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4534         if(!stringbuffer)
4535         {
4536                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4537                 return;
4538         }
4539
4540         partial = PRVM_G_STRING(OFS_PARM1);
4541         if(!partial)
4542                 len = 0;
4543         else
4544                 len = strlen(partial);
4545
4546         if(prog->argc == 3)
4547                 antipartial = PRVM_G_STRING(OFS_PARM2);
4548         else
4549                 antipartial = NULL;
4550         if(!antipartial)
4551                 antilen = 0;
4552         else
4553                 antilen = strlen(antipartial);
4554         
4555         for (n = 0;n < stringbuffer->num_strings;n++)
4556                 if (stringbuffer->strings[n])
4557                         Mem_Free(stringbuffer->strings[n]);
4558         if (stringbuffer->strings)
4559                 Mem_Free(stringbuffer->strings);
4560         stringbuffer->strings = NULL;
4561
4562         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
4563         antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
4564
4565         n = 0;
4566         for(cvar = cvar_vars; cvar; cvar = cvar->next)
4567         {
4568                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4569                         continue;
4570
4571                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4572                         continue;
4573
4574                 ++n;
4575         }
4576
4577         stringbuffer->max_strings = stringbuffer->num_strings = n;
4578         if (stringbuffer->max_strings)
4579                 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
4580         
4581         n = 0;
4582         for(cvar = cvar_vars; cvar; cvar = cvar->next)
4583         {
4584                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4585                         continue;
4586
4587                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4588                         continue;
4589
4590                 alloclen = strlen(cvar->name) + 1;
4591                 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4592                 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
4593
4594                 ++n;
4595         }
4596 }
4597
4598
4599
4600
4601 //=============
4602
4603 /*
4604 ==============
4605 VM_changeyaw
4606
4607 This was a major timewaster in progs, so it was converted to C
4608 ==============
4609 */
4610 void VM_changeyaw (void)
4611 {
4612         prvm_edict_t            *ent;
4613         float           ideal, current, move, speed;
4614
4615         // this is called (VERY HACKISHLY) by SV_MoveToGoal, so it can not use any
4616         // parameters because they are the parameters to SV_MoveToGoal, not this
4617         //VM_SAFEPARMCOUNT(0, VM_changeyaw);
4618
4619         ent = PRVM_PROG_TO_EDICT(PRVM_GLOBALFIELDVALUE(prog->globaloffsets.self)->edict);
4620         if (ent == prog->edicts)
4621         {
4622                 VM_Warning("changeyaw: can not modify world entity\n");
4623                 return;
4624         }
4625         if (ent->priv.server->free)
4626         {
4627                 VM_Warning("changeyaw: can not modify free entity\n");
4628                 return;
4629         }
4630         if (prog->fieldoffsets.angles < 0 || prog->fieldoffsets.ideal_yaw < 0 || prog->fieldoffsets.yaw_speed < 0)
4631         {
4632                 VM_Warning("changeyaw: angles, ideal_yaw, or yaw_speed field(s) not found\n");
4633                 return;
4634         }
4635         current = ANGLEMOD(PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[1]);
4636         ideal = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.ideal_yaw)->_float;
4637         speed = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.yaw_speed)->_float;
4638
4639         if (current == ideal)
4640                 return;
4641         move = ideal - current;
4642         if (ideal > current)
4643         {
4644                 if (move >= 180)
4645                         move = move - 360;
4646         }
4647         else
4648         {
4649                 if (move <= -180)
4650                         move = move + 360;
4651         }
4652         if (move > 0)
4653         {
4654                 if (move > speed)
4655                         move = speed;
4656         }
4657         else
4658         {
4659                 if (move < -speed)
4660                         move = -speed;
4661         }
4662
4663         PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[1] = ANGLEMOD (current + move);
4664 }
4665
4666 /*
4667 ==============
4668 VM_changepitch
4669 ==============
4670 */
4671 void VM_changepitch (void)
4672 {
4673         prvm_edict_t            *ent;
4674         float           ideal, current, move, speed;
4675
4676         VM_SAFEPARMCOUNT(1, VM_changepitch);
4677
4678         ent = PRVM_G_EDICT(OFS_PARM0);
4679         if (ent == prog->edicts)
4680         {
4681                 VM_Warning("changepitch: can not modify world entity\n");
4682                 return;
4683         }
4684         if (ent->priv.server->free)
4685         {
4686                 VM_Warning("changepitch: can not modify free entity\n");
4687                 return;
4688         }
4689         if (prog->fieldoffsets.angles < 0 || prog->fieldoffsets.idealpitch < 0 || prog->fieldoffsets.pitch_speed < 0)
4690         {
4691                 VM_Warning("changepitch: angles, idealpitch, or pitch_speed field(s) not found\n");
4692                 return;
4693         }
4694         current = ANGLEMOD(PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[0]);
4695         ideal = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.idealpitch)->_float;
4696         speed = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.pitch_speed)->_float;
4697
4698         if (current == ideal)
4699                 return;
4700         move = ideal - current;
4701         if (ideal > current)
4702         {
4703                 if (move >= 180)
4704                         move = move - 360;
4705         }
4706         else
4707         {
4708                 if (move <= -180)
4709                         move = move + 360;
4710         }
4711         if (move > 0)
4712         {
4713                 if (move > speed)
4714                         move = speed;
4715         }
4716         else
4717         {
4718                 if (move < -speed)
4719                         move = -speed;
4720         }
4721
4722         PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[0] = ANGLEMOD (current + move);
4723 }
4724
4725
4726 void VM_uncolorstring (void)
4727 {
4728         char szNewString[VM_STRINGTEMP_LENGTH];
4729         const char *szString;
4730
4731         // Prepare Strings
4732         VM_SAFEPARMCOUNT(1, VM_uncolorstring);
4733         szString = PRVM_G_STRING(OFS_PARM0);
4734         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
4735         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
4736         
4737 }
4738
4739 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
4740 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
4741 void VM_strstrofs (void)
4742 {
4743         const char *instr, *match;
4744         int firstofs;
4745         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
4746         instr = PRVM_G_STRING(OFS_PARM0);
4747         match = PRVM_G_STRING(OFS_PARM1);
4748         firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
4749
4750         if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
4751         {
4752                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4753                 return;
4754         }
4755
4756         match = strstr(instr+firstofs, match);
4757         if (!match)
4758                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4759         else
4760                 PRVM_G_FLOAT(OFS_RETURN) = match - instr;
4761 }
4762
4763 //#222 string(string s, float index) str2chr (FTE_STRINGS)
4764 void VM_str2chr (void)
4765 {
4766         const char *s;
4767         VM_SAFEPARMCOUNT(2, VM_str2chr);
4768         s = PRVM_G_STRING(OFS_PARM0);
4769         if((unsigned)PRVM_G_FLOAT(OFS_PARM1) < strlen(s))
4770                 PRVM_G_FLOAT(OFS_RETURN) = (unsigned char)s[(unsigned)PRVM_G_FLOAT(OFS_PARM1)];
4771         else
4772                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4773 }
4774
4775 //#223 string(float c, ...) chr2str (FTE_STRINGS)
4776 void VM_chr2str (void)
4777 {
4778         char    t[9];
4779         int             i;
4780         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4781         for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
4782                 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
4783         t[i] = 0;
4784         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(t);
4785 }
4786
4787 static int chrconv_number(int i, int base, int conv)
4788 {
4789         i -= base;
4790         switch (conv)
4791         {
4792         default:
4793         case 5:
4794         case 6:
4795         case 0:
4796                 break;
4797         case 1:
4798                 base = '0';
4799                 break;
4800         case 2:
4801                 base = '0'+128;
4802                 break;
4803         case 3:
4804                 base = '0'-30;
4805                 break;
4806         case 4:
4807                 base = '0'+128-30;
4808                 break;
4809         }
4810         return i + base;
4811 }
4812 static int chrconv_punct(int i, int base, int conv)
4813 {
4814         i -= base;
4815         switch (conv)
4816         {
4817         default:
4818         case 0:
4819                 break;
4820         case 1:
4821                 base = 0;
4822                 break;
4823         case 2:
4824                 base = 128;
4825                 break;
4826         }
4827         return i + base;
4828 }
4829
4830 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
4831 {
4832         //convert case and colour seperatly...
4833
4834         i -= baset + basec;
4835         switch (convt)
4836         {
4837         default:
4838         case 0:
4839                 break;
4840         case 1:
4841                 baset = 0;
4842                 break;
4843         case 2:
4844                 baset = 128;
4845                 break;
4846
4847         case 5:
4848         case 6:
4849                 baset = 128*((charnum&1) == (convt-5));
4850                 break;
4851         }
4852
4853         switch (convc)
4854         {
4855         default:
4856         case 0:
4857                 break;
4858         case 1:
4859                 basec = 'a';
4860                 break;
4861         case 2:
4862                 basec = 'A';
4863                 break;
4864         }
4865         return i + basec + baset;
4866 }
4867 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
4868 //bulk convert a string. change case or colouring.
4869 void VM_strconv (void)
4870 {
4871         int ccase, redalpha, rednum, len, i;
4872         unsigned char resbuf[VM_STRINGTEMP_LENGTH];
4873         unsigned char *result = resbuf;
4874
4875         VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
4876
4877         ccase = (int) PRVM_G_FLOAT(OFS_PARM0);  //0 same, 1 lower, 2 upper
4878         redalpha = (int) PRVM_G_FLOAT(OFS_PARM1);       //0 same, 1 white, 2 red,  5 alternate, 6 alternate-alternate
4879         rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
4880         VM_VarString(3, (char *) resbuf, sizeof(resbuf));
4881         len = strlen((char *) resbuf);
4882
4883         for (i = 0; i < len; i++, result++)     //should this be done backwards?
4884         {
4885                 if (*result >= '0' && *result <= '9')   //normal numbers...
4886                         *result = chrconv_number(*result, '0', rednum);
4887                 else if (*result >= '0'+128 && *result <= '9'+128)
4888                         *result = chrconv_number(*result, '0'+128, rednum);
4889                 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
4890                         *result = chrconv_number(*result, '0'+128-30, rednum);
4891                 else if (*result >= '0'-30 && *result <= '9'-30)
4892                         *result = chrconv_number(*result, '0'-30, rednum);
4893
4894                 else if (*result >= 'a' && *result <= 'z')      //normal numbers...
4895                         *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
4896                 else if (*result >= 'A' && *result <= 'Z')      //normal numbers...
4897                         *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
4898                 else if (*result >= 'a'+128 && *result <= 'z'+128)      //normal numbers...
4899                         *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
4900                 else if (*result >= 'A'+128 && *result <= 'Z'+128)      //normal numbers...
4901                         *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
4902
4903                 else if ((*result & 127) < 16 || !redalpha)     //special chars..
4904                         *result = *result;
4905                 else if (*result < 128)
4906                         *result = chrconv_punct(*result, 0, redalpha);
4907                 else
4908                         *result = chrconv_punct(*result, 128, redalpha);
4909         }
4910         *result = '\0';
4911
4912         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString((char *) resbuf);
4913 }
4914
4915 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
4916 void VM_strpad (void)
4917 {
4918         char src[VM_STRINGTEMP_LENGTH];
4919         char destbuf[VM_STRINGTEMP_LENGTH];
4920         int pad;
4921         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
4922         pad = (int) PRVM_G_FLOAT(OFS_PARM0);
4923         VM_VarString(1, src, sizeof(src));
4924
4925         // note: < 0 = left padding, > 0 = right padding,
4926         // this is reverse logic of printf!
4927         dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
4928
4929         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(destbuf);
4930 }
4931
4932 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
4933 //uses qw style \key\value strings
4934 void VM_infoadd (void)
4935 {
4936         const char *info, *key;
4937         char value[VM_STRINGTEMP_LENGTH];
4938         char temp[VM_STRINGTEMP_LENGTH];
4939
4940         VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
4941         info = PRVM_G_STRING(OFS_PARM0);
4942         key = PRVM_G_STRING(OFS_PARM1);
4943         VM_VarString(2, value, sizeof(value));
4944
4945         strlcpy(temp, info, VM_STRINGTEMP_LENGTH);
4946
4947         InfoString_SetValue(temp, VM_STRINGTEMP_LENGTH, key, value);
4948
4949         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(temp);
4950 }
4951
4952 // #227 string(string info, string key) infoget (FTE_STRINGS)
4953 //uses qw style \key\value strings
4954 void VM_infoget (void)
4955 {
4956         const char *info;
4957         const char *key;
4958         char value[VM_STRINGTEMP_LENGTH];
4959
4960         VM_SAFEPARMCOUNT(2, VM_infoget);
4961         info = PRVM_G_STRING(OFS_PARM0);
4962         key = PRVM_G_STRING(OFS_PARM1);
4963
4964         InfoString_GetValue(info, key, value, VM_STRINGTEMP_LENGTH);
4965
4966         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(value);
4967 }
4968
4969 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
4970 // also float(string s1, string s2) strcmp (FRIK_FILE)
4971 void VM_strncmp (void)
4972 {
4973         const char *s1, *s2;
4974         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
4975         s1 = PRVM_G_STRING(OFS_PARM0);
4976         s2 = PRVM_G_STRING(OFS_PARM1);
4977         if (prog->argc > 2)
4978         {
4979                 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
4980         }
4981         else
4982         {
4983                 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
4984         }
4985 }
4986
4987 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
4988 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
4989 void VM_strncasecmp (void)
4990 {
4991         const char *s1, *s2;
4992         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
4993         s1 = PRVM_G_STRING(OFS_PARM0);
4994         s2 = PRVM_G_STRING(OFS_PARM1);
4995         if (prog->argc > 2)
4996         {
4997                 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
4998         }
4999         else
5000         {
5001                 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5002         }
5003 }
5004
5005 // #494 float(float caseinsensitive, string s, ...) crc16
5006 void VM_crc16(void)
5007 {
5008         float insensitive;
5009         static char s[VM_STRINGTEMP_LENGTH];
5010         VM_SAFEPARMCOUNTRANGE(2, 8, VM_hash);
5011         insensitive = PRVM_G_FLOAT(OFS_PARM0);
5012         VM_VarString(1, s, sizeof(s));
5013         PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, strlen(s)));
5014 }
5015
5016 void VM_wasfreed (void)
5017 {
5018         VM_SAFEPARMCOUNT(1, VM_wasfreed);
5019         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->priv.required->free;
5020 }
5021
5022 void VM_SetTraceGlobals(const trace_t *trace)
5023 {
5024         prvm_eval_t *val;
5025         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_allsolid)))
5026                 val->_float = trace->allsolid;
5027         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_startsolid)))
5028                 val->_float = trace->startsolid;
5029         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_fraction)))
5030                 val->_float = trace->fraction;
5031         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inwater)))
5032                 val->_float = trace->inwater;
5033         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inopen)))
5034                 val->_float = trace->inopen;
5035         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_endpos)))
5036                 VectorCopy(trace->endpos, val->vector);
5037         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_normal)))
5038                 VectorCopy(trace->plane.normal, val->vector);
5039         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_dist)))
5040                 val->_float = trace->plane.dist;
5041         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_ent)))
5042                 val->edict = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5043         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dpstartcontents)))
5044                 val->_float = trace->startsupercontents;
5045         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitcontents)))
5046                 val->_float = trace->hitsupercontents;
5047         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitq3surfaceflags)))
5048                 val->_float = trace->hitq3surfaceflags;
5049         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphittexturename)))
5050                 val->string = trace->hittexture ? PRVM_SetTempString(trace->hittexture->name) : 0;
5051 }
5052
5053 void VM_ClearTraceGlobals(void)
5054 {
5055         // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5056         prvm_eval_t *val;
5057         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_allsolid)))
5058                 val->_float = 0;
5059         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_startsolid)))
5060                 val->_float = 0;
5061         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_fraction)))
5062                 val->_float = 0;
5063         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inwater)))
5064                 val->_float = 0;
5065         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inopen)))
5066                 val->_float = 0;
5067         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_endpos)))
5068                 VectorClear(val->vector);
5069         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_normal)))
5070                 VectorClear(val->vector);
5071         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_dist)))
5072                 val->_float = 0;
5073         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_ent)))
5074                 val->edict = PRVM_EDICT_TO_PROG(prog->edicts);
5075         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dpstartcontents)))
5076                 val->_float = 0;
5077         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitcontents)))
5078                 val->_float = 0;
5079         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitq3surfaceflags)))
5080                 val->_float = 0;
5081         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphittexturename)))
5082                 val->string = 0;
5083 }
5084
5085 //=============
5086
5087 void VM_Cmd_Init(void)
5088 {
5089         // only init the stuff for the current prog
5090         VM_Files_Init();
5091         VM_Search_Init();
5092         VM_Gecko_Init();
5093 //      VM_BufStr_Init();
5094 }
5095
5096 void VM_Cmd_Reset(void)
5097 {
5098         CL_PurgeOwner( MENUOWNER );
5099         VM_Search_Reset();
5100         VM_Files_CloseAll();
5101         VM_Gecko_Destroy();
5102 //      VM_BufStr_ShutDown();
5103 }
5104
5105 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5106 // does URI escaping on a string (replace evil stuff by %AB escapes)
5107 void VM_uri_escape (void)
5108 {
5109         char src[VM_STRINGTEMP_LENGTH];
5110         char dest[VM_STRINGTEMP_LENGTH];
5111         char *p, *q;
5112         static const char *hex = "0123456789ABCDEF";
5113
5114         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5115         VM_VarString(0, src, sizeof(src));
5116
5117         for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5118         {
5119                 if((*p >= 'A' && *p <= 'Z')
5120                         || (*p >= 'a' && *p <= 'z')
5121                         || (*p >= '0' && *p <= '9')
5122                         || (*p == '-')  || (*p == '_') || (*p == '.')
5123                         || (*p == '!')  || (*p == '~') || (*p == '*')
5124                         || (*p == '\'') || (*p == '(') || (*p == ')'))
5125                         *q++ = *p;
5126                 else
5127                 {
5128                         *q++ = '%';
5129                         *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5130                         *q++ = hex[ *(unsigned char *)p       & 0xF];
5131                 }
5132         }
5133         *q++ = 0;
5134
5135         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5136 }
5137
5138 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5139 // does URI unescaping on a string (get back the evil stuff)
5140 void VM_uri_unescape (void)
5141 {
5142         char src[VM_STRINGTEMP_LENGTH];
5143         char dest[VM_STRINGTEMP_LENGTH];
5144         char *p, *q;
5145         int hi, lo;
5146
5147         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5148         VM_VarString(0, src, sizeof(src));
5149
5150         for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5151         {
5152                 if(*p == '%')
5153                 {
5154                         if(p[1] >= '0' && p[1] <= '9')
5155                                 hi = p[1] - '0';
5156                         else if(p[1] >= 'a' && p[1] <= 'f')
5157                                 hi = p[1] - 'a' + 10;
5158                         else if(p[1] >= 'A' && p[1] <= 'F')
5159                                 hi = p[1] - 'A' + 10;
5160                         else
5161                                 goto nohex;
5162                         if(p[2] >= '0' && p[2] <= '9')
5163                                 lo = p[2] - '0';
5164                         else if(p[2] >= 'a' && p[2] <= 'f')
5165                                 lo = p[2] - 'a' + 10;
5166                         else if(p[2] >= 'A' && p[2] <= 'F')
5167                                 lo = p[2] - 'A' + 10;
5168                         else
5169                                 goto nohex;
5170                         if(hi != 0 || lo != 0) // don't unescape NUL bytes
5171                                 *q++ = (char) (hi * 0x10 + lo);
5172                         p += 3;
5173                         continue;
5174                 }
5175
5176 nohex:
5177                 // otherwise:
5178                 *q++ = *p++;
5179         }
5180         *q++ = 0;
5181
5182         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5183 }
5184
5185 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5186 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5187 void VM_whichpack (void)
5188 {
5189         const char *fn, *pack;
5190
5191         VM_SAFEPARMCOUNT(1, VM_whichpack);
5192         fn = PRVM_G_STRING(OFS_PARM0);
5193         pack = FS_WhichPack(fn);
5194
5195         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(pack ? pack : "");
5196 }
5197
5198 typedef struct
5199 {
5200         int prognr;
5201         double starttime;
5202         float id;
5203         char buffer[MAX_INPUTLINE];
5204 }
5205 uri_to_prog_t;
5206
5207 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5208 {
5209         uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5210
5211         if(!PRVM_ProgLoaded(handle->prognr))
5212         {
5213                 // curl reply came too late... so just drop it
5214                 Z_Free(handle);
5215                 return;
5216         }
5217                 
5218         PRVM_SetProg(handle->prognr);
5219         PRVM_Begin;
5220                 if((prog->starttime == handle->starttime) && (prog->funcoffsets.URI_Get_Callback))
5221                 {
5222                         if(length_received >= sizeof(handle->buffer))
5223                                 length_received = sizeof(handle->buffer) - 1;
5224                         handle->buffer[length_received] = 0;
5225                 
5226                         PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5227                         PRVM_G_FLOAT(OFS_PARM1) = status;
5228                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(handle->buffer);
5229                         PRVM_ExecuteProgram(prog->funcoffsets.URI_Get_Callback, "QC function URI_Get_Callback is missing");
5230                 }
5231         PRVM_End;
5232         
5233         Z_Free(handle);
5234 }
5235
5236 // uri_get() gets content from an URL and calls a callback "uri_get_callback" with it set as string; an unique ID of the transfer is returned
5237 // returns 1 on success, and then calls the callback with the ID, 0 or the HTTP status code, and the received data in a string
5238 void VM_uri_get (void)
5239 {
5240         const char *url;
5241         float id;
5242         qboolean ret;
5243         uri_to_prog_t *handle;
5244
5245         if(!prog->funcoffsets.URI_Get_Callback)
5246                 PRVM_ERROR("uri_get called by %s without URI_Get_Callback defined", PRVM_NAME);
5247
5248         VM_SAFEPARMCOUNT(2, VM_uri_get);
5249
5250         url = PRVM_G_STRING(OFS_PARM0);
5251         id = PRVM_G_FLOAT(OFS_PARM1);
5252         handle = (uri_to_prog_t *) Z_Malloc(sizeof(*handle)); // this can't be the prog's mem pool, as curl may call the callback later!
5253
5254         handle->prognr = PRVM_GetProgNr();
5255         handle->starttime = prog->starttime;
5256         handle->id = id;
5257         ret = Curl_Begin_ToMemory(url, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5258         if(ret)
5259         {
5260                 PRVM_G_INT(OFS_RETURN) = 1;
5261         }
5262         else
5263         {
5264                 Z_Free(handle);
5265                 PRVM_G_INT(OFS_RETURN) = 0;
5266         }
5267 }
5268
5269 void VM_netaddress_resolve (void)
5270 {
5271         const char *ip;
5272         char normalized[128];
5273         int port;
5274         lhnetaddress_t addr;
5275
5276         VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
5277
5278         ip = PRVM_G_STRING(OFS_PARM0);
5279         port = 0;
5280         if(prog->argc > 1)
5281                 port = (int) PRVM_G_FLOAT(OFS_PARM1);
5282
5283         if(LHNETADDRESS_FromString(&addr, ip, port) && LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1))
5284                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(normalized);
5285         else
5286                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
5287 }
5288
5289 //string(void) getextresponse = #624; // returns the next extResponse packet that was sent to this client
5290 void VM_CL_getextresponse (void)
5291 {
5292         VM_SAFEPARMCOUNT(0,VM_argv);
5293
5294         if (net_extresponse_count <= 0)
5295                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5296         else
5297         {
5298                 int first;
5299                 --net_extresponse_count;
5300                 first = (net_extresponse_last + NET_EXTRESPONSE_MAX - net_extresponse_count) % NET_EXTRESPONSE_MAX;
5301                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(net_extresponse[first]);
5302         }
5303 }
5304
5305 void VM_SV_getextresponse (void)
5306 {
5307         VM_SAFEPARMCOUNT(0,VM_argv);
5308
5309         if (sv_net_extresponse_count <= 0)
5310                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5311         else
5312         {
5313                 int first;
5314                 --sv_net_extresponse_count;
5315                 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5316                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(sv_net_extresponse[first]);
5317         }
5318 }
5319
5320 /*
5321 =========
5322 VM_M_callfunction
5323
5324         callfunction(...,string function_name)
5325 Extension: pass
5326 =========
5327 */
5328 mfunction_t *PRVM_ED_FindFunction (const char *name);
5329 void VM_callfunction(void)
5330 {
5331         mfunction_t *func;
5332         const char *s;
5333
5334         VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
5335
5336         s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
5337
5338         VM_CheckEmptyString(s);
5339
5340         func = PRVM_ED_FindFunction(s);
5341
5342         if(!func)
5343                 PRVM_ERROR("VM_callfunciton: function %s not found !", s);
5344         else if (func->first_statement < 0)
5345         {
5346                 // negative statements are built in functions
5347                 int builtinnumber = -func->first_statement;
5348                 prog->xfunction->builtinsprofile++;
5349                 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
5350                         prog->builtins[builtinnumber]();
5351                 else
5352                         PRVM_ERROR("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, PRVM_NAME);
5353         }
5354         else if(func - prog->functions > 0)
5355         {
5356                 prog->argc--;
5357                 PRVM_ExecuteProgram(func - prog->functions,"");
5358                 prog->argc++;
5359         }
5360 }
5361
5362 /*
5363 =========
5364 VM_isfunction
5365
5366 float   isfunction(string function_name)
5367 =========
5368 */
5369 mfunction_t *PRVM_ED_FindFunction (const char *name);
5370 void VM_isfunction(void)
5371 {
5372         mfunction_t *func;
5373         const char *s;
5374
5375         VM_SAFEPARMCOUNT(1, VM_isfunction);
5376
5377         s = PRVM_G_STRING(OFS_PARM0);
5378
5379         VM_CheckEmptyString(s);
5380
5381         func = PRVM_ED_FindFunction(s);
5382
5383         if(!func)
5384                 PRVM_G_FLOAT(OFS_RETURN) = false;
5385         else
5386                 PRVM_G_FLOAT(OFS_RETURN) = true;
5387 }