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