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