]> git.xonotic.org Git - xonotic/darkplaces.git/blob - prvm_cmds.c
fix warnings I caused in a previous commit
[xonotic/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 #include "cl_collision.h"
14 #include "clvm_cmds.h"
15 #include "ft2.h"
16 #include "mdfour.h"
17
18 extern cvar_t prvm_backtraceforwarnings;
19
20 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
21 void VM_Warning(const char *fmt, ...)
22 {
23         va_list argptr;
24         char msg[MAX_INPUTLINE];
25         static double recursive = -1;
26
27         va_start(argptr,fmt);
28         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
29         va_end(argptr);
30
31         Con_DPrint(msg);
32
33         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
34         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
35         {
36                 recursive = realtime;
37                 PRVM_PrintState();
38                 recursive = -1;
39         }
40 }
41
42
43 //============================================================================
44 // Common
45
46 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
47 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
48 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
49 // TODO: will this war ever end? [2007-01-23 LordHavoc]
50
51 void VM_CheckEmptyString (const char *s)
52 {
53         if (ISWHITESPACE(s[0]))
54                 PRVM_ERROR ("%s: Bad string", PRVM_NAME);
55 }
56
57 void VM_GenerateFrameGroupBlend(framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
58 {
59         // self.frame is the interpolation target (new frame)
60         // self.frame1time is the animation base time for the interpolation target
61         // self.frame2 is the interpolation start (previous frame)
62         // self.frame2time is the animation base time for the interpolation start
63         // self.lerpfrac is the interpolation strength for self.frame2
64         // self.lerpfrac3 is the interpolation strength for self.frame3
65         // self.lerpfrac4 is the interpolation strength for self.frame4
66         // pitch angle on a player model where the animator set up 5 sets of
67         // animations and the csqc simply lerps between sets)
68         framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame     );
69         framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2    );
70         framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3    );
71         framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4    );
72         framegroupblend[0].start =       PRVM_gameedictfloat(ed, frame1time);
73         framegroupblend[1].start =       PRVM_gameedictfloat(ed, frame2time);
74         framegroupblend[2].start =       PRVM_gameedictfloat(ed, frame3time);
75         framegroupblend[3].start =       PRVM_gameedictfloat(ed, frame4time);
76         framegroupblend[1].lerp  =       PRVM_gameedictfloat(ed, lerpfrac  );
77         framegroupblend[2].lerp  =       PRVM_gameedictfloat(ed, lerpfrac3 );
78         framegroupblend[3].lerp  =       PRVM_gameedictfloat(ed, lerpfrac4 );
79         // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
80         framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
81 }
82
83 // LordHavoc: quite tempting to break apart this function to reuse the
84 //            duplicated code, but I suspect it is better for performance
85 //            this way
86 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const dp_model_t *model)
87 {
88         int sub2, numframes, f, i, k;
89         int isfirstframegroup = true;
90         int nolerp;
91         double sublerp, lerp, d;
92         const animscene_t *scene;
93         const framegroupblend_t *g;
94         frameblend_t *blend = frameblend;
95
96         memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
97
98         if (!model || !model->surfmesh.isanimated)
99         {
100                 blend[0].lerp = 1;
101                 return;
102         }
103
104         nolerp = (model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer;
105         numframes = model->numframes;
106         for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
107         {
108                 f = g->frame;
109                 if ((unsigned int)f >= (unsigned int)numframes)
110                 {
111                         Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
112                         f = 0;
113                 }
114                 d = lerp = g->lerp;
115                 if (lerp <= 0)
116                         continue;
117                 if (nolerp)
118                 {
119                         if (isfirstframegroup)
120                         {
121                                 d = lerp = 1;
122                                 isfirstframegroup = false;
123                         }
124                         else
125                                 continue;
126                 }
127                 if (model->animscenes)
128                 {
129                         scene = model->animscenes + f;
130                         f = scene->firstframe;
131                         if (scene->framecount > 1)
132                         {
133                                 // this code path is only used on .zym models and torches
134                                 sublerp = scene->framerate * (cl.time - g->start);
135                                 f = (int) floor(sublerp);
136                                 sublerp -= f;
137                                 sub2 = f + 1;
138                                 if (sublerp < (1.0 / 65536.0f))
139                                         sublerp = 0;
140                                 if (sublerp > (65535.0f / 65536.0f))
141                                         sublerp = 1;
142                                 if (nolerp)
143                                         sublerp = 0;
144                                 if (scene->loop)
145                                 {
146                                         f = (f % scene->framecount);
147                                         sub2 = (sub2 % scene->framecount);
148                                 }
149                                 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
150                                 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
151                                 d = sublerp * lerp;
152                                 // two framelerps produced from one animation
153                                 if (d > 0)
154                                 {
155                                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
156                                         {
157                                                 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
158                                                 {
159                                                         blend[i].subframe = sub2;
160                                                         blend[i].lerp += d;
161                                                         break;
162                                                 }
163                                         }
164                                 }
165                                 d = (1 - sublerp) * lerp;
166                         }
167                 }
168                 if (d > 0)
169                 {
170                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
171                         {
172                                 if (blend[i].lerp <= 0 || blend[i].subframe == f)
173                                 {
174                                         blend[i].subframe = f;
175                                         blend[i].lerp += d;
176                                         break;
177                                 }
178                         }
179                 }
180         }
181 }
182
183 void VM_UpdateEdictSkeleton(prvm_edict_t *ed, const dp_model_t *edmodel, const frameblend_t *frameblend)
184 {
185         if (ed->priv.server->skeleton.model != edmodel)
186         {
187                 VM_RemoveEdictSkeleton(ed);
188                 ed->priv.server->skeleton.model = edmodel;
189         }
190         if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
191         {
192                 if(ed->priv.server->skeleton.relativetransforms)
193                         Mem_Free(ed->priv.server->skeleton.relativetransforms);
194                 ed->priv.server->skeleton.relativetransforms = NULL;
195                 return;
196         }
197
198         {
199                 int skeletonindex = -1;
200                 skeleton_t *skeleton;
201                 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
202                 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
203                 {
204                         // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
205                         if (!ed->priv.server->skeleton.relativetransforms)
206                                 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
207                         memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
208                 }
209                 else
210                 {
211                         if(ed->priv.server->skeleton.relativetransforms)
212                                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
213                         ed->priv.server->skeleton.relativetransforms = NULL;
214                 }
215         }
216 }
217
218 void VM_RemoveEdictSkeleton(prvm_edict_t *ed)
219 {
220         if (ed->priv.server->skeleton.relativetransforms)
221                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
222         memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
223 }
224
225
226
227
228 //============================================================================
229 //BUILT-IN FUNCTIONS
230
231 void VM_VarString(int first, char *out, int outlength)
232 {
233         int i;
234         const char *s;
235         char *outend;
236
237         outend = out + outlength - 1;
238         for (i = first;i < prog->argc && out < outend;i++)
239         {
240                 s = PRVM_G_STRING((OFS_PARM0+i*3));
241                 while (out < outend && *s)
242                         *out++ = *s++;
243         }
244         *out++ = 0;
245 }
246
247 /*
248 =================
249 VM_checkextension
250
251 returns true if the extension is supported by the server
252
253 checkextension(extensionname)
254 =================
255 */
256
257 // kind of helper function
258 static qboolean checkextension(const char *name)
259 {
260         int len;
261         const char *e, *start;
262         len = (int)strlen(name);
263
264         for (e = prog->extensionstring;*e;e++)
265         {
266                 while (*e == ' ')
267                         e++;
268                 if (!*e)
269                         break;
270                 start = e;
271                 while (*e && *e != ' ')
272                         e++;
273                 if ((e - start) == len && !strncasecmp(start, name, len))
274                 {
275                         // special sheck for ODE
276                         if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
277                         {
278 #ifdef USEODE
279                                 return ode_dll ? true : false;
280 #else
281                                 return false;
282 #endif
283                         }
284
285                         // special sheck for d0_blind_id
286                         if (!strcasecmp("DP_CRYPTO", name))
287                                 return Crypto_Available();
288                         if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
289                                 return Crypto_Available();
290
291                         return true;
292                 }
293         }
294         return false;
295 }
296
297 void VM_checkextension (void)
298 {
299         VM_SAFEPARMCOUNT(1,VM_checkextension);
300
301         PRVM_G_FLOAT(OFS_RETURN) = checkextension(PRVM_G_STRING(OFS_PARM0));
302 }
303
304 /*
305 =================
306 VM_error
307
308 This is a TERMINAL error, which will kill off the entire prog.
309 Dumps self.
310
311 error(value)
312 =================
313 */
314 void VM_error (void)
315 {
316         prvm_edict_t    *ed;
317         char string[VM_STRINGTEMP_LENGTH];
318
319         VM_VarString(0, string, sizeof(string));
320         Con_Printf("======%s ERROR in %s:\n%s\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
321         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
322         PRVM_ED_Print(ed, NULL);
323
324         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);
325 }
326
327 /*
328 =================
329 VM_objerror
330
331 Dumps out self, then an error message.  The program is aborted and self is
332 removed, but the level can continue.
333
334 objerror(value)
335 =================
336 */
337 void VM_objerror (void)
338 {
339         prvm_edict_t    *ed;
340         char string[VM_STRINGTEMP_LENGTH];
341
342         VM_VarString(0, string, sizeof(string));
343         Con_Printf("======OBJECT ERROR======\n"); // , PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
344         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
345         PRVM_ED_Print(ed, NULL);
346         PRVM_ED_Free (ed);
347         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);
348 }
349
350 /*
351 =================
352 VM_print
353
354 print to console
355
356 print(...[string])
357 =================
358 */
359 void VM_print (void)
360 {
361         char string[VM_STRINGTEMP_LENGTH];
362
363         VM_VarString(0, string, sizeof(string));
364         Con_Print(string);
365 }
366
367 /*
368 =================
369 VM_bprint
370
371 broadcast print to everyone on server
372
373 bprint(...[string])
374 =================
375 */
376 void VM_bprint (void)
377 {
378         char string[VM_STRINGTEMP_LENGTH];
379
380         if(!sv.active)
381         {
382                 VM_Warning("VM_bprint: game is not server(%s) !\n", PRVM_NAME);
383                 return;
384         }
385
386         VM_VarString(0, string, sizeof(string));
387         SV_BroadcastPrint(string);
388 }
389
390 /*
391 =================
392 VM_sprint (menu & client but only if server.active == true)
393
394 single print to a specific client
395
396 sprint(float clientnum,...[string])
397 =================
398 */
399 void VM_sprint (void)
400 {
401         client_t        *client;
402         int                     clientnum;
403         char string[VM_STRINGTEMP_LENGTH];
404
405         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
406
407         //find client for this entity
408         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
409         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
410         {
411                 VM_Warning("VM_sprint: %s: invalid client or server is not active !\n", PRVM_NAME);
412                 return;
413         }
414
415         client = svs.clients + clientnum;
416         if (!client->netconnection)
417                 return;
418
419         VM_VarString(1, string, sizeof(string));
420         MSG_WriteChar(&client->netconnection->message,svc_print);
421         MSG_WriteString(&client->netconnection->message, string);
422 }
423
424 /*
425 =================
426 VM_centerprint
427
428 single print to the screen
429
430 centerprint(value)
431 =================
432 */
433 void VM_centerprint (void)
434 {
435         char string[VM_STRINGTEMP_LENGTH];
436
437         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
438         VM_VarString(0, string, sizeof(string));
439         SCR_CenterPrint(string);
440 }
441
442 /*
443 =================
444 VM_normalize
445
446 vector normalize(vector)
447 =================
448 */
449 void VM_normalize (void)
450 {
451         float   *value1;
452         vec3_t  newvalue;
453         double  f;
454
455         VM_SAFEPARMCOUNT(1,VM_normalize);
456
457         value1 = PRVM_G_VECTOR(OFS_PARM0);
458
459         f = VectorLength2(value1);
460         if (f)
461         {
462                 f = 1.0 / sqrt(f);
463                 VectorScale(value1, f, newvalue);
464         }
465         else
466                 VectorClear(newvalue);
467
468         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
469 }
470
471 /*
472 =================
473 VM_vlen
474
475 scalar vlen(vector)
476 =================
477 */
478 void VM_vlen (void)
479 {
480         VM_SAFEPARMCOUNT(1,VM_vlen);
481         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
482 }
483
484 /*
485 =================
486 VM_vectoyaw
487
488 float vectoyaw(vector)
489 =================
490 */
491 void VM_vectoyaw (void)
492 {
493         float   *value1;
494         float   yaw;
495
496         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
497
498         value1 = PRVM_G_VECTOR(OFS_PARM0);
499
500         if (value1[1] == 0 && value1[0] == 0)
501                 yaw = 0;
502         else
503         {
504                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
505                 if (yaw < 0)
506                         yaw += 360;
507         }
508
509         PRVM_G_FLOAT(OFS_RETURN) = yaw;
510 }
511
512
513 /*
514 =================
515 VM_vectoangles
516
517 vector vectoangles(vector[, vector])
518 =================
519 */
520 void VM_vectoangles (void)
521 {
522         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
523
524         AnglesFromVectors(PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_PARM0), prog->argc >= 2 ? PRVM_G_VECTOR(OFS_PARM1) : NULL, true);
525 }
526
527 /*
528 =================
529 VM_random
530
531 Returns a number from 0<= num < 1
532
533 float random()
534 =================
535 */
536 void VM_random (void)
537 {
538         VM_SAFEPARMCOUNT(0,VM_random);
539
540         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
541 }
542
543 /*
544 =========
545 VM_localsound
546
547 localsound(string sample)
548 =========
549 */
550 void VM_localsound(void)
551 {
552         const char *s;
553
554         VM_SAFEPARMCOUNT(1,VM_localsound);
555
556         s = PRVM_G_STRING(OFS_PARM0);
557
558         if(!S_LocalSound (s))
559         {
560                 PRVM_G_FLOAT(OFS_RETURN) = -4;
561                 VM_Warning("VM_localsound: Failed to play %s for %s !\n", s, PRVM_NAME);
562                 return;
563         }
564
565         PRVM_G_FLOAT(OFS_RETURN) = 1;
566 }
567
568 /*
569 =================
570 VM_break
571
572 break()
573 =================
574 */
575 void VM_break (void)
576 {
577         PRVM_ERROR ("%s: break statement", PRVM_NAME);
578 }
579
580 //============================================================================
581
582 /*
583 =================
584 VM_localcmd
585
586 Sends text over to the client's execution buffer
587
588 [localcmd (string, ...) or]
589 cmd (string, ...)
590 =================
591 */
592 void VM_localcmd (void)
593 {
594         char string[VM_STRINGTEMP_LENGTH];
595         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
596         VM_VarString(0, string, sizeof(string));
597         Cbuf_AddText(string);
598 }
599
600 static qboolean PRVM_Cvar_ReadOk(const char *string)
601 {
602         cvar_t *cvar;
603         cvar = Cvar_FindVar(string);
604         return ((cvar) && ((cvar->flags & CVAR_PRIVATE) == 0));
605 }
606
607 /*
608 =================
609 VM_cvar
610
611 float cvar (string)
612 =================
613 */
614 void VM_cvar (void)
615 {
616         char string[VM_STRINGTEMP_LENGTH];
617         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
618         VM_VarString(0, string, sizeof(string));
619         VM_CheckEmptyString(string);
620         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(string) ? Cvar_VariableValue(string) : 0;
621 }
622
623 /*
624 =================
625 VM_cvar
626
627 float cvar_type (string)
628 float CVAR_TYPEFLAG_EXISTS = 1;
629 float CVAR_TYPEFLAG_SAVED = 2;
630 float CVAR_TYPEFLAG_PRIVATE = 4;
631 float CVAR_TYPEFLAG_ENGINE = 8;
632 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
633 float CVAR_TYPEFLAG_READONLY = 32;
634 =================
635 */
636 void VM_cvar_type (void)
637 {
638         char string[VM_STRINGTEMP_LENGTH];
639         cvar_t *cvar;
640         int ret;
641
642         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
643         VM_VarString(0, string, sizeof(string));
644         VM_CheckEmptyString(string);
645         cvar = Cvar_FindVar(string);
646
647
648         if(!cvar)
649         {
650                 PRVM_G_FLOAT(OFS_RETURN) = 0;
651                 return; // CVAR_TYPE_NONE
652         }
653
654         ret = 1; // CVAR_EXISTS
655         if(cvar->flags & CVAR_SAVE)
656                 ret |= 2; // CVAR_TYPE_SAVED
657         if(cvar->flags & CVAR_PRIVATE)
658                 ret |= 4; // CVAR_TYPE_PRIVATE
659         if(!(cvar->flags & CVAR_ALLOCATED))
660                 ret |= 8; // CVAR_TYPE_ENGINE
661         if(cvar->description != cvar_dummy_description)
662                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
663         if(cvar->flags & CVAR_READONLY)
664                 ret |= 32; // CVAR_TYPE_READONLY
665         
666         PRVM_G_FLOAT(OFS_RETURN) = ret;
667 }
668
669 /*
670 =================
671 VM_cvar_string
672
673 const string    VM_cvar_string (string, ...)
674 =================
675 */
676 void VM_cvar_string(void)
677 {
678         char string[VM_STRINGTEMP_LENGTH];
679         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
680         VM_VarString(0, string, sizeof(string));
681         VM_CheckEmptyString(string);
682         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_Cvar_ReadOk(string) ? Cvar_VariableString(string) : "");
683 }
684
685
686 /*
687 ========================
688 VM_cvar_defstring
689
690 const string    VM_cvar_defstring (string, ...)
691 ========================
692 */
693 void VM_cvar_defstring (void)
694 {
695         char string[VM_STRINGTEMP_LENGTH];
696         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
697         VM_VarString(0, string, sizeof(string));
698         VM_CheckEmptyString(string);
699         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDefString(string));
700 }
701
702 /*
703 ========================
704 VM_cvar_defstring
705
706 const string    VM_cvar_description (string, ...)
707 ========================
708 */
709 void VM_cvar_description (void)
710 {
711         char string[VM_STRINGTEMP_LENGTH];
712         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
713         VM_VarString(0, string, sizeof(string));
714         VM_CheckEmptyString(string);
715         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDescription(string));
716 }
717 /*
718 =================
719 VM_cvar_set
720
721 void cvar_set (string,string, ...)
722 =================
723 */
724 void VM_cvar_set (void)
725 {
726         const char *name;
727         char string[VM_STRINGTEMP_LENGTH];
728         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
729         VM_VarString(1, string, sizeof(string));
730         name = PRVM_G_STRING(OFS_PARM0);
731         VM_CheckEmptyString(name);
732         Cvar_Set(name, string);
733 }
734
735 /*
736 =========
737 VM_dprint
738
739 dprint(...[string])
740 =========
741 */
742 void VM_dprint (void)
743 {
744         char string[VM_STRINGTEMP_LENGTH];
745         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
746         VM_VarString(0, string, sizeof(string));
747 #if 1
748         Con_DPrintf("%s", string);
749 #else
750         Con_DPrintf("%s: %s", PRVM_NAME, string);
751 #endif
752 }
753
754 /*
755 =========
756 VM_ftos
757
758 string  ftos(float)
759 =========
760 */
761
762 void VM_ftos (void)
763 {
764         float v;
765         char s[128];
766
767         VM_SAFEPARMCOUNT(1, VM_ftos);
768
769         v = PRVM_G_FLOAT(OFS_PARM0);
770
771         if ((float)((int)v) == v)
772                 dpsnprintf(s, sizeof(s), "%i", (int)v);
773         else
774                 dpsnprintf(s, sizeof(s), "%f", v);
775         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
776 }
777
778 /*
779 =========
780 VM_fabs
781
782 float   fabs(float)
783 =========
784 */
785
786 void VM_fabs (void)
787 {
788         float   v;
789
790         VM_SAFEPARMCOUNT(1,VM_fabs);
791
792         v = PRVM_G_FLOAT(OFS_PARM0);
793         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
794 }
795
796 /*
797 =========
798 VM_vtos
799
800 string  vtos(vector)
801 =========
802 */
803
804 void VM_vtos (void)
805 {
806         char s[512];
807
808         VM_SAFEPARMCOUNT(1,VM_vtos);
809
810         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]);
811         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
812 }
813
814 /*
815 =========
816 VM_etos
817
818 string  etos(entity)
819 =========
820 */
821
822 void VM_etos (void)
823 {
824         char s[128];
825
826         VM_SAFEPARMCOUNT(1, VM_etos);
827
828         dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
829         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
830 }
831
832 /*
833 =========
834 VM_stof
835
836 float stof(...[string])
837 =========
838 */
839 void VM_stof(void)
840 {
841         char string[VM_STRINGTEMP_LENGTH];
842         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
843         VM_VarString(0, string, sizeof(string));
844         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
845 }
846
847 /*
848 ========================
849 VM_itof
850
851 float itof(intt ent)
852 ========================
853 */
854 void VM_itof(void)
855 {
856         VM_SAFEPARMCOUNT(1, VM_itof);
857         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
858 }
859
860 /*
861 ========================
862 VM_ftoe
863
864 entity ftoe(float num)
865 ========================
866 */
867 void VM_ftoe(void)
868 {
869         int ent;
870         VM_SAFEPARMCOUNT(1, VM_ftoe);
871
872         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
873         if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
874                 ent = 0; // return world instead of a free or invalid entity
875
876         PRVM_G_INT(OFS_RETURN) = ent;
877 }
878
879 /*
880 ========================
881 VM_etof
882
883 float etof(entity ent)
884 ========================
885 */
886 void VM_etof(void)
887 {
888         VM_SAFEPARMCOUNT(1, VM_etof);
889         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
890 }
891
892 /*
893 =========
894 VM_strftime
895
896 string strftime(float uselocaltime, string[, string ...])
897 =========
898 */
899 void VM_strftime(void)
900 {
901         time_t t;
902 #if _MSC_VER >= 1400
903         struct tm tm;
904         int tmresult;
905 #else
906         struct tm *tm;
907 #endif
908         char fmt[VM_STRINGTEMP_LENGTH];
909         char result[VM_STRINGTEMP_LENGTH];
910         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
911         VM_VarString(1, fmt, sizeof(fmt));
912         t = time(NULL);
913 #if _MSC_VER >= 1400
914         if (PRVM_G_FLOAT(OFS_PARM0))
915                 tmresult = localtime_s(&tm, &t);
916         else
917                 tmresult = gmtime_s(&tm, &t);
918         if (!tmresult)
919 #else
920         if (PRVM_G_FLOAT(OFS_PARM0))
921                 tm = localtime(&t);
922         else
923                 tm = gmtime(&t);
924         if (!tm)
925 #endif
926         {
927                 PRVM_G_INT(OFS_RETURN) = 0;
928                 return;
929         }
930 #if _MSC_VER >= 1400
931         strftime(result, sizeof(result), fmt, &tm);
932 #else
933         strftime(result, sizeof(result), fmt, tm);
934 #endif
935         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(result);
936 }
937
938 /*
939 =========
940 VM_spawn
941
942 entity spawn()
943 =========
944 */
945
946 void VM_spawn (void)
947 {
948         prvm_edict_t    *ed;
949         VM_SAFEPARMCOUNT(0, VM_spawn);
950         prog->xfunction->builtinsprofile += 20;
951         ed = PRVM_ED_Alloc();
952         VM_RETURN_EDICT(ed);
953 }
954
955 /*
956 =========
957 VM_remove
958
959 remove(entity e)
960 =========
961 */
962
963 void VM_remove (void)
964 {
965         prvm_edict_t    *ed;
966         prog->xfunction->builtinsprofile += 20;
967
968         VM_SAFEPARMCOUNT(1, VM_remove);
969
970         ed = PRVM_G_EDICT(OFS_PARM0);
971         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
972         {
973                 if (developer.integer > 0)
974                         VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
975         }
976         else if( ed->priv.required->free )
977         {
978                 if (developer.integer > 0)
979                         VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
980         }
981         else
982                 PRVM_ED_Free (ed);
983 }
984
985 /*
986 =========
987 VM_find
988
989 entity  find(entity start, .string field, string match)
990 =========
991 */
992
993 void VM_find (void)
994 {
995         int             e;
996         int             f;
997         const char      *s, *t;
998         prvm_edict_t    *ed;
999
1000         VM_SAFEPARMCOUNT(3,VM_find);
1001
1002         e = PRVM_G_EDICTNUM(OFS_PARM0);
1003         f = PRVM_G_INT(OFS_PARM1);
1004         s = PRVM_G_STRING(OFS_PARM2);
1005
1006         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1007         // expects it to find all the monsters, so we must be careful to support
1008         // searching for ""
1009
1010         for (e++ ; e < prog->num_edicts ; e++)
1011         {
1012                 prog->xfunction->builtinsprofile++;
1013                 ed = PRVM_EDICT_NUM(e);
1014                 if (ed->priv.required->free)
1015                         continue;
1016                 t = PRVM_E_STRING(ed,f);
1017                 if (!t)
1018                         t = "";
1019                 if (!strcmp(t,s))
1020                 {
1021                         VM_RETURN_EDICT(ed);
1022                         return;
1023                 }
1024         }
1025
1026         VM_RETURN_EDICT(prog->edicts);
1027 }
1028
1029 /*
1030 =========
1031 VM_findfloat
1032
1033   entity        findfloat(entity start, .float field, float match)
1034   entity        findentity(entity start, .entity field, entity match)
1035 =========
1036 */
1037 // LordHavoc: added this for searching float, int, and entity reference fields
1038 void VM_findfloat (void)
1039 {
1040         int             e;
1041         int             f;
1042         float   s;
1043         prvm_edict_t    *ed;
1044
1045         VM_SAFEPARMCOUNT(3,VM_findfloat);
1046
1047         e = PRVM_G_EDICTNUM(OFS_PARM0);
1048         f = PRVM_G_INT(OFS_PARM1);
1049         s = PRVM_G_FLOAT(OFS_PARM2);
1050
1051         for (e++ ; e < prog->num_edicts ; e++)
1052         {
1053                 prog->xfunction->builtinsprofile++;
1054                 ed = PRVM_EDICT_NUM(e);
1055                 if (ed->priv.required->free)
1056                         continue;
1057                 if (PRVM_E_FLOAT(ed,f) == s)
1058                 {
1059                         VM_RETURN_EDICT(ed);
1060                         return;
1061                 }
1062         }
1063
1064         VM_RETURN_EDICT(prog->edicts);
1065 }
1066
1067 /*
1068 =========
1069 VM_findchain
1070
1071 entity  findchain(.string field, string match)
1072 =========
1073 */
1074 // chained search for strings in entity fields
1075 // entity(.string field, string match) findchain = #402;
1076 void VM_findchain (void)
1077 {
1078         int             i;
1079         int             f;
1080         const char      *s, *t;
1081         prvm_edict_t    *ent, *chain;
1082         int chainfield;
1083
1084         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1085
1086         if(prog->argc == 3)
1087                 chainfield = PRVM_G_INT(OFS_PARM2);
1088         else
1089                 chainfield = prog->fieldoffsets.chain;
1090         if (chainfield < 0)
1091                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1092
1093         chain = prog->edicts;
1094
1095         f = PRVM_G_INT(OFS_PARM0);
1096         s = PRVM_G_STRING(OFS_PARM1);
1097
1098         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1099         // expects it to find all the monsters, so we must be careful to support
1100         // searching for ""
1101
1102         ent = PRVM_NEXT_EDICT(prog->edicts);
1103         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1104         {
1105                 prog->xfunction->builtinsprofile++;
1106                 if (ent->priv.required->free)
1107                         continue;
1108                 t = PRVM_E_STRING(ent,f);
1109                 if (!t)
1110                         t = "";
1111                 if (strcmp(t,s))
1112                         continue;
1113
1114                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1115                 chain = ent;
1116         }
1117
1118         VM_RETURN_EDICT(chain);
1119 }
1120
1121 /*
1122 =========
1123 VM_findchainfloat
1124
1125 entity  findchainfloat(.string field, float match)
1126 entity  findchainentity(.string field, entity match)
1127 =========
1128 */
1129 // LordHavoc: chained search for float, int, and entity reference fields
1130 // entity(.string field, float match) findchainfloat = #403;
1131 void VM_findchainfloat (void)
1132 {
1133         int             i;
1134         int             f;
1135         float   s;
1136         prvm_edict_t    *ent, *chain;
1137         int chainfield;
1138
1139         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1140
1141         if(prog->argc == 3)
1142                 chainfield = PRVM_G_INT(OFS_PARM2);
1143         else
1144                 chainfield = prog->fieldoffsets.chain;
1145         if (chainfield < 0)
1146                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1147
1148         chain = (prvm_edict_t *)prog->edicts;
1149
1150         f = PRVM_G_INT(OFS_PARM0);
1151         s = PRVM_G_FLOAT(OFS_PARM1);
1152
1153         ent = PRVM_NEXT_EDICT(prog->edicts);
1154         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1155         {
1156                 prog->xfunction->builtinsprofile++;
1157                 if (ent->priv.required->free)
1158                         continue;
1159                 if (PRVM_E_FLOAT(ent,f) != s)
1160                         continue;
1161
1162                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1163                 chain = ent;
1164         }
1165
1166         VM_RETURN_EDICT(chain);
1167 }
1168
1169 /*
1170 ========================
1171 VM_findflags
1172
1173 entity  findflags(entity start, .float field, float match)
1174 ========================
1175 */
1176 // LordHavoc: search for flags in float fields
1177 void VM_findflags (void)
1178 {
1179         int             e;
1180         int             f;
1181         int             s;
1182         prvm_edict_t    *ed;
1183
1184         VM_SAFEPARMCOUNT(3, VM_findflags);
1185
1186
1187         e = PRVM_G_EDICTNUM(OFS_PARM0);
1188         f = PRVM_G_INT(OFS_PARM1);
1189         s = (int)PRVM_G_FLOAT(OFS_PARM2);
1190
1191         for (e++ ; e < prog->num_edicts ; e++)
1192         {
1193                 prog->xfunction->builtinsprofile++;
1194                 ed = PRVM_EDICT_NUM(e);
1195                 if (ed->priv.required->free)
1196                         continue;
1197                 if (!PRVM_E_FLOAT(ed,f))
1198                         continue;
1199                 if ((int)PRVM_E_FLOAT(ed,f) & s)
1200                 {
1201                         VM_RETURN_EDICT(ed);
1202                         return;
1203                 }
1204         }
1205
1206         VM_RETURN_EDICT(prog->edicts);
1207 }
1208
1209 /*
1210 ========================
1211 VM_findchainflags
1212
1213 entity  findchainflags(.float field, float match)
1214 ========================
1215 */
1216 // LordHavoc: chained search for flags in float fields
1217 void VM_findchainflags (void)
1218 {
1219         int             i;
1220         int             f;
1221         int             s;
1222         prvm_edict_t    *ent, *chain;
1223         int chainfield;
1224
1225         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1226
1227         if(prog->argc == 3)
1228                 chainfield = PRVM_G_INT(OFS_PARM2);
1229         else
1230                 chainfield = prog->fieldoffsets.chain;
1231         if (chainfield < 0)
1232                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1233
1234         chain = (prvm_edict_t *)prog->edicts;
1235
1236         f = PRVM_G_INT(OFS_PARM0);
1237         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1238
1239         ent = PRVM_NEXT_EDICT(prog->edicts);
1240         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1241         {
1242                 prog->xfunction->builtinsprofile++;
1243                 if (ent->priv.required->free)
1244                         continue;
1245                 if (!PRVM_E_FLOAT(ent,f))
1246                         continue;
1247                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1248                         continue;
1249
1250                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1251                 chain = ent;
1252         }
1253
1254         VM_RETURN_EDICT(chain);
1255 }
1256
1257 /*
1258 =========
1259 VM_precache_sound
1260
1261 string  precache_sound (string sample)
1262 =========
1263 */
1264 void VM_precache_sound (void)
1265 {
1266         const char *s;
1267
1268         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1269
1270         s = PRVM_G_STRING(OFS_PARM0);
1271         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1272         //VM_CheckEmptyString(s);
1273
1274         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1275         {
1276                 VM_Warning("VM_precache_sound: Failed to load %s for %s\n", s, PRVM_NAME);
1277                 return;
1278         }
1279 }
1280
1281 /*
1282 =================
1283 VM_precache_file
1284
1285 returns the same string as output
1286
1287 does nothing, only used by qcc to build .pak archives
1288 =================
1289 */
1290 void VM_precache_file (void)
1291 {
1292         VM_SAFEPARMCOUNT(1,VM_precache_file);
1293         // precache_file is only used to copy files with qcc, it does nothing
1294         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1295 }
1296
1297 /*
1298 =========
1299 VM_coredump
1300
1301 coredump()
1302 =========
1303 */
1304 void VM_coredump (void)
1305 {
1306         VM_SAFEPARMCOUNT(0,VM_coredump);
1307
1308         Cbuf_AddText("prvm_edicts ");
1309         Cbuf_AddText(PRVM_NAME);
1310         Cbuf_AddText("\n");
1311 }
1312
1313 /*
1314 =========
1315 VM_stackdump
1316
1317 stackdump()
1318 =========
1319 */
1320 void PRVM_StackTrace(void);
1321 void VM_stackdump (void)
1322 {
1323         VM_SAFEPARMCOUNT(0, VM_stackdump);
1324
1325         PRVM_StackTrace();
1326 }
1327
1328 /*
1329 =========
1330 VM_crash
1331
1332 crash()
1333 =========
1334 */
1335
1336 void VM_crash(void)
1337 {
1338         VM_SAFEPARMCOUNT(0, VM_crash);
1339
1340         PRVM_ERROR("Crash called by %s",PRVM_NAME);
1341 }
1342
1343 /*
1344 =========
1345 VM_traceon
1346
1347 traceon()
1348 =========
1349 */
1350 void VM_traceon (void)
1351 {
1352         VM_SAFEPARMCOUNT(0,VM_traceon);
1353
1354         prog->trace = true;
1355 }
1356
1357 /*
1358 =========
1359 VM_traceoff
1360
1361 traceoff()
1362 =========
1363 */
1364 void VM_traceoff (void)
1365 {
1366         VM_SAFEPARMCOUNT(0,VM_traceoff);
1367
1368         prog->trace = false;
1369 }
1370
1371 /*
1372 =========
1373 VM_eprint
1374
1375 eprint(entity e)
1376 =========
1377 */
1378 void VM_eprint (void)
1379 {
1380         VM_SAFEPARMCOUNT(1,VM_eprint);
1381
1382         PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1383 }
1384
1385 /*
1386 =========
1387 VM_rint
1388
1389 float   rint(float)
1390 =========
1391 */
1392 void VM_rint (void)
1393 {
1394         float f;
1395         VM_SAFEPARMCOUNT(1,VM_rint);
1396
1397         f = PRVM_G_FLOAT(OFS_PARM0);
1398         if (f > 0)
1399                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1400         else
1401                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1402 }
1403
1404 /*
1405 =========
1406 VM_floor
1407
1408 float   floor(float)
1409 =========
1410 */
1411 void VM_floor (void)
1412 {
1413         VM_SAFEPARMCOUNT(1,VM_floor);
1414
1415         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1416 }
1417
1418 /*
1419 =========
1420 VM_ceil
1421
1422 float   ceil(float)
1423 =========
1424 */
1425 void VM_ceil (void)
1426 {
1427         VM_SAFEPARMCOUNT(1,VM_ceil);
1428
1429         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1430 }
1431
1432
1433 /*
1434 =============
1435 VM_nextent
1436
1437 entity  nextent(entity)
1438 =============
1439 */
1440 void VM_nextent (void)
1441 {
1442         int             i;
1443         prvm_edict_t    *ent;
1444
1445         VM_SAFEPARMCOUNT(1, VM_nextent);
1446
1447         i = PRVM_G_EDICTNUM(OFS_PARM0);
1448         while (1)
1449         {
1450                 prog->xfunction->builtinsprofile++;
1451                 i++;
1452                 if (i == prog->num_edicts)
1453                 {
1454                         VM_RETURN_EDICT(prog->edicts);
1455                         return;
1456                 }
1457                 ent = PRVM_EDICT_NUM(i);
1458                 if (!ent->priv.required->free)
1459                 {
1460                         VM_RETURN_EDICT(ent);
1461                         return;
1462                 }
1463         }
1464 }
1465
1466 //=============================================================================
1467
1468 /*
1469 ==============
1470 VM_changelevel
1471 server and menu
1472
1473 changelevel(string map)
1474 ==============
1475 */
1476 void VM_changelevel (void)
1477 {
1478         VM_SAFEPARMCOUNT(1, VM_changelevel);
1479
1480         if(!sv.active)
1481         {
1482                 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1483                 return;
1484         }
1485
1486 // make sure we don't issue two changelevels
1487         if (svs.changelevel_issued)
1488                 return;
1489         svs.changelevel_issued = true;
1490
1491         Cbuf_AddText (va("changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1492 }
1493
1494 /*
1495 =========
1496 VM_sin
1497
1498 float   sin(float)
1499 =========
1500 */
1501 void VM_sin (void)
1502 {
1503         VM_SAFEPARMCOUNT(1,VM_sin);
1504         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1505 }
1506
1507 /*
1508 =========
1509 VM_cos
1510 float   cos(float)
1511 =========
1512 */
1513 void VM_cos (void)
1514 {
1515         VM_SAFEPARMCOUNT(1,VM_cos);
1516         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1517 }
1518
1519 /*
1520 =========
1521 VM_sqrt
1522
1523 float   sqrt(float)
1524 =========
1525 */
1526 void VM_sqrt (void)
1527 {
1528         VM_SAFEPARMCOUNT(1,VM_sqrt);
1529         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1530 }
1531
1532 /*
1533 =========
1534 VM_asin
1535
1536 float   asin(float)
1537 =========
1538 */
1539 void VM_asin (void)
1540 {
1541         VM_SAFEPARMCOUNT(1,VM_asin);
1542         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1543 }
1544
1545 /*
1546 =========
1547 VM_acos
1548 float   acos(float)
1549 =========
1550 */
1551 void VM_acos (void)
1552 {
1553         VM_SAFEPARMCOUNT(1,VM_acos);
1554         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1555 }
1556
1557 /*
1558 =========
1559 VM_atan
1560 float   atan(float)
1561 =========
1562 */
1563 void VM_atan (void)
1564 {
1565         VM_SAFEPARMCOUNT(1,VM_atan);
1566         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1567 }
1568
1569 /*
1570 =========
1571 VM_atan2
1572 float   atan2(float,float)
1573 =========
1574 */
1575 void VM_atan2 (void)
1576 {
1577         VM_SAFEPARMCOUNT(2,VM_atan2);
1578         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1579 }
1580
1581 /*
1582 =========
1583 VM_tan
1584 float   tan(float)
1585 =========
1586 */
1587 void VM_tan (void)
1588 {
1589         VM_SAFEPARMCOUNT(1,VM_tan);
1590         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1591 }
1592
1593 /*
1594 =================
1595 VM_randomvec
1596
1597 Returns a vector of length < 1 and > 0
1598
1599 vector randomvec()
1600 =================
1601 */
1602 void VM_randomvec (void)
1603 {
1604         vec3_t          temp;
1605         //float         length;
1606
1607         VM_SAFEPARMCOUNT(0, VM_randomvec);
1608
1609         //// WTF ??
1610         do
1611         {
1612                 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1613                 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1614                 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1615         }
1616         while (DotProduct(temp, temp) >= 1);
1617         VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1618
1619         /*
1620         temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1621         temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1622         temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1623         // length returned always > 0
1624         length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1625         VectorScale(temp,length, temp);*/
1626         //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1627 }
1628
1629 //=============================================================================
1630
1631 /*
1632 =========
1633 VM_registercvar
1634
1635 float   registercvar (string name, string value[, float flags])
1636 =========
1637 */
1638 void VM_registercvar (void)
1639 {
1640         const char *name, *value;
1641         int     flags;
1642
1643         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1644
1645         name = PRVM_G_STRING(OFS_PARM0);
1646         value = PRVM_G_STRING(OFS_PARM1);
1647         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1648         PRVM_G_FLOAT(OFS_RETURN) = 0;
1649
1650         if(flags > CVAR_MAXFLAGSVAL)
1651                 return;
1652
1653 // first check to see if it has already been defined
1654         if (Cvar_FindVar (name))
1655                 return;
1656
1657 // check for overlap with a command
1658         if (Cmd_Exists (name))
1659         {
1660                 VM_Warning("VM_registercvar: %s is a command\n", name);
1661                 return;
1662         }
1663
1664         Cvar_Get(name, value, flags, NULL);
1665
1666         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1667 }
1668
1669
1670 /*
1671 =================
1672 VM_min
1673
1674 returns the minimum of two supplied floats
1675
1676 float min(float a, float b, ...[float])
1677 =================
1678 */
1679 void VM_min (void)
1680 {
1681         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1682         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1683         if (prog->argc >= 3)
1684         {
1685                 int i;
1686                 float f = PRVM_G_FLOAT(OFS_PARM0);
1687                 for (i = 1;i < prog->argc;i++)
1688                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1689                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1690                 PRVM_G_FLOAT(OFS_RETURN) = f;
1691         }
1692         else
1693                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1694 }
1695
1696 /*
1697 =================
1698 VM_max
1699
1700 returns the maximum of two supplied floats
1701
1702 float   max(float a, float b, ...[float])
1703 =================
1704 */
1705 void VM_max (void)
1706 {
1707         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1708         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1709         if (prog->argc >= 3)
1710         {
1711                 int i;
1712                 float f = PRVM_G_FLOAT(OFS_PARM0);
1713                 for (i = 1;i < prog->argc;i++)
1714                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1715                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1716                 PRVM_G_FLOAT(OFS_RETURN) = f;
1717         }
1718         else
1719                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1720 }
1721
1722 /*
1723 =================
1724 VM_bound
1725
1726 returns number bounded by supplied range
1727
1728 float   bound(float min, float value, float max)
1729 =================
1730 */
1731 void VM_bound (void)
1732 {
1733         VM_SAFEPARMCOUNT(3,VM_bound);
1734         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1735 }
1736
1737 /*
1738 =================
1739 VM_pow
1740
1741 returns a raised to power b
1742
1743 float   pow(float a, float b)
1744 =================
1745 */
1746 void VM_pow (void)
1747 {
1748         VM_SAFEPARMCOUNT(2,VM_pow);
1749         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1750 }
1751
1752 void VM_log (void)
1753 {
1754         VM_SAFEPARMCOUNT(1,VM_log);
1755         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1756 }
1757
1758 void VM_Files_Init(void)
1759 {
1760         int i;
1761         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1762                 prog->openfiles[i] = NULL;
1763 }
1764
1765 void VM_Files_CloseAll(void)
1766 {
1767         int i;
1768         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1769         {
1770                 if (prog->openfiles[i])
1771                         FS_Close(prog->openfiles[i]);
1772                 prog->openfiles[i] = NULL;
1773         }
1774 }
1775
1776 static qfile_t *VM_GetFileHandle( int index )
1777 {
1778         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1779         {
1780                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1781                 return NULL;
1782         }
1783         if (prog->openfiles[index] == NULL)
1784         {
1785                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1786                 return NULL;
1787         }
1788         return prog->openfiles[index];
1789 }
1790
1791 /*
1792 =========
1793 VM_fopen
1794
1795 float   fopen(string filename, float mode)
1796 =========
1797 */
1798 // float(string filename, float mode) fopen = #110;
1799 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1800 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1801 void VM_fopen(void)
1802 {
1803         int filenum, mode;
1804         const char *modestring, *filename;
1805
1806         VM_SAFEPARMCOUNT(2,VM_fopen);
1807
1808         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1809                 if (prog->openfiles[filenum] == NULL)
1810                         break;
1811         if (filenum >= PRVM_MAX_OPENFILES)
1812         {
1813                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1814                 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENFILES);
1815                 return;
1816         }
1817         filename = PRVM_G_STRING(OFS_PARM0);
1818         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1819         switch(mode)
1820         {
1821         case 0: // FILE_READ
1822                 modestring = "rb";
1823                 prog->openfiles[filenum] = FS_OpenVirtualFile(va("data/%s", filename), false);
1824                 if (prog->openfiles[filenum] == NULL)
1825                         prog->openfiles[filenum] = FS_OpenVirtualFile(va("%s", filename), false);
1826                 break;
1827         case 1: // FILE_APPEND
1828                 modestring = "a";
1829                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1830                 break;
1831         case 2: // FILE_WRITE
1832                 modestring = "w";
1833                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1834                 break;
1835         default:
1836                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1837                 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1838                 return;
1839         }
1840
1841         if (prog->openfiles[filenum] == NULL)
1842         {
1843                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1844                 if (developer_extra.integer)
1845                         VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1846         }
1847         else
1848         {
1849                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1850                 if (developer_extra.integer)
1851                         Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1852                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin();
1853         }
1854 }
1855
1856 /*
1857 =========
1858 VM_fclose
1859
1860 fclose(float fhandle)
1861 =========
1862 */
1863 //void(float fhandle) fclose = #111; // closes a file
1864 void VM_fclose(void)
1865 {
1866         int filenum;
1867
1868         VM_SAFEPARMCOUNT(1,VM_fclose);
1869
1870         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1871         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1872         {
1873                 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1874                 return;
1875         }
1876         if (prog->openfiles[filenum] == NULL)
1877         {
1878                 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1879                 return;
1880         }
1881         FS_Close(prog->openfiles[filenum]);
1882         prog->openfiles[filenum] = NULL;
1883         if(prog->openfiles_origin[filenum])
1884                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1885         if (developer_extra.integer)
1886                 Con_DPrintf("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1887 }
1888
1889 /*
1890 =========
1891 VM_fgets
1892
1893 string  fgets(float fhandle)
1894 =========
1895 */
1896 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1897 void VM_fgets(void)
1898 {
1899         int c, end;
1900         char string[VM_STRINGTEMP_LENGTH];
1901         int filenum;
1902
1903         VM_SAFEPARMCOUNT(1,VM_fgets);
1904
1905         // set the return value regardless of any possible errors
1906         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1907
1908         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1909         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1910         {
1911                 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1912                 return;
1913         }
1914         if (prog->openfiles[filenum] == NULL)
1915         {
1916                 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1917                 return;
1918         }
1919         end = 0;
1920         for (;;)
1921         {
1922                 c = FS_Getc(prog->openfiles[filenum]);
1923                 if (c == '\r' || c == '\n' || c < 0)
1924                         break;
1925                 if (end < VM_STRINGTEMP_LENGTH - 1)
1926                         string[end++] = c;
1927         }
1928         string[end] = 0;
1929         // remove \n following \r
1930         if (c == '\r')
1931         {
1932                 c = FS_Getc(prog->openfiles[filenum]);
1933                 if (c != '\n')
1934                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1935         }
1936         if (developer_extra.integer)
1937                 Con_DPrintf("fgets: %s: %s\n", PRVM_NAME, string);
1938         if (c >= 0 || end)
1939                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
1940 }
1941
1942 /*
1943 =========
1944 VM_fputs
1945
1946 fputs(float fhandle, string s)
1947 =========
1948 */
1949 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1950 void VM_fputs(void)
1951 {
1952         int stringlength;
1953         char string[VM_STRINGTEMP_LENGTH];
1954         int filenum;
1955
1956         VM_SAFEPARMCOUNT(2,VM_fputs);
1957
1958         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1959         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1960         {
1961                 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1962                 return;
1963         }
1964         if (prog->openfiles[filenum] == NULL)
1965         {
1966                 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1967                 return;
1968         }
1969         VM_VarString(1, string, sizeof(string));
1970         if ((stringlength = (int)strlen(string)))
1971                 FS_Write(prog->openfiles[filenum], string, stringlength);
1972         if (developer_extra.integer)
1973                 Con_DPrintf("fputs: %s: %s\n", PRVM_NAME, string);
1974 }
1975
1976 /*
1977 =========
1978 VM_writetofile
1979
1980         writetofile(float fhandle, entity ent)
1981 =========
1982 */
1983 void VM_writetofile(void)
1984 {
1985         prvm_edict_t * ent;
1986         qfile_t *file;
1987
1988         VM_SAFEPARMCOUNT(2, VM_writetofile);
1989
1990         file = VM_GetFileHandle( (int)PRVM_G_FLOAT(OFS_PARM0) );
1991         if( !file )
1992         {
1993                 VM_Warning("VM_writetofile: invalid or closed file handle\n");
1994                 return;
1995         }
1996
1997         ent = PRVM_G_EDICT(OFS_PARM1);
1998         if(ent->priv.required->free)
1999         {
2000                 VM_Warning("VM_writetofile: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2001                 return;
2002         }
2003
2004         PRVM_ED_Write (file, ent);
2005 }
2006
2007 // KrimZon - DP_QC_ENTITYDATA
2008 /*
2009 =========
2010 VM_numentityfields
2011
2012 float() numentityfields
2013 Return the number of entity fields - NOT offsets
2014 =========
2015 */
2016 void VM_numentityfields(void)
2017 {
2018         PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2019 }
2020
2021 // KrimZon - DP_QC_ENTITYDATA
2022 /*
2023 =========
2024 VM_entityfieldname
2025
2026 string(float fieldnum) entityfieldname
2027 Return name of the specified field as a string, or empty if the field is invalid (warning)
2028 =========
2029 */
2030 void VM_entityfieldname(void)
2031 {
2032         ddef_t *d;
2033         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2034         
2035         if (i < 0 || i >= prog->numfielddefs)
2036         {
2037         VM_Warning("VM_entityfieldname: %s: field index out of bounds\n", PRVM_NAME);
2038         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2039                 return;
2040         }
2041         
2042         d = &prog->fielddefs[i];
2043         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2044 }
2045
2046 // KrimZon - DP_QC_ENTITYDATA
2047 /*
2048 =========
2049 VM_entityfieldtype
2050
2051 float(float fieldnum) entityfieldtype
2052 =========
2053 */
2054 void VM_entityfieldtype(void)
2055 {
2056         ddef_t *d;
2057         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2058         
2059         if (i < 0 || i >= prog->numfielddefs)
2060         {
2061                 VM_Warning("VM_entityfieldtype: %s: field index out of bounds\n", PRVM_NAME);
2062                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2063                 return;
2064         }
2065         
2066         d = &prog->fielddefs[i];
2067         PRVM_G_FLOAT(OFS_RETURN) = (float)d->type;
2068 }
2069
2070 // KrimZon - DP_QC_ENTITYDATA
2071 /*
2072 =========
2073 VM_getentityfieldstring
2074
2075 string(float fieldnum, entity ent) getentityfieldstring
2076 =========
2077 */
2078 void VM_getentityfieldstring(void)
2079 {
2080         // put the data into a string
2081         ddef_t *d;
2082         int type, j;
2083         int *v;
2084         prvm_edict_t * ent;
2085         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2086         
2087         if (i < 0 || i >= prog->numfielddefs)
2088         {
2089         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2090                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2091                 return;
2092         }
2093         
2094         d = &prog->fielddefs[i];
2095         
2096         // get the entity
2097         ent = PRVM_G_EDICT(OFS_PARM1);
2098         if(ent->priv.required->free)
2099         {
2100                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2101                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2102                 return;
2103         }
2104         v = (int *)((char *)ent->fields.vp + d->ofs*4);
2105         
2106         // if it's 0 or blank, return an empty string
2107         type = d->type & ~DEF_SAVEGLOBAL;
2108         for (j=0 ; j<prvm_type_size[type] ; j++)
2109                 if (v[j])
2110                         break;
2111         if (j == prvm_type_size[type])
2112         {
2113                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2114                 return;
2115         }
2116                 
2117         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_UglyValueString((etype_t)d->type, (prvm_eval_t *)v));
2118 }
2119
2120 // KrimZon - DP_QC_ENTITYDATA
2121 /*
2122 =========
2123 VM_putentityfieldstring
2124
2125 float(float fieldnum, entity ent, string s) putentityfieldstring
2126 =========
2127 */
2128 void VM_putentityfieldstring(void)
2129 {
2130         ddef_t *d;
2131         prvm_edict_t * ent;
2132         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2133
2134         if (i < 0 || i >= prog->numfielddefs)
2135         {
2136         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2137                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2138                 return;
2139         }
2140
2141         d = &prog->fielddefs[i];
2142
2143         // get the entity
2144         ent = PRVM_G_EDICT(OFS_PARM1);
2145         if(ent->priv.required->free)
2146         {
2147                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2148                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2149                 return;
2150         }
2151
2152         // parse the string into the value
2153         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2154 }
2155
2156 /*
2157 =========
2158 VM_strlen
2159
2160 float   strlen(string s)
2161 =========
2162 */
2163 //float(string s) strlen = #114; // returns how many characters are in a string
2164 void VM_strlen(void)
2165 {
2166         VM_SAFEPARMCOUNT(1,VM_strlen);
2167
2168         //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2169         PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2170 }
2171
2172 // DRESK - Decolorized String
2173 /*
2174 =========
2175 VM_strdecolorize
2176
2177 string  strdecolorize(string s)
2178 =========
2179 */
2180 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2181 void VM_strdecolorize(void)
2182 {
2183         char szNewString[VM_STRINGTEMP_LENGTH];
2184         const char *szString;
2185
2186         // Prepare Strings
2187         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2188         szString = PRVM_G_STRING(OFS_PARM0);
2189         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
2190         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2191 }
2192
2193 // DRESK - String Length (not counting color codes)
2194 /*
2195 =========
2196 VM_strlennocol
2197
2198 float   strlennocol(string s)
2199 =========
2200 */
2201 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2202 // For example, ^2Dresk returns a length of 5
2203 void VM_strlennocol(void)
2204 {
2205         const char *szString;
2206         int nCnt;
2207
2208         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2209
2210         szString = PRVM_G_STRING(OFS_PARM0);
2211
2212         //nCnt = COM_StringLengthNoColors(szString, 0, NULL);
2213         nCnt = u8_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;
2294         int u_slength = 0, u_start;
2295         size_t u_length;
2296         const char *s;
2297         char string[VM_STRINGTEMP_LENGTH];
2298
2299         VM_SAFEPARMCOUNT(3,VM_substring);
2300
2301         /*
2302         s = PRVM_G_STRING(OFS_PARM0);
2303         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2304         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2305         slength = strlen(s);
2306
2307         if (start < 0) // FTE_STRINGS feature
2308                 start += slength;
2309         start = bound(0, start, slength);
2310
2311         if (length < 0) // FTE_STRINGS feature
2312                 length += slength - start + 1;
2313         maxlen = min((int)sizeof(string) - 1, slength - start);
2314         length = bound(0, length, maxlen);
2315
2316         memcpy(string, s + start, length);
2317         string[length] = 0;
2318         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2319         */
2320         
2321         s = PRVM_G_STRING(OFS_PARM0);
2322         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2323         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2324
2325         if (start < 0) // FTE_STRINGS feature
2326         {
2327                 u_slength = u8_strlen(s);
2328                 start += u_slength;
2329                 start = bound(0, start, u_slength);
2330         }
2331
2332         if (length < 0) // FTE_STRINGS feature
2333         {
2334                 if (!u_slength) // it's not calculated when it's not needed above
2335                         u_slength = u8_strlen(s);
2336                 length += u_slength - start + 1;
2337         }
2338                 
2339         // positive start, positive length
2340         u_start = u8_byteofs(s, start, NULL);
2341         if (u_start < 0)
2342         {
2343                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2344                 return;
2345         }
2346         u_length = u8_bytelen(s + u_start, length);
2347         if (u_length >= sizeof(string)-1)
2348                 u_length = sizeof(string)-1;
2349         
2350         memcpy(string, s + u_start, u_length);
2351         string[u_length] = 0;
2352         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2353 }
2354
2355 /*
2356 =========
2357 VM_strreplace
2358
2359 string(string search, string replace, string subject) strreplace = #484;
2360 =========
2361 */
2362 // replaces all occurrences of search with replace in the string subject, and returns the result
2363 void VM_strreplace(void)
2364 {
2365         int i, j, si;
2366         const char *search, *replace, *subject;
2367         char string[VM_STRINGTEMP_LENGTH];
2368         int search_len, replace_len, subject_len;
2369
2370         VM_SAFEPARMCOUNT(3,VM_strreplace);
2371
2372         search = PRVM_G_STRING(OFS_PARM0);
2373         replace = PRVM_G_STRING(OFS_PARM1);
2374         subject = PRVM_G_STRING(OFS_PARM2);
2375
2376         search_len = (int)strlen(search);
2377         replace_len = (int)strlen(replace);
2378         subject_len = (int)strlen(subject);
2379
2380         si = 0;
2381         for (i = 0; i <= subject_len - search_len; i++)
2382         {
2383                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2384                         if (subject[i+j] != search[j])
2385                                 break;
2386                 if (j == search_len)
2387                 {
2388                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2389                         // found it at offset 'i'
2390                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2391                                 string[si++] = replace[j];
2392                         if(search_len > 0)
2393                         {
2394                                 i += search_len - 1;
2395                         }
2396                         else
2397                         {
2398                                 // the above would subtract 1 from i... so we
2399                                 // don't do that, but instead output the next
2400                                 // char
2401                                 if (si < (int)sizeof(string) - 1)
2402                                         string[si++] = subject[i];
2403                         }
2404                 }
2405                 else
2406                 {
2407                         // in THIS case, we know search_len > 0, thus i < subject_len
2408                         // not found
2409                         if (si < (int)sizeof(string) - 1)
2410                                 string[si++] = subject[i];
2411                 }
2412         }
2413         // remaining chars (these cannot match)
2414         for (; i < subject_len; i++)
2415                 if (si < (int)sizeof(string) - 1)
2416                         string[si++] = subject[i];
2417         string[si] = '\0';
2418
2419         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2420 }
2421
2422 /*
2423 =========
2424 VM_strireplace
2425
2426 string(string search, string replace, string subject) strireplace = #485;
2427 =========
2428 */
2429 // case-insensitive version of strreplace
2430 void VM_strireplace(void)
2431 {
2432         int i, j, si;
2433         const char *search, *replace, *subject;
2434         char string[VM_STRINGTEMP_LENGTH];
2435         int search_len, replace_len, subject_len;
2436
2437         VM_SAFEPARMCOUNT(3,VM_strreplace);
2438
2439         search = PRVM_G_STRING(OFS_PARM0);
2440         replace = PRVM_G_STRING(OFS_PARM1);
2441         subject = PRVM_G_STRING(OFS_PARM2);
2442
2443         search_len = (int)strlen(search);
2444         replace_len = (int)strlen(replace);
2445         subject_len = (int)strlen(subject);
2446
2447         si = 0;
2448         for (i = 0; i <= subject_len - search_len; i++)
2449         {
2450                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2451                         if (tolower(subject[i+j]) != tolower(search[j]))
2452                                 break;
2453                 if (j == search_len)
2454                 {
2455                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2456                         // found it at offset 'i'
2457                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2458                                 string[si++] = replace[j];
2459                         if(search_len > 0)
2460                         {
2461                                 i += search_len - 1;
2462                         }
2463                         else
2464                         {
2465                                 // the above would subtract 1 from i... so we
2466                                 // don't do that, but instead output the next
2467                                 // char
2468                                 if (si < (int)sizeof(string) - 1)
2469                                         string[si++] = subject[i];
2470                         }
2471                 }
2472                 else
2473                 {
2474                         // in THIS case, we know search_len > 0, thus i < subject_len
2475                         // not found
2476                         if (si < (int)sizeof(string) - 1)
2477                                 string[si++] = subject[i];
2478                 }
2479         }
2480         // remaining chars (these cannot match)
2481         for (; i < subject_len; i++)
2482                 if (si < (int)sizeof(string) - 1)
2483                         string[si++] = subject[i];
2484         string[si] = '\0';
2485
2486         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2487 }
2488
2489 /*
2490 =========
2491 VM_stov
2492
2493 vector  stov(string s)
2494 =========
2495 */
2496 //vector(string s) stov = #117; // returns vector value from a string
2497 void VM_stov(void)
2498 {
2499         char string[VM_STRINGTEMP_LENGTH];
2500
2501         VM_SAFEPARMCOUNT(1,VM_stov);
2502
2503         VM_VarString(0, string, sizeof(string));
2504         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2505 }
2506
2507 /*
2508 =========
2509 VM_strzone
2510
2511 string  strzone(string s)
2512 =========
2513 */
2514 //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)
2515 void VM_strzone(void)
2516 {
2517         char *out;
2518         char string[VM_STRINGTEMP_LENGTH];
2519         size_t alloclen;
2520
2521         VM_SAFEPARMCOUNT(1,VM_strzone);
2522
2523         VM_VarString(0, string, sizeof(string));
2524         alloclen = strlen(string) + 1;
2525         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
2526         memcpy(out, string, alloclen);
2527 }
2528
2529 /*
2530 =========
2531 VM_strunzone
2532
2533 strunzone(string s)
2534 =========
2535 */
2536 //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!!!)
2537 void VM_strunzone(void)
2538 {
2539         VM_SAFEPARMCOUNT(1,VM_strunzone);
2540         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
2541 }
2542
2543 /*
2544 =========
2545 VM_command (used by client and menu)
2546
2547 clientcommand(float client, string s) (for client and menu)
2548 =========
2549 */
2550 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
2551 //this function originally written by KrimZon, made shorter by LordHavoc
2552 void VM_clcommand (void)
2553 {
2554         client_t *temp_client;
2555         int i;
2556
2557         VM_SAFEPARMCOUNT(2,VM_clcommand);
2558
2559         i = (int)PRVM_G_FLOAT(OFS_PARM0);
2560         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
2561         {
2562                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
2563                 return;
2564         }
2565
2566         temp_client = host_client;
2567         host_client = svs.clients + i;
2568         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
2569         host_client = temp_client;
2570 }
2571
2572
2573 /*
2574 =========
2575 VM_tokenize
2576
2577 float tokenize(string s)
2578 =========
2579 */
2580 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2581 //this function originally written by KrimZon, made shorter by LordHavoc
2582 //20040203: rewritten by LordHavoc (no longer uses allocations)
2583 static int num_tokens = 0;
2584 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2585 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2586 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2587 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2588 void VM_tokenize (void)
2589 {
2590         const char *p;
2591
2592         VM_SAFEPARMCOUNT(1,VM_tokenize);
2593
2594         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2595         p = tokenize_string;
2596
2597         num_tokens = 0;
2598         for(;;)
2599         {
2600                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2601                         break;
2602
2603                 // skip whitespace here to find token start pos
2604                 while(*p && ISWHITESPACE(*p))
2605                         ++p;
2606
2607                 tokens_startpos[num_tokens] = p - tokenize_string;
2608                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2609                         break;
2610                 tokens_endpos[num_tokens] = p - tokenize_string;
2611                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2612                 ++num_tokens;
2613         }
2614
2615         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2616 }
2617
2618 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2619 void VM_tokenize_console (void)
2620 {
2621         const char *p;
2622
2623         VM_SAFEPARMCOUNT(1,VM_tokenize);
2624
2625         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2626         p = tokenize_string;
2627
2628         num_tokens = 0;
2629         for(;;)
2630         {
2631                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2632                         break;
2633
2634                 // skip whitespace here to find token start pos
2635                 while(*p && ISWHITESPACE(*p))
2636                         ++p;
2637
2638                 tokens_startpos[num_tokens] = p - tokenize_string;
2639                 if(!COM_ParseToken_Console(&p))
2640                         break;
2641                 tokens_endpos[num_tokens] = p - tokenize_string;
2642                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2643                 ++num_tokens;
2644         }
2645
2646         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2647 }
2648
2649 /*
2650 =========
2651 VM_tokenizebyseparator
2652
2653 float tokenizebyseparator(string s, string separator1, ...)
2654 =========
2655 */
2656 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2657 //this function returns the token preceding each instance of a separator (of
2658 //which there can be multiple), and the text following the last separator
2659 //useful for parsing certain kinds of data like IP addresses
2660 //example:
2661 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2662 //returns 4 and the tokens "10" "1" "2" "3".
2663 void VM_tokenizebyseparator (void)
2664 {
2665         int j, k;
2666         int numseparators;
2667         int separatorlen[7];
2668         const char *separators[7];
2669         const char *p, *p0;
2670         const char *token;
2671         char tokentext[MAX_INPUTLINE];
2672
2673         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2674
2675         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2676         p = tokenize_string;
2677
2678         numseparators = 0;
2679         for (j = 1;j < prog->argc;j++)
2680         {
2681                 // skip any blank separator strings
2682                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2683                 if (!s[0])
2684                         continue;
2685                 separators[numseparators] = s;
2686                 separatorlen[numseparators] = strlen(s);
2687                 numseparators++;
2688         }
2689
2690         num_tokens = 0;
2691         j = 0;
2692
2693         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2694         {
2695                 token = tokentext + j;
2696                 tokens_startpos[num_tokens] = p - tokenize_string;
2697                 p0 = p;
2698                 while (*p)
2699                 {
2700                         for (k = 0;k < numseparators;k++)
2701                         {
2702                                 if (!strncmp(p, separators[k], separatorlen[k]))
2703                                 {
2704                                         p += separatorlen[k];
2705                                         break;
2706                                 }
2707                         }
2708                         if (k < numseparators)
2709                                 break;
2710                         if (j < (int)sizeof(tokentext)-1)
2711                                 tokentext[j++] = *p;
2712                         p++;
2713                         p0 = p;
2714                 }
2715                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2716                 if (j >= (int)sizeof(tokentext))
2717                         break;
2718                 tokentext[j++] = 0;
2719                 tokens[num_tokens++] = PRVM_SetTempString(token);
2720                 if (!*p)
2721                         break;
2722         }
2723
2724         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2725 }
2726
2727 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2728 //this function originally written by KrimZon, made shorter by LordHavoc
2729 void VM_argv (void)
2730 {
2731         int token_num;
2732
2733         VM_SAFEPARMCOUNT(1,VM_argv);
2734
2735         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2736
2737         if(token_num < 0)
2738                 token_num += num_tokens;
2739
2740         if (token_num >= 0 && token_num < num_tokens)
2741                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2742         else
2743                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2744 }
2745
2746 //float(float n) argv_start_index = #515; // returns the start index of a token
2747 void VM_argv_start_index (void)
2748 {
2749         int token_num;
2750
2751         VM_SAFEPARMCOUNT(1,VM_argv);
2752
2753         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2754
2755         if(token_num < 0)
2756                 token_num += num_tokens;
2757
2758         if (token_num >= 0 && token_num < num_tokens)
2759                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2760         else
2761                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2762 }
2763
2764 //float(float n) argv_end_index = #516; // returns the end index of a token
2765 void VM_argv_end_index (void)
2766 {
2767         int token_num;
2768
2769         VM_SAFEPARMCOUNT(1,VM_argv);
2770
2771         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2772
2773         if(token_num < 0)
2774                 token_num += num_tokens;
2775
2776         if (token_num >= 0 && token_num < num_tokens)
2777                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2778         else
2779                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2780 }
2781
2782 /*
2783 =========
2784 VM_isserver
2785
2786 float   isserver()
2787 =========
2788 */
2789 void VM_isserver(void)
2790 {
2791         VM_SAFEPARMCOUNT(0,VM_serverstate);
2792
2793         PRVM_G_FLOAT(OFS_RETURN) = sv.active && (svs.maxclients > 1 || cls.state == ca_dedicated);
2794 }
2795
2796 /*
2797 =========
2798 VM_clientcount
2799
2800 float   clientcount()
2801 =========
2802 */
2803 void VM_clientcount(void)
2804 {
2805         VM_SAFEPARMCOUNT(0,VM_clientcount);
2806
2807         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2808 }
2809
2810 /*
2811 =========
2812 VM_clientstate
2813
2814 float   clientstate()
2815 =========
2816 */
2817 void VM_clientstate(void)
2818 {
2819         VM_SAFEPARMCOUNT(0,VM_clientstate);
2820
2821
2822         switch( cls.state ) {
2823                 case ca_uninitialized:
2824                 case ca_dedicated:
2825                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2826                         break;
2827                 case ca_disconnected:
2828                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2829                         break;
2830                 case ca_connected:
2831                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2832                         break;
2833                 default:
2834                         // should never be reached!
2835                         break;
2836         }
2837 }
2838
2839 /*
2840 =========
2841 VM_getostype
2842
2843 float   getostype(void)
2844 =========
2845 */ // not used at the moment -> not included in the common list
2846 void VM_getostype(void)
2847 {
2848         VM_SAFEPARMCOUNT(0,VM_getostype);
2849
2850         /*
2851         OS_WINDOWS
2852         OS_LINUX
2853         OS_MAC - not supported
2854         */
2855
2856 #ifdef WIN32
2857         PRVM_G_FLOAT(OFS_RETURN) = 0;
2858 #elif defined(MACOSX)
2859         PRVM_G_FLOAT(OFS_RETURN) = 2;
2860 #else
2861         PRVM_G_FLOAT(OFS_RETURN) = 1;
2862 #endif
2863 }
2864
2865 /*
2866 =========
2867 VM_gettime
2868
2869 float   gettime(void)
2870 =========
2871 */
2872 extern double host_starttime;
2873 float CDAudio_GetPosition(void);
2874 void VM_gettime(void)
2875 {
2876         int timer_index;
2877
2878         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2879
2880         if(prog->argc == 0)
2881         {
2882                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2883         }
2884         else
2885         {
2886                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2887         switch(timer_index)
2888         {
2889             case 0: // GETTIME_FRAMESTART
2890                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2891                 break;
2892             case 1: // GETTIME_REALTIME
2893                 PRVM_G_FLOAT(OFS_RETURN) = (float) Sys_DoubleTime();
2894                 break;
2895             case 2: // GETTIME_HIRES
2896                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - realtime);
2897                 break;
2898             case 3: // GETTIME_UPTIME
2899                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - host_starttime);
2900                 break;
2901             case 4: // GETTIME_CDTRACK
2902                 PRVM_G_FLOAT(OFS_RETURN) = (float) CDAudio_GetPosition();
2903                 break;
2904                         default:
2905                                 VM_Warning("VM_gettime: %s: unsupported timer specified, returning realtime\n", PRVM_NAME);
2906                                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2907                                 break;
2908                 }
2909         }
2910 }
2911
2912 /*
2913 =========
2914 VM_getsoundtime
2915
2916 float   getsoundtime(void)
2917 =========
2918 */
2919
2920 void VM_getsoundtime (void)
2921 {
2922         int entnum, entchannel, pnum;
2923         VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2924
2925         pnum = PRVM_GetProgNr();
2926         if (pnum == PRVM_MENUPROG)
2927         {
2928                 VM_Warning("VM_getsoundtime: %s: not supported on this progs\n", PRVM_NAME);
2929                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2930                 return;
2931         }
2932         entnum = ((pnum == PRVM_CLIENTPROG) ? MAX_EDICTS : 0) + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2933         entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
2934         entchannel = CHAN_USER2ENGINE(entchannel);
2935         if (!IS_CHAN(entchannel))
2936                 VM_Warning("VM_getsoundtime: %s: bad channel %i\n", PRVM_NAME, entchannel);
2937         PRVM_G_FLOAT(OFS_RETURN) = (float)S_GetEntChannelPosition(entnum, entchannel);
2938 }
2939
2940 /*
2941 =========
2942 VM_GetSoundLen
2943
2944 string  soundlength (string sample)
2945 =========
2946 */
2947 void VM_soundlength (void)
2948 {
2949         const char *s;
2950
2951         VM_SAFEPARMCOUNT(1, VM_soundlength);
2952
2953         s = PRVM_G_STRING(OFS_PARM0);
2954         PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
2955 }
2956
2957 /*
2958 =========
2959 VM_loadfromdata
2960
2961 loadfromdata(string data)
2962 =========
2963 */
2964 void VM_loadfromdata(void)
2965 {
2966         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2967
2968         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2969 }
2970
2971 /*
2972 ========================
2973 VM_parseentitydata
2974
2975 parseentitydata(entity ent, string data)
2976 ========================
2977 */
2978 void VM_parseentitydata(void)
2979 {
2980         prvm_edict_t *ent;
2981         const char *data;
2982
2983         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2984
2985         // get edict and test it
2986         ent = PRVM_G_EDICT(OFS_PARM0);
2987         if (ent->priv.required->free)
2988                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2989
2990         data = PRVM_G_STRING(OFS_PARM1);
2991
2992         // parse the opening brace
2993         if (!COM_ParseToken_Simple(&data, false, false) || com_token[0] != '{' )
2994                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2995
2996         PRVM_ED_ParseEdict (data, ent);
2997 }
2998
2999 /*
3000 =========
3001 VM_loadfromfile
3002
3003 loadfromfile(string file)
3004 =========
3005 */
3006 void VM_loadfromfile(void)
3007 {
3008         const char *filename;
3009         char *data;
3010
3011         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3012
3013         filename = PRVM_G_STRING(OFS_PARM0);
3014         if (FS_CheckNastyPath(filename, false))
3015         {
3016                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3017                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
3018                 return;
3019         }
3020
3021         // not conform with VM_fopen
3022         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3023         if (data == NULL)
3024                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3025
3026         PRVM_ED_LoadFromFile(data);
3027
3028         if(data)
3029                 Mem_Free(data);
3030 }
3031
3032
3033 /*
3034 =========
3035 VM_modulo
3036
3037 float   mod(float val, float m)
3038 =========
3039 */
3040 void VM_modulo(void)
3041 {
3042         int val, m;
3043         VM_SAFEPARMCOUNT(2,VM_module);
3044
3045         val = (int) PRVM_G_FLOAT(OFS_PARM0);
3046         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
3047
3048         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
3049 }
3050
3051 void VM_Search_Init(void)
3052 {
3053         int i;
3054         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3055                 prog->opensearches[i] = NULL;
3056 }
3057
3058 void VM_Search_Reset(void)
3059 {
3060         int i;
3061         // reset the fssearch list
3062         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3063         {
3064                 if(prog->opensearches[i])
3065                         FS_FreeSearch(prog->opensearches[i]);
3066                 prog->opensearches[i] = NULL;
3067         }
3068 }
3069
3070 /*
3071 =========
3072 VM_search_begin
3073
3074 float search_begin(string pattern, float caseinsensitive, float quiet)
3075 =========
3076 */
3077 void VM_search_begin(void)
3078 {
3079         int handle;
3080         const char *pattern;
3081         int caseinsens, quiet;
3082
3083         VM_SAFEPARMCOUNT(3, VM_search_begin);
3084
3085         pattern = PRVM_G_STRING(OFS_PARM0);
3086
3087         VM_CheckEmptyString(pattern);
3088
3089         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3090         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3091
3092         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3093                 if(!prog->opensearches[handle])
3094                         break;
3095
3096         if(handle >= PRVM_MAX_OPENSEARCHES)
3097         {
3098                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3099                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
3100                 return;
3101         }
3102
3103         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
3104                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3105         else
3106         {
3107                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin();
3108                 PRVM_G_FLOAT(OFS_RETURN) = handle;
3109         }
3110 }
3111
3112 /*
3113 =========
3114 VM_search_end
3115
3116 void    search_end(float handle)
3117 =========
3118 */
3119 void VM_search_end(void)
3120 {
3121         int handle;
3122         VM_SAFEPARMCOUNT(1, VM_search_end);
3123
3124         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3125
3126         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3127         {
3128                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
3129                 return;
3130         }
3131         if(prog->opensearches[handle] == NULL)
3132         {
3133                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
3134                 return;
3135         }
3136
3137         FS_FreeSearch(prog->opensearches[handle]);
3138         prog->opensearches[handle] = NULL;
3139         if(prog->opensearches_origin[handle])
3140                 PRVM_Free((char *)prog->opensearches_origin[handle]);
3141 }
3142
3143 /*
3144 =========
3145 VM_search_getsize
3146
3147 float   search_getsize(float handle)
3148 =========
3149 */
3150 void VM_search_getsize(void)
3151 {
3152         int handle;
3153         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
3154
3155         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3156
3157         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3158         {
3159                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
3160                 return;
3161         }
3162         if(prog->opensearches[handle] == NULL)
3163         {
3164                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
3165                 return;
3166         }
3167
3168         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3169 }
3170
3171 /*
3172 =========
3173 VM_search_getfilename
3174
3175 string  search_getfilename(float handle, float num)
3176 =========
3177 */
3178 void VM_search_getfilename(void)
3179 {
3180         int handle, filenum;
3181         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3182
3183         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3184         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3185
3186         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3187         {
3188                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
3189                 return;
3190         }
3191         if(prog->opensearches[handle] == NULL)
3192         {
3193                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
3194                 return;
3195         }
3196         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3197         {
3198                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
3199                 return;
3200         }
3201
3202         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog->opensearches[handle]->filenames[filenum]);
3203 }
3204
3205 /*
3206 =========
3207 VM_chr
3208
3209 string  chr(float ascii)
3210 =========
3211 */
3212 void VM_chr(void)
3213 {
3214         /*
3215         char tmp[2];
3216         VM_SAFEPARMCOUNT(1, VM_chr);
3217
3218         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3219         tmp[1] = 0;
3220
3221         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3222         */
3223         
3224         char tmp[8];
3225         int len;
3226         VM_SAFEPARMCOUNT(1, VM_chr);
3227
3228         len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3229         tmp[len] = 0;
3230         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3231 }
3232
3233 //=============================================================================
3234 // Draw builtins (client & menu)
3235
3236 /*
3237 =========
3238 VM_iscachedpic
3239
3240 float   iscachedpic(string pic)
3241 =========
3242 */
3243 void VM_iscachedpic(void)
3244 {
3245         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
3246
3247         // drawq hasnt such a function, thus always return true
3248         PRVM_G_FLOAT(OFS_RETURN) = false;
3249 }
3250
3251 /*
3252 =========
3253 VM_precache_pic
3254
3255 string  precache_pic(string pic)
3256 =========
3257 */
3258 void VM_precache_pic(void)
3259 {
3260         const char      *s;
3261
3262         VM_SAFEPARMCOUNT(1, VM_precache_pic);
3263
3264         s = PRVM_G_STRING(OFS_PARM0);
3265         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
3266         VM_CheckEmptyString (s);
3267
3268         // AK Draw_CachePic is supposed to always return a valid pointer
3269         if( Draw_CachePic_Flags(s, 0)->tex == r_texture_notexture )
3270                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3271 }
3272
3273 /*
3274 =========
3275 VM_freepic
3276
3277 freepic(string s)
3278 =========
3279 */
3280 void VM_freepic(void)
3281 {
3282         const char *s;
3283
3284         VM_SAFEPARMCOUNT(1,VM_freepic);
3285
3286         s = PRVM_G_STRING(OFS_PARM0);
3287         VM_CheckEmptyString (s);
3288
3289         Draw_FreePic(s);
3290 }
3291
3292 void getdrawfontscale(float *sx, float *sy)
3293 {
3294         vec3_t v;
3295         *sx = *sy = 1;
3296         VectorCopy(PRVM_drawglobalvector(drawfontscale), v);
3297         if(VectorLength2(v) > 0)
3298         {
3299                 *sx = v[0];
3300                 *sy = v[1];
3301         }
3302 }
3303
3304 dp_font_t *getdrawfont(void)
3305 {
3306         int f = (int) PRVM_drawglobalfloat(drawfont);
3307         if(f < 0 || f >= dp_fonts.maxsize)
3308                 return FONT_DEFAULT;
3309         return &dp_fonts.f[f];
3310 }
3311
3312 /*
3313 =========
3314 VM_drawcharacter
3315
3316 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
3317 =========
3318 */
3319 void VM_drawcharacter(void)
3320 {
3321         float *pos,*scale,*rgb;
3322         char   character;
3323         int flag;
3324         float sx, sy;
3325         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
3326
3327         character = (char) PRVM_G_FLOAT(OFS_PARM1);
3328         if(character == 0)
3329         {
3330                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3331                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
3332                 return;
3333         }
3334
3335         pos = PRVM_G_VECTOR(OFS_PARM0);
3336         scale = PRVM_G_VECTOR(OFS_PARM2);
3337         rgb = PRVM_G_VECTOR(OFS_PARM3);
3338         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3339
3340         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3341         {
3342                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3343                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3344                 return;
3345         }
3346
3347         if(pos[2] || scale[2])
3348                 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")));
3349
3350         if(!scale[0] || !scale[1])
3351         {
3352                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3353                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3354                 return;
3355         }
3356
3357         getdrawfontscale(&sx, &sy);
3358         DrawQ_String_Scale(pos[0], pos[1], &character, 1, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3359         PRVM_G_FLOAT(OFS_RETURN) = 1;
3360 }
3361
3362 /*
3363 =========
3364 VM_drawstring
3365
3366 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha[, float flag])
3367 =========
3368 */
3369 void VM_drawstring(void)
3370 {
3371         float *pos,*scale,*rgb;
3372         const char  *string;
3373         int flag = 0;
3374         float sx, sy;
3375         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawstring);
3376
3377         string = PRVM_G_STRING(OFS_PARM1);
3378         pos = PRVM_G_VECTOR(OFS_PARM0);
3379         scale = PRVM_G_VECTOR(OFS_PARM2);
3380         rgb = PRVM_G_VECTOR(OFS_PARM3);
3381         if (prog->argc >= 6)
3382                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3383
3384         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3385         {
3386                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3387                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3388                 return;
3389         }
3390
3391         if(!scale[0] || !scale[1])
3392         {
3393                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3394                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3395                 return;
3396         }
3397
3398         if(pos[2] || scale[2])
3399                 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")));
3400
3401         getdrawfontscale(&sx, &sy);
3402         DrawQ_String_Scale(pos[0], pos[1], string, 0, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3403         //Font_DrawString(pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true);
3404         PRVM_G_FLOAT(OFS_RETURN) = 1;
3405 }
3406
3407 /*
3408 =========
3409 VM_drawcolorcodedstring
3410
3411 float   drawcolorcodedstring(vector position, string text, vector scale, float alpha, float flag)
3412 /
3413 float   drawcolorcodedstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3414 =========
3415 */
3416 void VM_drawcolorcodedstring(void)
3417 {
3418         float *pos, *scale;
3419         const char  *string;
3420         int flag;
3421         vec3_t rgb;
3422         float sx, sy, alpha;
3423
3424         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawcolorcodedstring);
3425
3426         if (prog->argc == 6) // full 6 parms, like normal drawstring
3427         {
3428                 pos = PRVM_G_VECTOR(OFS_PARM0);
3429                 string = PRVM_G_STRING(OFS_PARM1);
3430                 scale = PRVM_G_VECTOR(OFS_PARM2);
3431                 VectorCopy(PRVM_G_VECTOR(OFS_PARM3), rgb); 
3432                 alpha = PRVM_G_FLOAT(OFS_PARM4);
3433                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3434         }
3435         else
3436         {
3437                 pos = PRVM_G_VECTOR(OFS_PARM0);
3438                 string = PRVM_G_STRING(OFS_PARM1);
3439                 scale = PRVM_G_VECTOR(OFS_PARM2);
3440                 rgb[0] = 1.0;
3441                 rgb[1] = 1.0;
3442                 rgb[2] = 1.0;
3443                 alpha = PRVM_G_FLOAT(OFS_PARM3);
3444                 flag = (int)PRVM_G_FLOAT(OFS_PARM4);
3445         }
3446
3447         if(flag < DRAWFLAG_NORMAL || flag >= DRAWFLAG_NUMFLAGS)
3448         {
3449                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3450                 VM_Warning("VM_drawcolorcodedstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3451                 return;
3452         }
3453
3454         if(!scale[0] || !scale[1])
3455         {
3456                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3457                 VM_Warning("VM_drawcolorcodedstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3458                 return;
3459         }
3460
3461         if(pos[2] || scale[2])
3462                 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")));
3463
3464         getdrawfontscale(&sx, &sy);
3465         DrawQ_String_Scale(pos[0], pos[1], string, 0, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], alpha, flag, NULL, false, getdrawfont());
3466         if (prog->argc == 6) // also return vector of last color
3467                 VectorCopy(DrawQ_Color, PRVM_G_VECTOR(OFS_RETURN));
3468         else
3469                 PRVM_G_FLOAT(OFS_RETURN) = 1;
3470 }
3471 /*
3472 =========
3473 VM_stringwidth
3474
3475 float   stringwidth(string text, float allowColorCodes, float size)
3476 =========
3477 */
3478 void VM_stringwidth(void)
3479 {
3480         const char  *string;
3481         float *szv;
3482         float mult; // sz is intended font size so we can later add freetype support, mult is font size multiplier in pixels per character cell
3483         int colors;
3484         float sx, sy;
3485         size_t maxlen = 0;
3486         VM_SAFEPARMCOUNTRANGE(2,3,VM_drawstring);
3487
3488         getdrawfontscale(&sx, &sy);
3489         if(prog->argc == 3)
3490         {
3491                 szv = PRVM_G_VECTOR(OFS_PARM2);
3492                 mult = 1;
3493         }
3494         else
3495         {
3496                 // we want the width for 8x8 font size, divided by 8
3497                 static float defsize[] = {8, 8};
3498                 szv = defsize;
3499                 mult = 0.125;
3500                 // to make sure snapping is turned off, ALWAYS use a nontrivial scale in this case
3501                 if(sx >= 0.9 && sx <= 1.1)
3502                 {
3503                         mult *= 2;
3504                         sx /= 2;
3505                         sy /= 2;
3506                 }
3507         }
3508
3509         string = PRVM_G_STRING(OFS_PARM0);
3510         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3511
3512         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth_UntilWidth_TrackColors_Scale(string, &maxlen, szv[0], szv[1], sx, sy, NULL, !colors, getdrawfont(), 1000000000) * mult;
3513 /*
3514         if(prog->argc == 3)
3515         {
3516                 mult = sz = PRVM_G_FLOAT(OFS_PARM2);
3517         }
3518         else
3519         {
3520                 sz = 8;
3521                 mult = 1;
3522         }
3523
3524         string = PRVM_G_STRING(OFS_PARM0);
3525         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3526
3527         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth(string, 0, !colors, getdrawfont()) * mult; // 1x1 characters, don't actually draw
3528 */
3529 }
3530
3531 /*
3532 =========
3533 VM_findfont
3534
3535 float findfont(string s)
3536 =========
3537 */
3538
3539 float getdrawfontnum(const char *fontname)
3540 {
3541         int i;
3542
3543         for(i = 0; i < dp_fonts.maxsize; ++i)
3544                 if(!strcmp(dp_fonts.f[i].title, fontname))
3545                         return i;
3546         return -1;
3547 }
3548
3549 void VM_findfont(void)
3550 {
3551         VM_SAFEPARMCOUNT(1,VM_findfont);
3552         PRVM_G_FLOAT(OFS_RETURN) = getdrawfontnum(PRVM_G_STRING(OFS_PARM0));
3553 }
3554
3555 /*
3556 =========
3557 VM_loadfont
3558
3559 float loadfont(string fontname, string fontmaps, string sizes, float slot)
3560 =========
3561 */
3562
3563 dp_font_t *FindFont(const char *title, qboolean allocate_new);
3564 void LoadFont(qboolean override, const char *name, dp_font_t *fnt, float scale, float voffset);
3565 void VM_loadfont(void)
3566 {
3567         const char *fontname, *filelist, *sizes, *c, *cm;
3568         char mainfont[MAX_QPATH];
3569         int i, numsizes;
3570         float sz, scale, voffset;
3571         dp_font_t *f;
3572
3573         VM_SAFEPARMCOUNTRANGE(3,6,VM_loadfont);
3574
3575         fontname = PRVM_G_STRING(OFS_PARM0);
3576         if (!fontname[0])
3577                 fontname = "default";
3578
3579         filelist = PRVM_G_STRING(OFS_PARM1);
3580         if (!filelist[0])
3581                 filelist = "gfx/conchars";
3582
3583         sizes = PRVM_G_STRING(OFS_PARM2);
3584         if (!sizes[0])
3585                 sizes = "10";
3586
3587         // find a font
3588         f = NULL;
3589         if (prog->argc >= 4)
3590         {
3591                 i = PRVM_G_FLOAT(OFS_PARM3);
3592                 if (i >= 0 && i < dp_fonts.maxsize)
3593                 {
3594                         f = &dp_fonts.f[i];
3595                         strlcpy(f->title, fontname, sizeof(f->title)); // replace name
3596                 }
3597         }
3598         if (!f)
3599                 f = FindFont(fontname, true);
3600         if (!f)
3601         {
3602                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3603                 return; // something go wrong
3604         }
3605
3606         memset(f->fallbacks, 0, sizeof(f->fallbacks));
3607         memset(f->fallback_faces, 0, sizeof(f->fallback_faces));
3608
3609         // first font is handled "normally"
3610         c = strchr(filelist, ':');
3611         cm = strchr(filelist, ',');
3612         if(c && (!cm || c < cm))
3613                 f->req_face = atoi(c+1);
3614         else
3615         {
3616                 f->req_face = 0;
3617                 c = cm;
3618         }
3619         if(!c || (c - filelist) > MAX_QPATH)
3620                 strlcpy(mainfont, filelist, sizeof(mainfont));
3621         else
3622         {
3623                 memcpy(mainfont, filelist, c - filelist);
3624                 mainfont[c - filelist] = 0;
3625         }
3626
3627         // handle fallbacks
3628         for(i = 0; i < MAX_FONT_FALLBACKS; ++i)
3629         {
3630                 c = strchr(filelist, ',');
3631                 if(!c)
3632                         break;
3633                 filelist = c + 1;
3634                 if(!*filelist)
3635                         break;
3636                 c = strchr(filelist, ':');
3637                 cm = strchr(filelist, ',');
3638                 if(c && (!cm || c < cm))
3639                         f->fallback_faces[i] = atoi(c+1);
3640                 else
3641                 {
3642                         f->fallback_faces[i] = 0; // f->req_face; could make it stick to the default-font's face index
3643                         c = cm;
3644                 }
3645                 if(!c || (c-filelist) > MAX_QPATH)
3646                 {
3647                         strlcpy(f->fallbacks[i], filelist, sizeof(mainfont));
3648                 }
3649                 else
3650                 {
3651                         memcpy(f->fallbacks[i], filelist, c - filelist);
3652                         f->fallbacks[i][c - filelist] = 0;
3653                 }
3654         }
3655
3656         // handle sizes
3657         for(i = 0; i < MAX_FONT_SIZES; ++i)
3658                 f->req_sizes[i] = -1;
3659         for (numsizes = 0,c = sizes;;)
3660         {
3661                 if (!COM_ParseToken_VM_Tokenize(&c, 0))
3662                         break;
3663                 sz = atof(com_token);
3664                 // detect crap size
3665                 if (sz < 0.001f || sz > 1000.0f)
3666                 {
3667                         VM_Warning("VM_loadfont: crap size %s", com_token);
3668                         continue;
3669                 }
3670                 // check overflow
3671                 if (numsizes == MAX_FONT_SIZES)
3672                 {
3673                         VM_Warning("VM_loadfont: MAX_FONT_SIZES = %i exceeded", MAX_FONT_SIZES);
3674                         break;
3675                 }
3676                 f->req_sizes[numsizes] = sz;
3677                 numsizes++;
3678         }
3679
3680         // additional scale/hoffset parms
3681         scale = 1;
3682         voffset = 0;
3683         if (prog->argc >= 5)
3684         {
3685                 scale = PRVM_G_FLOAT(OFS_PARM4);
3686                 if (scale <= 0)
3687                         scale = 1;
3688         }
3689         if (prog->argc >= 6)
3690                 voffset = PRVM_G_FLOAT(OFS_PARM5);
3691
3692         // load
3693         LoadFont(true, mainfont, f, scale, voffset);
3694
3695         // return index of loaded font
3696         PRVM_G_FLOAT(OFS_RETURN) = (f - dp_fonts.f);
3697 }
3698
3699 /*
3700 =========
3701 VM_drawpic
3702
3703 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
3704 =========
3705 */
3706 void VM_drawpic(void)
3707 {
3708         const char *picname;
3709         float *size, *pos, *rgb;
3710         int flag = 0;
3711
3712         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawpic);
3713
3714         picname = PRVM_G_STRING(OFS_PARM1);
3715         VM_CheckEmptyString (picname);
3716
3717         // is pic cached ? no function yet for that
3718         if(!1)
3719         {
3720                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3721                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
3722                 return;
3723         }
3724
3725         pos = PRVM_G_VECTOR(OFS_PARM0);
3726         size = PRVM_G_VECTOR(OFS_PARM2);
3727         rgb = PRVM_G_VECTOR(OFS_PARM3);
3728         if (prog->argc >= 6)
3729                 flag = (int) PRVM_G_FLOAT(OFS_PARM5);
3730
3731         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3732         {
3733                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3734                 VM_Warning("VM_drawpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3735                 return;
3736         }
3737
3738         if(pos[2] || size[2])
3739                 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")));
3740
3741         DrawQ_Pic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT), size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
3742         PRVM_G_FLOAT(OFS_RETURN) = 1;
3743 }
3744 /*
3745 =========
3746 VM_drawrotpic
3747
3748 float   drawrotpic(vector position, string pic, vector size, vector org, float angle, vector rgb, float alpha, float flag)
3749 =========
3750 */
3751 void VM_drawrotpic(void)
3752 {
3753         const char *picname;
3754         float *size, *pos, *org, *rgb;
3755         int flag;
3756
3757         VM_SAFEPARMCOUNT(8,VM_drawrotpic);
3758
3759         picname = PRVM_G_STRING(OFS_PARM1);
3760         VM_CheckEmptyString (picname);
3761
3762         // is pic cached ? no function yet for that
3763         if(!1)
3764         {
3765                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3766                 VM_Warning("VM_drawrotpic: %s: %s not cached !\n", PRVM_NAME, picname);
3767                 return;
3768         }
3769
3770         pos = PRVM_G_VECTOR(OFS_PARM0);
3771         size = PRVM_G_VECTOR(OFS_PARM2);
3772         org = PRVM_G_VECTOR(OFS_PARM3);
3773         rgb = PRVM_G_VECTOR(OFS_PARM5);
3774         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3775
3776         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3777         {
3778                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3779                 VM_Warning("VM_drawrotpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3780                 return;
3781         }
3782
3783         if(pos[2] || size[2] || org[2])
3784                 Con_Printf("VM_drawrotpic: z value from pos/size/org discarded\n");
3785
3786         DrawQ_RotPic(pos[0], pos[1], Draw_CachePic_Flags(picname, CACHEPICFLAG_NOTPERSISTENT), 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);
3787         PRVM_G_FLOAT(OFS_RETURN) = 1;
3788 }
3789 /*
3790 =========
3791 VM_drawsubpic
3792
3793 float   drawsubpic(vector position, vector size, string pic, vector srcPos, vector srcSize, vector rgb, float alpha, float flag)
3794
3795 =========
3796 */
3797 void VM_drawsubpic(void)
3798 {
3799         const char *picname;
3800         float *size, *pos, *rgb, *srcPos, *srcSize, alpha;
3801         int flag;
3802
3803         VM_SAFEPARMCOUNT(8,VM_drawsubpic);
3804
3805         picname = PRVM_G_STRING(OFS_PARM2);
3806         VM_CheckEmptyString (picname);
3807
3808         // is pic cached ? no function yet for that
3809         if(!1)
3810         {
3811                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3812                 VM_Warning("VM_drawsubpic: %s: %s not cached !\n", PRVM_NAME, picname);
3813                 return;
3814         }
3815
3816         pos = PRVM_G_VECTOR(OFS_PARM0);
3817         size = PRVM_G_VECTOR(OFS_PARM1);
3818         srcPos = PRVM_G_VECTOR(OFS_PARM3);
3819         srcSize = PRVM_G_VECTOR(OFS_PARM4);
3820         rgb = PRVM_G_VECTOR(OFS_PARM5);
3821         alpha = PRVM_G_FLOAT(OFS_PARM6);
3822         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3823
3824         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3825         {
3826                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3827                 VM_Warning("VM_drawsubpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3828                 return;
3829         }
3830
3831         if(pos[2] || size[2])
3832                 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")));
3833
3834         DrawQ_SuperPic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT),
3835                 size[0], size[1],
3836                 srcPos[0],              srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3837                 srcPos[0] + srcSize[0], srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3838                 srcPos[0],              srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3839                 srcPos[0] + srcSize[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3840                 flag);
3841         PRVM_G_FLOAT(OFS_RETURN) = 1;
3842 }
3843
3844 /*
3845 =========
3846 VM_drawfill
3847
3848 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
3849 =========
3850 */
3851 void VM_drawfill(void)
3852 {
3853         float *size, *pos, *rgb;
3854         int flag;
3855
3856         VM_SAFEPARMCOUNT(5,VM_drawfill);
3857
3858
3859         pos = PRVM_G_VECTOR(OFS_PARM0);
3860         size = PRVM_G_VECTOR(OFS_PARM1);
3861         rgb = PRVM_G_VECTOR(OFS_PARM2);
3862         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
3863
3864         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3865         {
3866                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3867                 VM_Warning("VM_drawfill: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3868                 return;
3869         }
3870
3871         if(pos[2] || size[2])
3872                 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")));
3873
3874         DrawQ_Fill(pos[0], pos[1], size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
3875         PRVM_G_FLOAT(OFS_RETURN) = 1;
3876 }
3877
3878 /*
3879 =========
3880 VM_drawsetcliparea
3881
3882 drawsetcliparea(float x, float y, float width, float height)
3883 =========
3884 */
3885 void VM_drawsetcliparea(void)
3886 {
3887         float x,y,w,h;
3888         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
3889
3890         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
3891         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
3892         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
3893         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
3894
3895         DrawQ_SetClipArea(x, y, w, h);
3896 }
3897
3898 /*
3899 =========
3900 VM_drawresetcliparea
3901
3902 drawresetcliparea()
3903 =========
3904 */
3905 void VM_drawresetcliparea(void)
3906 {
3907         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
3908
3909         DrawQ_ResetClipArea();
3910 }
3911
3912 /*
3913 =========
3914 VM_getimagesize
3915
3916 vector  getimagesize(string pic)
3917 =========
3918 */
3919 void VM_getimagesize(void)
3920 {
3921         const char *p;
3922         cachepic_t *pic;
3923
3924         VM_SAFEPARMCOUNT(1,VM_getimagesize);
3925
3926         p = PRVM_G_STRING(OFS_PARM0);
3927         VM_CheckEmptyString (p);
3928
3929         pic = Draw_CachePic_Flags (p, CACHEPICFLAG_NOTPERSISTENT);
3930
3931         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
3932         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
3933         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3934 }
3935
3936 /*
3937 =========
3938 VM_keynumtostring
3939
3940 string keynumtostring(float keynum)
3941 =========
3942 */
3943 void VM_keynumtostring (void)
3944 {
3945         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3946
3947         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0)));
3948 }
3949
3950 /*
3951 =========
3952 VM_findkeysforcommand
3953
3954 string  findkeysforcommand(string command, float bindmap)
3955
3956 the returned string is an altstring
3957 =========
3958 */
3959 #define FKFC_NUMKEYS 5
3960 void M_FindKeysForCommand(const char *command, int *keys);
3961 void VM_findkeysforcommand(void)
3962 {
3963         const char *cmd;
3964         char ret[VM_STRINGTEMP_LENGTH];
3965         int keys[FKFC_NUMKEYS];
3966         int i;
3967         int bindmap;
3968
3969         VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3970
3971         cmd = PRVM_G_STRING(OFS_PARM0);
3972         if(prog->argc == 2)
3973                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3974         else
3975                 bindmap = 0; // consistent to "bind"
3976
3977         VM_CheckEmptyString(cmd);
3978
3979         Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3980
3981         ret[0] = 0;
3982         for(i = 0; i < FKFC_NUMKEYS; i++)
3983                 strlcat(ret, va(" \'%i\'", keys[i]), sizeof(ret));
3984
3985         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(ret);
3986 }
3987
3988 /*
3989 =========
3990 VM_stringtokeynum
3991
3992 float stringtokeynum(string key)
3993 =========
3994 */
3995 void VM_stringtokeynum (void)
3996 {
3997         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
3998
3999         PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
4000 }
4001
4002 /*
4003 =========
4004 VM_getkeybind
4005
4006 string getkeybind(float key, float bindmap)
4007 =========
4008 */
4009 void VM_getkeybind (void)
4010 {
4011         int bindmap;
4012         VM_SAFEPARMCOUNTRANGE(1, 2, VM_CL_getkeybind);
4013         if(prog->argc == 2)
4014                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
4015         else
4016                 bindmap = 0; // consistent to "bind"
4017
4018         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap));
4019 }
4020
4021 /*
4022 =========
4023 VM_setkeybind
4024
4025 float setkeybind(float key, string cmd, float bindmap)
4026 =========
4027 */
4028 void VM_setkeybind (void)
4029 {
4030         int bindmap;
4031         VM_SAFEPARMCOUNTRANGE(2, 3, VM_CL_setkeybind);
4032         if(prog->argc == 3)
4033                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
4034         else
4035                 bindmap = 0; // consistent to "bind"
4036
4037         PRVM_G_FLOAT(OFS_RETURN) = 0;
4038         if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
4039                 PRVM_G_FLOAT(OFS_RETURN) = 1;
4040 }
4041
4042 /*
4043 =========
4044 VM_getbindmap
4045
4046 vector getbindmaps()
4047 =========
4048 */
4049 void VM_getbindmaps (void)
4050 {
4051         int fg, bg;
4052         VM_SAFEPARMCOUNT(0, VM_CL_getbindmap);
4053         Key_GetBindMap(&fg, &bg);
4054         PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
4055         PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
4056         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4057 }
4058
4059 /*
4060 =========
4061 VM_setbindmap
4062
4063 float setbindmaps(vector bindmap)
4064 =========
4065 */
4066 void VM_setbindmaps (void)
4067 {
4068         VM_SAFEPARMCOUNT(1, VM_CL_setbindmap);
4069         PRVM_G_FLOAT(OFS_RETURN) = 0;
4070         if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
4071                 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
4072                         PRVM_G_FLOAT(OFS_RETURN) = 1;
4073 }
4074
4075 // CL_Video interface functions
4076
4077 /*
4078 ========================
4079 VM_cin_open
4080
4081 float cin_open(string file, string name)
4082 ========================
4083 */
4084 void VM_cin_open( void )
4085 {
4086         const char *file;
4087         const char *name;
4088
4089         VM_SAFEPARMCOUNT( 2, VM_cin_open );
4090
4091         file = PRVM_G_STRING( OFS_PARM0 );
4092         name = PRVM_G_STRING( OFS_PARM1 );
4093
4094         VM_CheckEmptyString( file );
4095     VM_CheckEmptyString( name );
4096
4097         if( CL_OpenVideo( file, name, MENUOWNER, "" ) )
4098                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
4099         else
4100                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4101 }
4102
4103 /*
4104 ========================
4105 VM_cin_close
4106
4107 void cin_close(string name)
4108 ========================
4109 */
4110 void VM_cin_close( void )
4111 {
4112         const char *name;
4113
4114         VM_SAFEPARMCOUNT( 1, VM_cin_close );
4115
4116         name = PRVM_G_STRING( OFS_PARM0 );
4117         VM_CheckEmptyString( name );
4118
4119         CL_CloseVideo( CL_GetVideoByName( name ) );
4120 }
4121
4122 /*
4123 ========================
4124 VM_cin_setstate
4125 void cin_setstate(string name, float type)
4126 ========================
4127 */
4128 void VM_cin_setstate( void )
4129 {
4130         const char *name;
4131         clvideostate_t  state;
4132         clvideo_t               *video;
4133
4134         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
4135
4136         name = PRVM_G_STRING( OFS_PARM0 );
4137         VM_CheckEmptyString( name );
4138
4139         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
4140
4141         video = CL_GetVideoByName( name );
4142         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
4143                 CL_SetVideoState( video, state );
4144 }
4145
4146 /*
4147 ========================
4148 VM_cin_getstate
4149
4150 float cin_getstate(string name)
4151 ========================
4152 */
4153 void VM_cin_getstate( void )
4154 {
4155         const char *name;
4156         clvideo_t               *video;
4157
4158         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
4159
4160         name = PRVM_G_STRING( OFS_PARM0 );
4161         VM_CheckEmptyString( name );
4162
4163         video = CL_GetVideoByName( name );
4164         if( video )
4165                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
4166         else
4167                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4168 }
4169
4170 /*
4171 ========================
4172 VM_cin_restart
4173
4174 void cin_restart(string name)
4175 ========================
4176 */
4177 void VM_cin_restart( void )
4178 {
4179         const char *name;
4180         clvideo_t               *video;
4181
4182         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
4183
4184         name = PRVM_G_STRING( OFS_PARM0 );
4185         VM_CheckEmptyString( name );
4186
4187         video = CL_GetVideoByName( name );
4188         if( video )
4189                 CL_RestartVideo( video );
4190 }
4191
4192 /*
4193 ========================
4194 VM_Gecko_Init
4195 ========================
4196 */
4197 void VM_Gecko_Init( void ) {
4198         // the prog struct is memset to 0 by Initprog? [12/6/2007 Black]
4199         // FIXME: remove the other _Init functions then, too? [12/6/2007 Black]
4200 }
4201
4202 /*
4203 ========================
4204 VM_Gecko_Destroy
4205 ========================
4206 */
4207 void VM_Gecko_Destroy( void ) {
4208         int i;
4209         for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
4210                 clgecko_t **instance = &prog->opengeckoinstances[ i ];
4211                 if( *instance ) {
4212                         CL_Gecko_DestroyBrowser( *instance );
4213                 }
4214                 *instance = NULL;
4215         }
4216 }
4217
4218 /*
4219 ========================
4220 VM_gecko_create
4221
4222 float[bool] gecko_create( string name )
4223 ========================
4224 */
4225 void VM_gecko_create( void ) {
4226         const char *name;
4227         int i;
4228         clgecko_t *instance;
4229         
4230         VM_SAFEPARMCOUNT( 1, VM_gecko_create );
4231
4232         name = PRVM_G_STRING( OFS_PARM0 );
4233         VM_CheckEmptyString( name );
4234
4235         // find an empty slot for this gecko browser..
4236         for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
4237                 if( prog->opengeckoinstances[ i ] == NULL ) {
4238                         break;
4239                 }
4240         }
4241         if( i == PRVM_MAX_GECKOINSTANCES ) {
4242                         VM_Warning("VM_gecko_create: %s ran out of gecko handles (%i)\n", PRVM_NAME, PRVM_MAX_GECKOINSTANCES);
4243                         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4244                         return;
4245         }
4246
4247         instance = prog->opengeckoinstances[ i ] = CL_Gecko_CreateBrowser( name, PRVM_GetProgNr() );
4248    if( !instance ) {
4249                 // TODO: error handling [12/3/2007 Black]
4250                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4251                 return;
4252         }
4253         PRVM_G_FLOAT( OFS_RETURN ) = 1;
4254 }
4255
4256 /*
4257 ========================
4258 VM_gecko_destroy
4259
4260 void gecko_destroy( string name )
4261 ========================
4262 */
4263 void VM_gecko_destroy( void ) {
4264         const char *name;
4265         clgecko_t *instance;
4266
4267         VM_SAFEPARMCOUNT( 1, VM_gecko_destroy );
4268
4269         name = PRVM_G_STRING( OFS_PARM0 );
4270         VM_CheckEmptyString( name );
4271         instance = CL_Gecko_FindBrowser( name );
4272         if( !instance ) {
4273                 return;
4274         }
4275         CL_Gecko_DestroyBrowser( instance );
4276 }
4277
4278 /*
4279 ========================
4280 VM_gecko_navigate
4281
4282 void gecko_navigate( string name, string URI )
4283 ========================
4284 */
4285 void VM_gecko_navigate( void ) {
4286         const char *name;
4287         const char *URI;
4288         clgecko_t *instance;
4289
4290         VM_SAFEPARMCOUNT( 2, VM_gecko_navigate );
4291
4292         name = PRVM_G_STRING( OFS_PARM0 );
4293         URI = PRVM_G_STRING( OFS_PARM1 );
4294         VM_CheckEmptyString( name );
4295         VM_CheckEmptyString( URI );
4296
4297    instance = CL_Gecko_FindBrowser( name );
4298         if( !instance ) {
4299                 return;
4300         }
4301         CL_Gecko_NavigateToURI( instance, URI );
4302 }
4303
4304 /*
4305 ========================
4306 VM_gecko_keyevent
4307
4308 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
4309 ========================
4310 */
4311 void VM_gecko_keyevent( void ) {
4312         const char *name;
4313         unsigned int key;
4314         clgecko_buttoneventtype_t eventtype;
4315         clgecko_t *instance;
4316
4317         VM_SAFEPARMCOUNT( 3, VM_gecko_keyevent );
4318
4319         name = PRVM_G_STRING( OFS_PARM0 );
4320         VM_CheckEmptyString( name );
4321         key = (unsigned int) PRVM_G_FLOAT( OFS_PARM1 );
4322         switch( (unsigned int) PRVM_G_FLOAT( OFS_PARM2 ) ) {
4323         case 0:
4324                 eventtype = CLG_BET_DOWN;
4325                 break;
4326         case 1:
4327                 eventtype = CLG_BET_UP;
4328                 break;
4329         case 2:
4330                 eventtype = CLG_BET_PRESS;
4331                 break;
4332         case 3:
4333                 eventtype = CLG_BET_DOUBLECLICK;
4334                 break;
4335         default:
4336                 // TODO: console printf? [12/3/2007 Black]
4337                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4338                 return;
4339         }
4340
4341         instance = CL_Gecko_FindBrowser( name );
4342         if( !instance ) {
4343                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4344                 return;
4345         }
4346
4347         PRVM_G_FLOAT( OFS_RETURN ) = (CL_Gecko_Event_Key( instance, (keynum_t) key, eventtype ) == true);
4348 }
4349
4350 /*
4351 ========================
4352 VM_gecko_movemouse
4353
4354 void gecko_mousemove( string name, float x, float y )
4355 ========================
4356 */
4357 void VM_gecko_movemouse( void ) {
4358         const char *name;
4359         float x, y;
4360         clgecko_t *instance;
4361
4362         VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
4363
4364         name = PRVM_G_STRING( OFS_PARM0 );
4365         VM_CheckEmptyString( name );
4366         x = PRVM_G_FLOAT( OFS_PARM1 );
4367         y = PRVM_G_FLOAT( OFS_PARM2 );
4368         
4369         instance = CL_Gecko_FindBrowser( name );
4370         if( !instance ) {
4371                 return;
4372         }
4373         CL_Gecko_Event_CursorMove( instance, x, y );
4374 }
4375
4376
4377 /*
4378 ========================
4379 VM_gecko_resize
4380
4381 void gecko_resize( string name, float w, float h )
4382 ========================
4383 */
4384 void VM_gecko_resize( void ) {
4385         const char *name;
4386         float w, h;
4387         clgecko_t *instance;
4388
4389         VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
4390
4391         name = PRVM_G_STRING( OFS_PARM0 );
4392         VM_CheckEmptyString( name );
4393         w = PRVM_G_FLOAT( OFS_PARM1 );
4394         h = PRVM_G_FLOAT( OFS_PARM2 );
4395         
4396         instance = CL_Gecko_FindBrowser( name );
4397         if( !instance ) {
4398                 return;
4399         }
4400         CL_Gecko_Resize( instance, (int) w, (int) h );
4401 }
4402
4403
4404 /*
4405 ========================
4406 VM_gecko_get_texture_extent
4407
4408 vector gecko_get_texture_extent( string name )
4409 ========================
4410 */
4411 void VM_gecko_get_texture_extent( void ) {
4412         const char *name;
4413         clgecko_t *instance;
4414
4415         VM_SAFEPARMCOUNT( 1, VM_gecko_movemouse );
4416
4417         name = PRVM_G_STRING( OFS_PARM0 );
4418         VM_CheckEmptyString( name );
4419         
4420         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4421         instance = CL_Gecko_FindBrowser( name );
4422         if( !instance ) {
4423                 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
4424                 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
4425                 return;
4426         }
4427         CL_Gecko_GetTextureExtent( instance, 
4428                 PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_RETURN)+1 );
4429 }
4430
4431
4432
4433 /*
4434 ==============
4435 VM_makevectors
4436
4437 Writes new values for v_forward, v_up, and v_right based on angles
4438 void makevectors(vector angle)
4439 ==============
4440 */
4441 void VM_makevectors (void)
4442 {
4443         VM_SAFEPARMCOUNT(1, VM_makevectors);
4444         AngleVectors(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4445 }
4446
4447 /*
4448 ==============
4449 VM_vectorvectors
4450
4451 Writes new values for v_forward, v_up, and v_right based on the given forward vector
4452 vectorvectors(vector)
4453 ==============
4454 */
4455 void VM_vectorvectors (void)
4456 {
4457         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
4458         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward));
4459         VectorVectors(PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4460 }
4461
4462 /*
4463 ========================
4464 VM_drawline
4465
4466 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
4467 ========================
4468 */
4469 void VM_drawline (void)
4470 {
4471         float   *c1, *c2, *rgb;
4472         float   alpha, width;
4473         unsigned char   flags;
4474
4475         VM_SAFEPARMCOUNT(6, VM_drawline);
4476         width   = PRVM_G_FLOAT(OFS_PARM0);
4477         c1              = PRVM_G_VECTOR(OFS_PARM1);
4478         c2              = PRVM_G_VECTOR(OFS_PARM2);
4479         rgb             = PRVM_G_VECTOR(OFS_PARM3);
4480         alpha   = PRVM_G_FLOAT(OFS_PARM4);
4481         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
4482         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
4483 }
4484
4485 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
4486 void VM_bitshift (void)
4487 {
4488         int n1, n2;
4489         VM_SAFEPARMCOUNT(2, VM_bitshift);
4490
4491         n1 = (int)fabs((float)((int)PRVM_G_FLOAT(OFS_PARM0)));
4492         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
4493         if(!n1)
4494                 PRVM_G_FLOAT(OFS_RETURN) = n1;
4495         else
4496         if(n2 < 0)
4497                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
4498         else
4499                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
4500 }
4501
4502 ////////////////////////////////////////
4503 // AltString functions
4504 ////////////////////////////////////////
4505
4506 /*
4507 ========================
4508 VM_altstr_count
4509
4510 float altstr_count(string)
4511 ========================
4512 */
4513 void VM_altstr_count( void )
4514 {
4515         const char *altstr, *pos;
4516         int     count;
4517
4518         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
4519
4520         altstr = PRVM_G_STRING( OFS_PARM0 );
4521         //VM_CheckEmptyString( altstr );
4522
4523         for( count = 0, pos = altstr ; *pos ; pos++ ) {
4524                 if( *pos == '\\' ) {
4525                         if( !*++pos ) {
4526                                 break;
4527                         }
4528                 } else if( *pos == '\'' ) {
4529                         count++;
4530                 }
4531         }
4532
4533         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
4534 }
4535
4536 /*
4537 ========================
4538 VM_altstr_prepare
4539
4540 string altstr_prepare(string)
4541 ========================
4542 */
4543 void VM_altstr_prepare( void )
4544 {
4545         char *out;
4546         const char *instr, *in;
4547         int size;
4548         char outstr[VM_STRINGTEMP_LENGTH];
4549
4550         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
4551
4552         instr = PRVM_G_STRING( OFS_PARM0 );
4553
4554         for( out = outstr, in = instr, size = sizeof(outstr) - 1 ; size && *in ; size--, in++, out++ )
4555                 if( *in == '\'' ) {
4556                         *out++ = '\\';
4557                         *out = '\'';
4558                         size--;
4559                 } else
4560                         *out = *in;
4561         *out = 0;
4562
4563         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4564 }
4565
4566 /*
4567 ========================
4568 VM_altstr_get
4569
4570 string altstr_get(string, float)
4571 ========================
4572 */
4573 void VM_altstr_get( void )
4574 {
4575         const char *altstr, *pos;
4576         char *out;
4577         int count, size;
4578         char outstr[VM_STRINGTEMP_LENGTH];
4579
4580         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
4581
4582         altstr = PRVM_G_STRING( OFS_PARM0 );
4583
4584         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
4585         count = count * 2 + 1;
4586
4587         for( pos = altstr ; *pos && count ; pos++ )
4588                 if( *pos == '\\' ) {
4589                         if( !*++pos )
4590                                 break;
4591                 } else if( *pos == '\'' )
4592                         count--;
4593
4594         if( !*pos ) {
4595                 PRVM_G_INT( OFS_RETURN ) = 0;
4596                 return;
4597         }
4598
4599         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
4600                 if( *pos == '\\' ) {
4601                         if( !*++pos )
4602                                 break;
4603                         *out = *pos;
4604                         size--;
4605                 } else if( *pos == '\'' )
4606                         break;
4607                 else
4608                         *out = *pos;
4609
4610         *out = 0;
4611         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4612 }
4613
4614 /*
4615 ========================
4616 VM_altstr_set
4617
4618 string altstr_set(string altstr, float num, string set)
4619 ========================
4620 */
4621 void VM_altstr_set( void )
4622 {
4623     int num;
4624         const char *altstr, *str;
4625         const char *in;
4626         char *out;
4627         char outstr[VM_STRINGTEMP_LENGTH];
4628
4629         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
4630
4631         altstr = PRVM_G_STRING( OFS_PARM0 );
4632
4633         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4634
4635         str = PRVM_G_STRING( OFS_PARM2 );
4636
4637         out = outstr;
4638         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
4639                 if( *in == '\\' ) {
4640                         if( !*++in ) {
4641                                 break;
4642                         }
4643                 } else if( *in == '\'' ) {
4644                         num--;
4645                 }
4646
4647         // copy set in
4648         for( ; *str; *out++ = *str++ );
4649         // now jump over the old content
4650         for( ; *in ; in++ )
4651                 if( *in == '\'' || (*in == '\\' && !*++in) )
4652                         break;
4653
4654         strlcpy(out, in, outstr + sizeof(outstr) - out);
4655         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4656 }
4657
4658 /*
4659 ========================
4660 VM_altstr_ins
4661 insert after num
4662 string  altstr_ins(string altstr, float num, string set)
4663 ========================
4664 */
4665 void VM_altstr_ins(void)
4666 {
4667         int num;
4668         const char *set;
4669         const char *in;
4670         char *out;
4671         char outstr[VM_STRINGTEMP_LENGTH];
4672
4673         VM_SAFEPARMCOUNT(3, VM_altstr_ins);
4674
4675         in = PRVM_G_STRING( OFS_PARM0 );
4676         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4677         set = PRVM_G_STRING( OFS_PARM2 );
4678
4679         out = outstr;
4680         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
4681                 if( *in == '\\' ) {
4682                         if( !*++in ) {
4683                                 break;
4684                         }
4685                 } else if( *in == '\'' ) {
4686                         num--;
4687                 }
4688
4689         *out++ = '\'';
4690         for( ; *set ; *out++ = *set++ );
4691         *out++ = '\'';
4692
4693         strlcpy(out, in, outstr + sizeof(outstr) - out);
4694         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4695 }
4696
4697
4698 ////////////////////////////////////////
4699 // BufString functions
4700 ////////////////////////////////////////
4701 //[515]: string buffers support
4702
4703 static size_t stringbuffers_sortlength;
4704
4705 static void BufStr_Expand(prvm_stringbuffer_t *stringbuffer, int strindex)
4706 {
4707         if (stringbuffer->max_strings <= strindex)
4708         {
4709                 char **oldstrings = stringbuffer->strings;
4710                 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
4711                 while (stringbuffer->max_strings <= strindex)
4712                         stringbuffer->max_strings *= 2;
4713                 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
4714                 if (stringbuffer->num_strings > 0)
4715                         memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
4716                 if (oldstrings)
4717                         Mem_Free(oldstrings);
4718         }
4719 }
4720
4721 static void BufStr_Shrink(prvm_stringbuffer_t *stringbuffer)
4722 {
4723         // reduce num_strings if there are empty string slots at the end
4724         while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
4725                 stringbuffer->num_strings--;
4726
4727         // if empty, free the string pointer array
4728         if (stringbuffer->num_strings == 0)
4729         {
4730                 stringbuffer->max_strings = 0;
4731                 if (stringbuffer->strings)
4732                         Mem_Free(stringbuffer->strings);
4733                 stringbuffer->strings = NULL;
4734         }
4735 }
4736
4737 static int BufStr_SortStringsUP (const void *in1, const void *in2)
4738 {
4739         const char *a, *b;
4740         a = *((const char **) in1);
4741         b = *((const char **) in2);
4742         if(!a || !a[0]) return 1;
4743         if(!b || !b[0]) return -1;
4744         return strncmp(a, b, stringbuffers_sortlength);
4745 }
4746
4747 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
4748 {
4749         const char *a, *b;
4750         a = *((const char **) in1);
4751         b = *((const char **) in2);
4752         if(!a || !a[0]) return 1;
4753         if(!b || !b[0]) return -1;
4754         return strncmp(b, a, stringbuffers_sortlength);
4755 }
4756
4757 /*
4758 ========================
4759 VM_buf_create
4760 creates new buffer, and returns it's index, returns -1 if failed
4761 float buf_create(void) = #460;
4762 float newbuf(string format, float flags) = #460;
4763 ========================
4764 */
4765
4766 void VM_buf_create (void)
4767 {
4768         prvm_stringbuffer_t *stringbuffer;
4769         int i;
4770         
4771         VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
4772
4773         // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
4774         if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
4775         {
4776                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4777                 return;
4778         }
4779         stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
4780         for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
4781         stringbuffer->origin = PRVM_AllocationOrigin();
4782         // optional flags parm
4783         if (prog->argc >= 2)
4784                 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & 0xFF;
4785         PRVM_G_FLOAT(OFS_RETURN) = i;
4786 }
4787
4788
4789
4790 /*
4791 ========================
4792 VM_buf_del
4793 deletes buffer and all strings in it
4794 void buf_del(float bufhandle) = #461;
4795 ========================
4796 */
4797 void VM_buf_del (void)
4798 {
4799         prvm_stringbuffer_t *stringbuffer;
4800         VM_SAFEPARMCOUNT(1, VM_buf_del);
4801         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4802         if (stringbuffer)
4803         {
4804                 int i;
4805                 for (i = 0;i < stringbuffer->num_strings;i++)
4806                         if (stringbuffer->strings[i])
4807                                 Mem_Free(stringbuffer->strings[i]);
4808                 if (stringbuffer->strings)
4809                         Mem_Free(stringbuffer->strings);
4810                 if(stringbuffer->origin)
4811                         PRVM_Free((char *)stringbuffer->origin);
4812                 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
4813         }
4814         else
4815         {
4816                 VM_Warning("VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4817                 return;
4818         }
4819 }
4820
4821 /*
4822 ========================
4823 VM_buf_getsize
4824 how many strings are stored in buffer
4825 float buf_getsize(float bufhandle) = #462;
4826 ========================
4827 */
4828 void VM_buf_getsize (void)
4829 {
4830         prvm_stringbuffer_t *stringbuffer;
4831         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4832
4833         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4834         if(!stringbuffer)
4835         {
4836                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4837                 VM_Warning("VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4838                 return;
4839         }
4840         else
4841                 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4842 }
4843
4844 /*
4845 ========================
4846 VM_buf_copy
4847 copy all content from one buffer to another, make sure it exists
4848 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4849 ========================
4850 */
4851 void VM_buf_copy (void)
4852 {
4853         prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4854         int i;
4855         VM_SAFEPARMCOUNT(2, VM_buf_copy);
4856
4857         srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4858         if(!srcstringbuffer)
4859         {
4860                 VM_Warning("VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4861                 return;
4862         }
4863         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4864         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4865         {
4866                 VM_Warning("VM_buf_copy: source == destination (%i) in %s\n", i, PRVM_NAME);
4867                 return;
4868         }
4869         dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4870         if(!dststringbuffer)
4871         {
4872                 VM_Warning("VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
4873                 return;
4874         }
4875
4876         for (i = 0;i < dststringbuffer->num_strings;i++)
4877                 if (dststringbuffer->strings[i])
4878                         Mem_Free(dststringbuffer->strings[i]);
4879         if (dststringbuffer->strings)
4880                 Mem_Free(dststringbuffer->strings);
4881         *dststringbuffer = *srcstringbuffer;
4882         if (dststringbuffer->max_strings)
4883                 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4884
4885         for (i = 0;i < dststringbuffer->num_strings;i++)
4886         {
4887                 if (srcstringbuffer->strings[i])
4888                 {
4889                         size_t stringlen;
4890                         stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4891                         dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4892                         memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4893                 }
4894         }
4895 }
4896
4897 /*
4898 ========================
4899 VM_buf_sort
4900 sort buffer by beginnings of strings (cmplength defaults it's length)
4901 "backward == TRUE" means that sorting goes upside-down
4902 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4903 ========================
4904 */
4905 void VM_buf_sort (void)
4906 {
4907         prvm_stringbuffer_t *stringbuffer;
4908         VM_SAFEPARMCOUNT(3, VM_buf_sort);
4909
4910         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4911         if(!stringbuffer)
4912         {
4913                 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4914                 return;
4915         }
4916         if(stringbuffer->num_strings <= 0)
4917         {
4918                 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4919                 return;
4920         }
4921         stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4922         if(stringbuffers_sortlength <= 0)
4923                 stringbuffers_sortlength = 0x7FFFFFFF;
4924
4925         if(!PRVM_G_FLOAT(OFS_PARM2))
4926                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4927         else
4928                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4929
4930         BufStr_Shrink(stringbuffer);
4931 }
4932
4933 /*
4934 ========================
4935 VM_buf_implode
4936 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4937 string buf_implode(float bufhandle, string glue) = #465;
4938 ========================
4939 */
4940 void VM_buf_implode (void)
4941 {
4942         prvm_stringbuffer_t *stringbuffer;
4943         char                    k[VM_STRINGTEMP_LENGTH];
4944         const char              *sep;
4945         int                             i;
4946         size_t                  l;
4947         VM_SAFEPARMCOUNT(2, VM_buf_implode);
4948
4949         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4950         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4951         if(!stringbuffer)
4952         {
4953                 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4954                 return;
4955         }
4956         if(!stringbuffer->num_strings)
4957                 return;
4958         sep = PRVM_G_STRING(OFS_PARM1);
4959         k[0] = 0;
4960         for(l = i = 0;i < stringbuffer->num_strings;i++)
4961         {
4962                 if(stringbuffer->strings[i])
4963                 {
4964                         l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4965                         if (l >= sizeof(k) - 1)
4966                                 break;
4967                         strlcat(k, sep, sizeof(k));
4968                         strlcat(k, stringbuffer->strings[i], sizeof(k));
4969                 }
4970         }
4971         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(k);
4972 }
4973
4974 /*
4975 ========================
4976 VM_bufstr_get
4977 get a string from buffer, returns tempstring, dont str_unzone it!
4978 string bufstr_get(float bufhandle, float string_index) = #465;
4979 ========================
4980 */
4981 void VM_bufstr_get (void)
4982 {
4983         prvm_stringbuffer_t *stringbuffer;
4984         int                             strindex;
4985         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4986
4987         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4988         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4989         if(!stringbuffer)
4990         {
4991                 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4992                 return;
4993         }
4994         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4995         if (strindex < 0)
4996         {
4997                 // VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
4998                 return;
4999         }
5000         if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
5001                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(stringbuffer->strings[strindex]);
5002 }
5003
5004 /*
5005 ========================
5006 VM_bufstr_set
5007 copies a string into selected slot of buffer
5008 void bufstr_set(float bufhandle, float string_index, string str) = #466;
5009 ========================
5010 */
5011 void VM_bufstr_set (void)
5012 {
5013         size_t alloclen;
5014         int                             strindex;
5015         prvm_stringbuffer_t *stringbuffer;
5016         const char              *news;
5017
5018         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
5019
5020         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5021         if(!stringbuffer)
5022         {
5023                 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5024                 return;
5025         }
5026         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
5027         if(strindex < 0 || strindex >= 1000000) // huge number of strings
5028         {
5029                 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
5030                 return;
5031         }
5032
5033         BufStr_Expand(stringbuffer, strindex);
5034         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
5035
5036         if(stringbuffer->strings[strindex])
5037                 Mem_Free(stringbuffer->strings[strindex]);
5038         stringbuffer->strings[strindex] = NULL;
5039
5040         if(PRVM_G_INT(OFS_PARM2))
5041         {
5042                 // not the NULL string!
5043                 news = PRVM_G_STRING(OFS_PARM2);
5044                 alloclen = strlen(news) + 1;
5045                 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5046                 memcpy(stringbuffer->strings[strindex], news, alloclen);
5047         }
5048
5049         BufStr_Shrink(stringbuffer);
5050 }
5051
5052 /*
5053 ========================
5054 VM_bufstr_add
5055 adds string to buffer in first free slot and returns its index
5056 "order == TRUE" means that string will be added after last "full" slot
5057 float bufstr_add(float bufhandle, string str, float order) = #467;
5058 ========================
5059 */
5060 void VM_bufstr_add (void)
5061 {
5062         int                             order, strindex;
5063         prvm_stringbuffer_t *stringbuffer;
5064         const char              *string;
5065         size_t                  alloclen;
5066
5067         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
5068
5069         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5070         PRVM_G_FLOAT(OFS_RETURN) = -1;
5071         if(!stringbuffer)
5072         {
5073                 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5074                 return;
5075         }
5076         if(!PRVM_G_INT(OFS_PARM1)) // NULL string
5077         {
5078                 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);
5079                 return;
5080         }
5081         string = PRVM_G_STRING(OFS_PARM1);
5082         order = (int)PRVM_G_FLOAT(OFS_PARM2);
5083         if(order)
5084                 strindex = stringbuffer->num_strings;
5085         else
5086                 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
5087                         if (stringbuffer->strings[strindex] == NULL)
5088                                 break;
5089
5090         BufStr_Expand(stringbuffer, strindex);
5091
5092         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
5093         alloclen = strlen(string) + 1;
5094         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5095         memcpy(stringbuffer->strings[strindex], string, alloclen);
5096
5097         PRVM_G_FLOAT(OFS_RETURN) = strindex;
5098 }
5099
5100 /*
5101 ========================
5102 VM_bufstr_free
5103 delete string from buffer
5104 void bufstr_free(float bufhandle, float string_index) = #468;
5105 ========================
5106 */
5107 void VM_bufstr_free (void)
5108 {
5109         int                             i;
5110         prvm_stringbuffer_t     *stringbuffer;
5111         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
5112
5113         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5114         if(!stringbuffer)
5115         {
5116                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5117                 return;
5118         }
5119         i = (int)PRVM_G_FLOAT(OFS_PARM1);
5120         if(i < 0)
5121         {
5122                 VM_Warning("VM_bufstr_free: invalid string index %i used in %s\n", i, PRVM_NAME);
5123                 return;
5124         }
5125
5126         if (i < stringbuffer->num_strings)
5127         {
5128                 if(stringbuffer->strings[i])
5129                         Mem_Free(stringbuffer->strings[i]);
5130                 stringbuffer->strings[i] = NULL;
5131         }
5132
5133         BufStr_Shrink(stringbuffer);
5134 }
5135
5136
5137
5138
5139
5140
5141
5142 void VM_buf_cvarlist(void)
5143 {
5144         cvar_t *cvar;
5145         const char *partial, *antipartial;
5146         size_t len, antilen;
5147         size_t alloclen;
5148         qboolean ispattern, antiispattern;
5149         int n;
5150         prvm_stringbuffer_t     *stringbuffer;
5151         VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
5152
5153         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5154         if(!stringbuffer)
5155         {
5156                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5157                 return;
5158         }
5159
5160         partial = PRVM_G_STRING(OFS_PARM1);
5161         if(!partial)
5162                 len = 0;
5163         else
5164                 len = strlen(partial);
5165
5166         if(prog->argc == 3)
5167                 antipartial = PRVM_G_STRING(OFS_PARM2);
5168         else
5169                 antipartial = NULL;
5170         if(!antipartial)
5171                 antilen = 0;
5172         else
5173                 antilen = strlen(antipartial);
5174         
5175         for (n = 0;n < stringbuffer->num_strings;n++)
5176                 if (stringbuffer->strings[n])
5177                         Mem_Free(stringbuffer->strings[n]);
5178         if (stringbuffer->strings)
5179                 Mem_Free(stringbuffer->strings);
5180         stringbuffer->strings = NULL;
5181
5182         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
5183         antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
5184
5185         n = 0;
5186         for(cvar = cvar_vars; cvar; cvar = cvar->next)
5187         {
5188                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5189                         continue;
5190
5191                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5192                         continue;
5193
5194                 ++n;
5195         }
5196
5197         stringbuffer->max_strings = stringbuffer->num_strings = n;
5198         if (stringbuffer->max_strings)
5199                 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
5200         
5201         n = 0;
5202         for(cvar = cvar_vars; cvar; cvar = cvar->next)
5203         {
5204                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5205                         continue;
5206
5207                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5208                         continue;
5209
5210                 alloclen = strlen(cvar->name) + 1;
5211                 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5212                 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
5213
5214                 ++n;
5215         }
5216 }
5217
5218
5219
5220
5221 //=============
5222
5223 /*
5224 ==============
5225 VM_changeyaw
5226
5227 This was a major timewaster in progs, so it was converted to C
5228 ==============
5229 */
5230 void VM_changeyaw (void)
5231 {
5232         prvm_edict_t            *ent;
5233         float           ideal, current, move, speed;
5234
5235         // this is called (VERY HACKISHLY) by SV_MoveToGoal, so it can not use any
5236         // parameters because they are the parameters to SV_MoveToGoal, not this
5237         //VM_SAFEPARMCOUNT(0, VM_changeyaw);
5238
5239         ent = PRVM_PROG_TO_EDICT(PRVM_gameglobaledict(self));
5240         if (ent == prog->edicts)
5241         {
5242                 VM_Warning("changeyaw: can not modify world entity\n");
5243                 return;
5244         }
5245         if (ent->priv.server->free)
5246         {
5247                 VM_Warning("changeyaw: can not modify free entity\n");
5248                 return;
5249         }
5250         current = PRVM_gameedictvector(ent, angles)[1];
5251         current = ANGLEMOD(current);
5252         ideal = PRVM_gameedictfloat(ent, ideal_yaw);
5253         speed = PRVM_gameedictfloat(ent, yaw_speed);
5254
5255         if (current == ideal)
5256                 return;
5257         move = ideal - current;
5258         if (ideal > current)
5259         {
5260                 if (move >= 180)
5261                         move = move - 360;
5262         }
5263         else
5264         {
5265                 if (move <= -180)
5266                         move = move + 360;
5267         }
5268         if (move > 0)
5269         {
5270                 if (move > speed)
5271                         move = speed;
5272         }
5273         else
5274         {
5275                 if (move < -speed)
5276                         move = -speed;
5277         }
5278
5279         current += move;
5280         PRVM_gameedictvector(ent, angles)[1] = ANGLEMOD(current);
5281 }
5282
5283 /*
5284 ==============
5285 VM_changepitch
5286 ==============
5287 */
5288 void VM_changepitch (void)
5289 {
5290         prvm_edict_t            *ent;
5291         float           ideal, current, move, speed;
5292
5293         VM_SAFEPARMCOUNT(1, VM_changepitch);
5294
5295         ent = PRVM_G_EDICT(OFS_PARM0);
5296         if (ent == prog->edicts)
5297         {
5298                 VM_Warning("changepitch: can not modify world entity\n");
5299                 return;
5300         }
5301         if (ent->priv.server->free)
5302         {
5303                 VM_Warning("changepitch: can not modify free entity\n");
5304                 return;
5305         }
5306         current = PRVM_gameedictvector(ent, angles)[0];
5307         current = ANGLEMOD(current);
5308         ideal = PRVM_gameedictfloat(ent, idealpitch);
5309         speed = PRVM_gameedictfloat(ent, pitch_speed);
5310
5311         if (current == ideal)
5312                 return;
5313         move = ideal - current;
5314         if (ideal > current)
5315         {
5316                 if (move >= 180)
5317                         move = move - 360;
5318         }
5319         else
5320         {
5321                 if (move <= -180)
5322                         move = move + 360;
5323         }
5324         if (move > 0)
5325         {
5326                 if (move > speed)
5327                         move = speed;
5328         }
5329         else
5330         {
5331                 if (move < -speed)
5332                         move = -speed;
5333         }
5334
5335         current += move;
5336         PRVM_gameedictvector(ent, angles)[0] = ANGLEMOD(current);
5337 }
5338
5339
5340 void VM_uncolorstring (void)
5341 {
5342         char szNewString[VM_STRINGTEMP_LENGTH];
5343         const char *szString;
5344
5345         // Prepare Strings
5346         VM_SAFEPARMCOUNT(1, VM_uncolorstring);
5347         szString = PRVM_G_STRING(OFS_PARM0);
5348         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
5349         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
5350         
5351 }
5352
5353 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
5354 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
5355 void VM_strstrofs (void)
5356 {
5357         const char *instr, *match;
5358         int firstofs;
5359         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
5360         instr = PRVM_G_STRING(OFS_PARM0);
5361         match = PRVM_G_STRING(OFS_PARM1);
5362         firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
5363         firstofs = u8_bytelen(instr, firstofs);
5364
5365         if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
5366         {
5367                 PRVM_G_FLOAT(OFS_RETURN) = -1;
5368                 return;
5369         }
5370
5371         match = strstr(instr+firstofs, match);
5372         if (!match)
5373                 PRVM_G_FLOAT(OFS_RETURN) = -1;
5374         else
5375                 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
5376 }
5377
5378 //#222 string(string s, float index) str2chr (FTE_STRINGS)
5379 void VM_str2chr (void)
5380 {
5381         const char *s;
5382         Uchar ch;
5383         int index;
5384         VM_SAFEPARMCOUNT(2, VM_str2chr);
5385         s = PRVM_G_STRING(OFS_PARM0);
5386         index = u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
5387
5388         if((unsigned)index < strlen(s))
5389         {
5390                 if (utf8_enable.integer)
5391                         ch = u8_getchar_noendptr(s + index);
5392                 else
5393                         ch = (unsigned char)s[index];
5394                 PRVM_G_FLOAT(OFS_RETURN) = ch;
5395         }
5396         else
5397                 PRVM_G_FLOAT(OFS_RETURN) = 0;
5398 }
5399
5400 //#223 string(float c, ...) chr2str (FTE_STRINGS)
5401 void VM_chr2str (void)
5402 {
5403         /*
5404         char    t[9];
5405         int             i;
5406         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5407         for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
5408                 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
5409         t[i] = 0;
5410         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(t);
5411         */
5412         char t[9 * 4 + 1];
5413         int i;
5414         size_t len = 0;
5415         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5416         for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
5417                 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
5418         t[len] = 0;
5419         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(t);
5420 }
5421
5422 static int chrconv_number(int i, int base, int conv)
5423 {
5424         i -= base;
5425         switch (conv)
5426         {
5427         default:
5428         case 5:
5429         case 6:
5430         case 0:
5431                 break;
5432         case 1:
5433                 base = '0';
5434                 break;
5435         case 2:
5436                 base = '0'+128;
5437                 break;
5438         case 3:
5439                 base = '0'-30;
5440                 break;
5441         case 4:
5442                 base = '0'+128-30;
5443                 break;
5444         }
5445         return i + base;
5446 }
5447 static int chrconv_punct(int i, int base, int conv)
5448 {
5449         i -= base;
5450         switch (conv)
5451         {
5452         default:
5453         case 0:
5454                 break;
5455         case 1:
5456                 base = 0;
5457                 break;
5458         case 2:
5459                 base = 128;
5460                 break;
5461         }
5462         return i + base;
5463 }
5464
5465 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
5466 {
5467         //convert case and colour seperatly...
5468
5469         i -= baset + basec;
5470         switch (convt)
5471         {
5472         default:
5473         case 0:
5474                 break;
5475         case 1:
5476                 baset = 0;
5477                 break;
5478         case 2:
5479                 baset = 128;
5480                 break;
5481
5482         case 5:
5483         case 6:
5484                 baset = 128*((charnum&1) == (convt-5));
5485                 break;
5486         }
5487
5488         switch (convc)
5489         {
5490         default:
5491         case 0:
5492                 break;
5493         case 1:
5494                 basec = 'a';
5495                 break;
5496         case 2:
5497                 basec = 'A';
5498                 break;
5499         }
5500         return i + basec + baset;
5501 }
5502 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5503 //bulk convert a string. change case or colouring.
5504 void VM_strconv (void)
5505 {
5506         int ccase, redalpha, rednum, len, i;
5507         unsigned char resbuf[VM_STRINGTEMP_LENGTH];
5508         unsigned char *result = resbuf;
5509
5510         VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5511
5512         ccase = (int) PRVM_G_FLOAT(OFS_PARM0);  //0 same, 1 lower, 2 upper
5513         redalpha = (int) PRVM_G_FLOAT(OFS_PARM1);       //0 same, 1 white, 2 red,  5 alternate, 6 alternate-alternate
5514         rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5515         VM_VarString(3, (char *) resbuf, sizeof(resbuf));
5516         len = strlen((char *) resbuf);
5517
5518         for (i = 0; i < len; i++, result++)     //should this be done backwards?
5519         {
5520                 if (*result >= '0' && *result <= '9')   //normal numbers...
5521                         *result = chrconv_number(*result, '0', rednum);
5522                 else if (*result >= '0'+128 && *result <= '9'+128)
5523                         *result = chrconv_number(*result, '0'+128, rednum);
5524                 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5525                         *result = chrconv_number(*result, '0'+128-30, rednum);
5526                 else if (*result >= '0'-30 && *result <= '9'-30)
5527                         *result = chrconv_number(*result, '0'-30, rednum);
5528
5529                 else if (*result >= 'a' && *result <= 'z')      //normal numbers...
5530                         *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5531                 else if (*result >= 'A' && *result <= 'Z')      //normal numbers...
5532                         *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5533                 else if (*result >= 'a'+128 && *result <= 'z'+128)      //normal numbers...
5534                         *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5535                 else if (*result >= 'A'+128 && *result <= 'Z'+128)      //normal numbers...
5536                         *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5537
5538                 else if ((*result & 127) < 16 || !redalpha)     //special chars..
5539                         *result = *result;
5540                 else if (*result < 128)
5541                         *result = chrconv_punct(*result, 0, redalpha);
5542                 else
5543                         *result = chrconv_punct(*result, 128, redalpha);
5544         }
5545         *result = '\0';
5546
5547         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString((char *) resbuf);
5548 }
5549
5550 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5551 void VM_strpad (void)
5552 {
5553         char src[VM_STRINGTEMP_LENGTH];
5554         char destbuf[VM_STRINGTEMP_LENGTH];
5555         int pad;
5556         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5557         pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5558         VM_VarString(1, src, sizeof(src));
5559
5560         // note: < 0 = left padding, > 0 = right padding,
5561         // this is reverse logic of printf!
5562         dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5563
5564         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(destbuf);
5565 }
5566
5567 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5568 //uses qw style \key\value strings
5569 void VM_infoadd (void)
5570 {
5571         const char *info, *key;
5572         char value[VM_STRINGTEMP_LENGTH];
5573         char temp[VM_STRINGTEMP_LENGTH];
5574
5575         VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5576         info = PRVM_G_STRING(OFS_PARM0);
5577         key = PRVM_G_STRING(OFS_PARM1);
5578         VM_VarString(2, value, sizeof(value));
5579
5580         strlcpy(temp, info, VM_STRINGTEMP_LENGTH);
5581
5582         InfoString_SetValue(temp, VM_STRINGTEMP_LENGTH, key, value);
5583
5584         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(temp);
5585 }
5586
5587 // #227 string(string info, string key) infoget (FTE_STRINGS)
5588 //uses qw style \key\value strings
5589 void VM_infoget (void)
5590 {
5591         const char *info;
5592         const char *key;
5593         char value[VM_STRINGTEMP_LENGTH];
5594
5595         VM_SAFEPARMCOUNT(2, VM_infoget);
5596         info = PRVM_G_STRING(OFS_PARM0);
5597         key = PRVM_G_STRING(OFS_PARM1);
5598
5599         InfoString_GetValue(info, key, value, VM_STRINGTEMP_LENGTH);
5600
5601         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(value);
5602 }
5603
5604 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5605 // also float(string s1, string s2) strcmp (FRIK_FILE)
5606 void VM_strncmp (void)
5607 {
5608         const char *s1, *s2;
5609         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5610         s1 = PRVM_G_STRING(OFS_PARM0);
5611         s2 = PRVM_G_STRING(OFS_PARM1);
5612         if (prog->argc > 2)
5613         {
5614                 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5615         }
5616         else
5617         {
5618                 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5619         }
5620 }
5621
5622 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5623 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5624 void VM_strncasecmp (void)
5625 {
5626         const char *s1, *s2;
5627         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5628         s1 = PRVM_G_STRING(OFS_PARM0);
5629         s2 = PRVM_G_STRING(OFS_PARM1);
5630         if (prog->argc > 2)
5631         {
5632                 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5633         }
5634         else
5635         {
5636                 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5637         }
5638 }
5639
5640 // #494 float(float caseinsensitive, string s, ...) crc16
5641 void VM_crc16(void)
5642 {
5643         float insensitive;
5644         static char s[VM_STRINGTEMP_LENGTH];
5645         VM_SAFEPARMCOUNTRANGE(2, 8, VM_crc16);
5646         insensitive = PRVM_G_FLOAT(OFS_PARM0);
5647         VM_VarString(1, s, sizeof(s));
5648         PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, strlen(s)));
5649 }
5650
5651 // #639 float(string digest, string data, ...) digest_hex
5652 void VM_digest_hex(void)
5653 {
5654         const char *digest;
5655
5656         static char out[32];
5657         static char outhex[65];
5658         int outlen;
5659
5660         static char s[VM_STRINGTEMP_LENGTH];
5661         int len;
5662
5663         VM_SAFEPARMCOUNTRANGE(2, 8, VM_digest_hex);
5664         digest = PRVM_G_STRING(OFS_PARM0);
5665         if(!digest)
5666                 digest = "";
5667         VM_VarString(1, s, sizeof(s));
5668         len = strlen(s);
5669
5670         outlen = 0;
5671
5672         if(!strcmp(digest, "MD4"))
5673         {
5674                 outlen = 16;
5675                 mdfour((unsigned char *) out, (unsigned char *) s, len);
5676         }
5677         else if(!strcmp(digest, "SHA256") && Crypto_Available())
5678         {
5679                 outlen = 32;
5680                 sha256((unsigned char *) out, (unsigned char *) s, len);
5681         }
5682         // no warning needed on mismatch - we return string_null to QC
5683
5684         if(outlen)
5685         {
5686                 int i;
5687                 static const char *hexmap = "0123456789abcdef";
5688                 for(i = 0; i < outlen; ++i)
5689                 {
5690                         outhex[2*i]   = hexmap[(out[i] >> 4) & 15];
5691                         outhex[2*i+1] = hexmap[(out[i] >> 0) & 15];
5692                 }
5693                 outhex[2*i] = 0;
5694                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(outhex);
5695         }
5696         else
5697                 PRVM_G_INT(OFS_RETURN) = 0;
5698 }
5699
5700 void VM_wasfreed (void)
5701 {
5702         VM_SAFEPARMCOUNT(1, VM_wasfreed);
5703         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->priv.required->free;
5704 }
5705
5706 void VM_SetTraceGlobals(const trace_t *trace)
5707 {
5708         PRVM_gameglobalfloat(trace_allsolid) = trace->allsolid;
5709         PRVM_gameglobalfloat(trace_startsolid) = trace->startsolid;
5710         PRVM_gameglobalfloat(trace_fraction) = trace->fraction;
5711         PRVM_gameglobalfloat(trace_inwater) = trace->inwater;
5712         PRVM_gameglobalfloat(trace_inopen) = trace->inopen;
5713         VectorCopy(trace->endpos, PRVM_gameglobalvector(trace_endpos));
5714         VectorCopy(trace->plane.normal, PRVM_gameglobalvector(trace_plane_normal));
5715         PRVM_gameglobalfloat(trace_plane_dist) = trace->plane.dist;
5716         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5717         PRVM_gameglobalfloat(trace_dpstartcontents) = trace->startsupercontents;
5718         PRVM_gameglobalfloat(trace_dphitcontents) = trace->hitsupercontents;
5719         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = trace->hitq3surfaceflags;
5720         PRVM_gameglobalstring(trace_dphittexturename) = trace->hittexture ? PRVM_SetTempString(trace->hittexture->name) : 0;
5721 }
5722
5723 void VM_ClearTraceGlobals(void)
5724 {
5725         // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5726         PRVM_gameglobalfloat(trace_allsolid) = 0;
5727         PRVM_gameglobalfloat(trace_startsolid) = 0;
5728         PRVM_gameglobalfloat(trace_fraction) = 0;
5729         PRVM_gameglobalfloat(trace_inwater) = 0;
5730         PRVM_gameglobalfloat(trace_inopen) = 0;
5731         VectorClear(PRVM_gameglobalvector(trace_endpos));
5732         VectorClear(PRVM_gameglobalvector(trace_plane_normal));
5733         PRVM_gameglobalfloat(trace_plane_dist) = 0;
5734         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(prog->edicts);
5735         PRVM_gameglobalfloat(trace_dpstartcontents) = 0;
5736         PRVM_gameglobalfloat(trace_dphitcontents) = 0;
5737         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = 0;
5738         PRVM_gameglobalstring(trace_dphittexturename) = 0;
5739 }
5740
5741 //=============
5742
5743 void VM_Cmd_Init(void)
5744 {
5745         // only init the stuff for the current prog
5746         VM_Files_Init();
5747         VM_Search_Init();
5748         VM_Gecko_Init();
5749 //      VM_BufStr_Init();
5750 }
5751
5752 void VM_Cmd_Reset(void)
5753 {
5754         CL_PurgeOwner( MENUOWNER );
5755         VM_Search_Reset();
5756         VM_Files_CloseAll();
5757         VM_Gecko_Destroy();
5758 //      VM_BufStr_ShutDown();
5759 }
5760
5761 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5762 // does URI escaping on a string (replace evil stuff by %AB escapes)
5763 void VM_uri_escape (void)
5764 {
5765         char src[VM_STRINGTEMP_LENGTH];
5766         char dest[VM_STRINGTEMP_LENGTH];
5767         char *p, *q;
5768         static const char *hex = "0123456789ABCDEF";
5769
5770         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5771         VM_VarString(0, src, sizeof(src));
5772
5773         for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5774         {
5775                 if((*p >= 'A' && *p <= 'Z')
5776                         || (*p >= 'a' && *p <= 'z')
5777                         || (*p >= '0' && *p <= '9')
5778                         || (*p == '-')  || (*p == '_') || (*p == '.')
5779                         || (*p == '!')  || (*p == '~')
5780                         || (*p == '\'') || (*p == '(') || (*p == ')'))
5781                         *q++ = *p;
5782                 else
5783                 {
5784                         *q++ = '%';
5785                         *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5786                         *q++ = hex[ *(unsigned char *)p       & 0xF];
5787                 }
5788         }
5789         *q++ = 0;
5790
5791         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5792 }
5793
5794 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5795 // does URI unescaping on a string (get back the evil stuff)
5796 void VM_uri_unescape (void)
5797 {
5798         char src[VM_STRINGTEMP_LENGTH];
5799         char dest[VM_STRINGTEMP_LENGTH];
5800         char *p, *q;
5801         int hi, lo;
5802
5803         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5804         VM_VarString(0, src, sizeof(src));
5805
5806         for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5807         {
5808                 if(*p == '%')
5809                 {
5810                         if(p[1] >= '0' && p[1] <= '9')
5811                                 hi = p[1] - '0';
5812                         else if(p[1] >= 'a' && p[1] <= 'f')
5813                                 hi = p[1] - 'a' + 10;
5814                         else if(p[1] >= 'A' && p[1] <= 'F')
5815                                 hi = p[1] - 'A' + 10;
5816                         else
5817                                 goto nohex;
5818                         if(p[2] >= '0' && p[2] <= '9')
5819                                 lo = p[2] - '0';
5820                         else if(p[2] >= 'a' && p[2] <= 'f')
5821                                 lo = p[2] - 'a' + 10;
5822                         else if(p[2] >= 'A' && p[2] <= 'F')
5823                                 lo = p[2] - 'A' + 10;
5824                         else
5825                                 goto nohex;
5826                         if(hi != 0 || lo != 0) // don't unescape NUL bytes
5827                                 *q++ = (char) (hi * 0x10 + lo);
5828                         p += 3;
5829                         continue;
5830                 }
5831
5832 nohex:
5833                 // otherwise:
5834                 *q++ = *p++;
5835         }
5836         *q++ = 0;
5837
5838         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5839 }
5840
5841 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5842 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5843 void VM_whichpack (void)
5844 {
5845         const char *fn, *pack;
5846
5847         VM_SAFEPARMCOUNT(1, VM_whichpack);
5848         fn = PRVM_G_STRING(OFS_PARM0);
5849         pack = FS_WhichPack(fn);
5850
5851         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(pack ? pack : "");
5852 }
5853
5854 typedef struct
5855 {
5856         int prognr;
5857         double starttime;
5858         float id;
5859         char buffer[MAX_INPUTLINE];
5860         unsigned char *postdata; // free when uri_to_prog_t is freed
5861         size_t postlen;
5862         char *sigdata; // free when uri_to_prog_t is freed
5863         size_t siglen;
5864 }
5865 uri_to_prog_t;
5866
5867 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5868 {
5869         uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5870
5871         if(!PRVM_ProgLoaded(handle->prognr))
5872         {
5873                 // curl reply came too late... so just drop it
5874                 if(handle->postdata)
5875                         Z_Free(handle->postdata);
5876                 if(handle->sigdata)
5877                         Z_Free(handle->sigdata);
5878                 Z_Free(handle);
5879                 return;
5880         }
5881                 
5882         PRVM_SetProg(handle->prognr);
5883         PRVM_Begin;
5884                 if((prog->starttime == handle->starttime) && (PRVM_allfunction(URI_Get_Callback)))
5885                 {
5886                         if(length_received >= sizeof(handle->buffer))
5887                                 length_received = sizeof(handle->buffer) - 1;
5888                         handle->buffer[length_received] = 0;
5889                 
5890                         PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5891                         PRVM_G_FLOAT(OFS_PARM1) = status;
5892                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(handle->buffer);
5893                         PRVM_ExecuteProgram(PRVM_allfunction(URI_Get_Callback), "QC function URI_Get_Callback is missing");
5894                 }
5895         PRVM_End;
5896         
5897         if(handle->postdata)
5898                 Z_Free(handle->postdata);
5899         if(handle->sigdata)
5900                 Z_Free(handle->sigdata);
5901         Z_Free(handle);
5902 }
5903
5904 // 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
5905 // 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
5906 void VM_uri_get (void)
5907 {
5908         const char *url;
5909         float id;
5910         qboolean ret;
5911         uri_to_prog_t *handle;
5912         const char *posttype = NULL;
5913         const char *postseparator = NULL;
5914         int poststringbuffer = -1;
5915         int postkeyid = -1;
5916         const char *query_string = NULL;
5917         size_t lq;
5918
5919         if(!PRVM_allfunction(URI_Get_Callback))
5920                 PRVM_ERROR("uri_get called by %s without URI_Get_Callback defined", PRVM_NAME);
5921
5922         VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5923
5924         url = PRVM_G_STRING(OFS_PARM0);
5925         id = PRVM_G_FLOAT(OFS_PARM1);
5926         if(prog->argc >= 3)
5927                 posttype = PRVM_G_STRING(OFS_PARM2);
5928         if(prog->argc >= 4)
5929                 postseparator = PRVM_G_STRING(OFS_PARM3);
5930         if(prog->argc >= 5)
5931                 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5932         if(prog->argc >= 6)
5933                 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5934         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!
5935
5936         query_string = strchr(url, '?');
5937         if(query_string)
5938                 ++query_string;
5939         lq = query_string ? strlen(query_string) : 0;
5940
5941         handle->prognr = PRVM_GetProgNr();
5942         handle->starttime = prog->starttime;
5943         handle->id = id;
5944         if(postseparator && posttype && *posttype)
5945         {
5946                 size_t l = strlen(postseparator);
5947                 if(poststringbuffer >= 0)
5948                 {
5949                         size_t ltotal;
5950                         int i;
5951                         // "implode"
5952                         prvm_stringbuffer_t *stringbuffer;
5953                         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5954                         if(!stringbuffer)
5955                         {
5956                                 VM_Warning("uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5957                                 return;
5958                         }
5959                         ltotal = 0;
5960                         for(i = 0;i < stringbuffer->num_strings;i++)
5961                         {
5962                                 if(i > 0)
5963                                         ltotal += l;
5964                                 if(stringbuffer->strings[i])
5965                                         ltotal += strlen(stringbuffer->strings[i]);
5966                         }
5967                         handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5968                         handle->postlen = ltotal;
5969                         ltotal = 0;
5970                         for(i = 0;i < stringbuffer->num_strings;i++)
5971                         {
5972                                 if(i > 0)
5973                                 {
5974                                         memcpy(handle->postdata + ltotal, postseparator, l);
5975                                         ltotal += l;
5976                                 }
5977                                 if(stringbuffer->strings[i])
5978                                 {
5979                                         memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5980                                         ltotal += strlen(stringbuffer->strings[i]);
5981                                 }
5982                         }
5983                         if(ltotal != handle->postlen)
5984                                 PRVM_ERROR ("%s: string buffer content size mismatch, possible overrun", PRVM_NAME);
5985                 }
5986                 else
5987                 {
5988                         handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
5989                         handle->postlen = l;
5990                         memcpy(handle->postdata, postseparator, l);
5991                 }
5992                 handle->postdata[handle->postlen] = 0;
5993                 if(query_string)
5994                         memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
5995                 if(postkeyid >= 0)
5996                 {
5997                         // POST: we sign postdata \0 query string
5998                         size_t ll;
5999                         handle->sigdata = (char *)Z_Malloc(8192);
6000                         strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
6001                         l = strlen(handle->sigdata);
6002                         handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
6003                         if(!handle->siglen)
6004                         {
6005                                 Z_Free(handle->sigdata);
6006                                 handle->sigdata = NULL;
6007                                 goto out1;
6008                         }
6009                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
6010                         if(!ll)
6011                         {
6012                                 Z_Free(handle->sigdata);
6013                                 handle->sigdata = NULL;
6014                                 goto out1;
6015                         }
6016                         handle->siglen = l + ll;
6017                         handle->sigdata[handle->siglen] = 0;
6018                 }
6019 out1:
6020                 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, posttype, handle->postdata, handle->postlen, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
6021         }
6022         else
6023         {
6024                 if(postkeyid >= 0 && query_string)
6025                 {
6026                         // GET: we sign JUST the query string
6027                         size_t l, ll;
6028                         handle->sigdata = (char *)Z_Malloc(8192);
6029                         strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
6030                         l = strlen(handle->sigdata);
6031                         handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
6032                         if(!handle->siglen)
6033                         {
6034                                 Z_Free(handle->sigdata);
6035                                 handle->sigdata = NULL;
6036                                 goto out2;
6037                         }
6038                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
6039                         if(!ll)
6040                         {
6041                                 Z_Free(handle->sigdata);
6042                                 handle->sigdata = NULL;
6043                                 goto out2;
6044                         }
6045                         handle->siglen = l + ll;
6046                         handle->sigdata[handle->siglen] = 0;
6047                 }
6048 out2:
6049                 handle->postdata = NULL;
6050                 handle->postlen = 0;
6051                 ret = Curl_Begin_ToMemory(url, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
6052         }
6053         if(ret)
6054         {
6055                 PRVM_G_INT(OFS_RETURN) = 1;
6056         }
6057         else
6058         {
6059                 if(handle->postdata)
6060                         Z_Free(handle->postdata);
6061                 if(handle->sigdata)
6062                         Z_Free(handle->sigdata);
6063                 Z_Free(handle);
6064                 PRVM_G_INT(OFS_RETURN) = 0;
6065         }
6066 }
6067
6068 void VM_netaddress_resolve (void)
6069 {
6070         const char *ip;
6071         char normalized[128];
6072         int port;
6073         lhnetaddress_t addr;
6074
6075         VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
6076
6077         ip = PRVM_G_STRING(OFS_PARM0);
6078         port = 0;
6079         if(prog->argc > 1)
6080                 port = (int) PRVM_G_FLOAT(OFS_PARM1);
6081
6082         if(LHNETADDRESS_FromString(&addr, ip, port) && LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1))
6083                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(normalized);
6084         else
6085                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
6086 }
6087
6088 //string(void) getextresponse = #624; // returns the next extResponse packet that was sent to this client
6089 void VM_CL_getextresponse (void)
6090 {
6091         VM_SAFEPARMCOUNT(0,VM_argv);
6092
6093         if (cl_net_extresponse_count <= 0)
6094                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6095         else
6096         {
6097                 int first;
6098                 --cl_net_extresponse_count;
6099                 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
6100                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(cl_net_extresponse[first]);
6101         }
6102 }
6103
6104 void VM_SV_getextresponse (void)
6105 {
6106         VM_SAFEPARMCOUNT(0,VM_argv);
6107
6108         if (sv_net_extresponse_count <= 0)
6109                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6110         else
6111         {
6112                 int first;
6113                 --sv_net_extresponse_count;
6114                 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
6115                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(sv_net_extresponse[first]);
6116         }
6117 }
6118
6119 /*
6120 =========
6121 Common functions between menu.dat and clsprogs
6122 =========
6123 */
6124
6125 //#349 float() isdemo 
6126 void VM_CL_isdemo (void)
6127 {
6128         VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
6129         PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
6130 }
6131
6132 //#355 float() videoplaying 
6133 void VM_CL_videoplaying (void)
6134 {
6135         VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
6136         PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
6137 }
6138
6139 /*
6140 =========
6141 VM_M_callfunction
6142
6143         callfunction(...,string function_name)
6144 Extension: pass
6145 =========
6146 */
6147 mfunction_t *PRVM_ED_FindFunction (const char *name);
6148 void VM_callfunction(void)
6149 {
6150         mfunction_t *func;
6151         const char *s;
6152
6153         VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
6154
6155         s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
6156
6157         VM_CheckEmptyString(s);
6158
6159         func = PRVM_ED_FindFunction(s);
6160
6161         if(!func)
6162                 PRVM_ERROR("VM_callfunciton: function %s not found !", s);
6163         else if (func->first_statement < 0)
6164         {
6165                 // negative statements are built in functions
6166                 int builtinnumber = -func->first_statement;
6167                 prog->xfunction->builtinsprofile++;
6168                 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
6169                         prog->builtins[builtinnumber]();
6170                 else
6171                         PRVM_ERROR("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, PRVM_NAME);
6172         }
6173         else if(func - prog->functions > 0)
6174         {
6175                 prog->argc--;
6176                 PRVM_ExecuteProgram(func - prog->functions,"");
6177                 prog->argc++;
6178         }
6179 }
6180
6181 /*
6182 =========
6183 VM_isfunction
6184
6185 float   isfunction(string function_name)
6186 =========
6187 */
6188 mfunction_t *PRVM_ED_FindFunction (const char *name);
6189 void VM_isfunction(void)
6190 {
6191         mfunction_t *func;
6192         const char *s;
6193
6194         VM_SAFEPARMCOUNT(1, VM_isfunction);
6195
6196         s = PRVM_G_STRING(OFS_PARM0);
6197
6198         VM_CheckEmptyString(s);
6199
6200         func = PRVM_ED_FindFunction(s);
6201
6202         if(!func)
6203                 PRVM_G_FLOAT(OFS_RETURN) = false;
6204         else
6205                 PRVM_G_FLOAT(OFS_RETURN) = true;
6206 }
6207
6208 /*
6209 =========
6210 VM_sprintf
6211
6212 string sprintf(string format, ...)
6213 =========
6214 */
6215
6216 void VM_sprintf(void)
6217 {
6218         const char *s, *s0;
6219         char outbuf[MAX_INPUTLINE];
6220         char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
6221         int argpos = 1;
6222         int width, precision, thisarg, flags;
6223         char formatbuf[16];
6224         char *f;
6225         int isfloat;
6226         static int dummyivec[3] = {0, 0, 0};
6227         static float dummyvec[3] = {0, 0, 0};
6228
6229 #define PRINTF_ALTERNATE 1
6230 #define PRINTF_ZEROPAD 2
6231 #define PRINTF_LEFT 4
6232 #define PRINTF_SPACEPOSITIVE 8
6233 #define PRINTF_SIGNPOSITIVE 16
6234
6235         formatbuf[0] = '%';
6236
6237         s = PRVM_G_STRING(OFS_PARM0);
6238
6239 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
6240 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
6241 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
6242 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((int*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
6243 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
6244
6245         for(;;)
6246         {
6247                 s0 = s;
6248                 switch(*s)
6249                 {
6250                         case 0:
6251                                 goto finished;
6252                         case '%':
6253                                 ++s;
6254
6255                                 if(*s == '%')
6256                                         goto verbatim;
6257
6258                                 // complete directive format:
6259                                 // %3$*1$.*2$ld
6260                                 
6261                                 width = -1;
6262                                 precision = -1;
6263                                 thisarg = -1;
6264                                 flags = 0;
6265                                 isfloat = -1;
6266
6267                                 // is number following?
6268                                 if(*s >= '0' && *s <= '9')
6269                                 {
6270                                         width = strtol(s, &err, 10);
6271                                         if(!err)
6272                                         {
6273                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6274                                                 goto finished;
6275                                         }
6276                                         if(*err == '$')
6277                                         {
6278                                                 thisarg = width;
6279                                                 width = -1;
6280                                                 s = err + 1;
6281                                         }
6282                                         else
6283                                         {
6284                                                 if(*s == '0')
6285                                                 {
6286                                                         flags |= PRINTF_ZEROPAD;
6287                                                         if(width == 0)
6288                                                                 width = -1; // it was just a flag
6289                                                 }
6290                                                 s = err;
6291                                         }
6292                                 }
6293
6294                                 if(width < 0)
6295                                 {
6296                                         for(;;)
6297                                         {
6298                                                 switch(*s)
6299                                                 {
6300                                                         case '#': flags |= PRINTF_ALTERNATE; break;
6301                                                         case '0': flags |= PRINTF_ZEROPAD; break;
6302                                                         case '-': flags |= PRINTF_LEFT; break;
6303                                                         case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
6304                                                         case '+': flags |= PRINTF_SIGNPOSITIVE; break;
6305                                                         default:
6306                                                                 goto noflags;
6307                                                 }
6308                                                 ++s;
6309                                         }
6310 noflags:
6311                                         if(*s == '*')
6312                                         {
6313                                                 ++s;
6314                                                 if(*s >= '0' && *s <= '9')
6315                                                 {
6316                                                         width = strtol(s, &err, 10);
6317                                                         if(!err || *err != '$')
6318                                                         {
6319                                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6320                                                                 goto finished;
6321                                                         }
6322                                                         s = err + 1;
6323                                                 }
6324                                                 else
6325                                                         width = argpos++;
6326                                                 width = GETARG_FLOAT(width);
6327                                                 if(width < 0)
6328                                                 {
6329                                                         flags |= PRINTF_LEFT;
6330                                                         width = -width;
6331                                                 }
6332                                         }
6333                                         else if(*s >= '0' && *s <= '9')
6334                                         {
6335                                                 width = strtol(s, &err, 10);
6336                                                 if(!err)
6337                                                 {
6338                                                         VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6339                                                         goto finished;
6340                                                 }
6341                                                 s = err;
6342                                                 if(width < 0)
6343                                                 {
6344                                                         flags |= PRINTF_LEFT;
6345                                                         width = -width;
6346                                                 }
6347                                         }
6348                                         // otherwise width stays -1
6349                                 }
6350
6351                                 if(*s == '.')
6352                                 {
6353                                         ++s;
6354                                         if(*s == '*')
6355                                         {
6356                                                 ++s;
6357                                                 if(*s >= '0' && *s <= '9')
6358                                                 {
6359                                                         precision = strtol(s, &err, 10);
6360                                                         if(!err || *err != '$')
6361                                                         {
6362                                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6363                                                                 goto finished;
6364                                                         }
6365                                                         s = err + 1;
6366                                                 }
6367                                                 else
6368                                                         precision = argpos++;
6369                                                 precision = GETARG_FLOAT(precision);
6370                                         }
6371                                         else if(*s >= '0' && *s <= '9')
6372                                         {
6373                                                 precision = strtol(s, &err, 10);
6374                                                 if(!err)
6375                                                 {
6376                                                         VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6377                                                         goto finished;
6378                                                 }
6379                                                 s = err;
6380                                         }
6381                                         else
6382                                         {
6383                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6384                                                 goto finished;
6385                                         }
6386                                 }
6387
6388                                 for(;;)
6389                                 {
6390                                         switch(*s)
6391                                         {
6392                                                 case 'h': isfloat = 1; break;
6393                                                 case 'l': isfloat = 0; break;
6394                                                 case 'L': isfloat = 0; break;
6395                                                 case 'j': break;
6396                                                 case 'z': break;
6397                                                 case 't': break;
6398                                                 default:
6399                                                         goto nolength;
6400                                         }
6401                                         ++s;
6402                                 }
6403 nolength:
6404
6405                                 // now s points to the final directive char and is no longer changed
6406                                 if(isfloat < 0)
6407                                 {
6408                                         if(*s == 'i')
6409                                                 isfloat = 0;
6410                                         else
6411                                                 isfloat = 1;
6412                                 }
6413
6414                                 if(thisarg < 0)
6415                                         thisarg = argpos++;
6416
6417                                 if(o < end - 1)
6418                                 {
6419                                         f = &formatbuf[1];
6420                                         if(*s != 's' && *s != 'c')
6421                                                 if(flags & PRINTF_ALTERNATE) *f++ = '#';
6422                                         if(flags & PRINTF_ZEROPAD) *f++ = '0';
6423                                         if(flags & PRINTF_LEFT) *f++ = '-';
6424                                         if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
6425                                         if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
6426                                         *f++ = '*';
6427                                         if(precision >= 0)
6428                                         {
6429                                                 *f++ = '.';
6430                                                 *f++ = '*';
6431                                         }
6432                                         *f++ = *s;
6433                                         *f++ = 0;
6434
6435                                         if(width < 0) // not set
6436                                                 width = 0;
6437
6438                                         switch(*s)
6439                                         {
6440                                                 case 'd': case 'i':
6441                                                         if(precision < 0) // not set
6442                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6443                                                         else
6444                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6445                                                         break;
6446                                                 case 'o': case 'u': case 'x': case 'X':
6447                                                         if(precision < 0) // not set
6448                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6449                                                         else
6450                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6451                                                         break;
6452                                                 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6453                                                         if(precision < 0) // not set
6454                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6455                                                         else
6456                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6457                                                         break;
6458                                                 case 'v': case 'V':
6459                                                         f[-2] += 'g' - 'v';
6460                                                         if(precision < 0) // not set
6461                                                                 o += dpsnprintf(o, end - o, va("%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6462                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6463                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6464                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6465                                                                 );
6466                                                         else
6467                                                                 o += dpsnprintf(o, end - o, va("%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6468                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6469                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6470                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6471                                                                 );
6472                                                         break;
6473                                                 case 'c':
6474                                                         if(flags & PRINTF_ALTERNATE)
6475                                                         {
6476                                                                 if(precision < 0) // not set
6477                                                                         o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6478                                                                 else
6479                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6480                                                         }
6481                                                         else
6482                                                         {
6483                                                                 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6484                                                                 const char *buf = u8_encodech(c, NULL);
6485                                                                 if(!buf)
6486                                                                         buf = "";
6487                                                                 if(precision < 0) // not set
6488                                                                         precision = end - o - 1;
6489                                                                 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6490                                                         }
6491                                                         break;
6492                                                 case 's':
6493                                                         if(flags & PRINTF_ALTERNATE)
6494                                                         {
6495                                                                 if(precision < 0) // not set
6496                                                                         o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6497                                                                 else
6498                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6499                                                         }
6500                                                         else
6501                                                         {
6502                                                                 if(precision < 0) // not set
6503                                                                         precision = end - o - 1;
6504                                                                 o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6505                                                         }
6506                                                         break;
6507                                                 default:
6508                                                         VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6509                                                         goto finished;
6510                                         }
6511                                 }
6512                                 ++s;
6513                                 break;
6514                         default:
6515 verbatim:
6516                                 if(o < end - 1)
6517                                         *o++ = *s++;
6518                                 break;
6519                 }
6520         }
6521 finished:
6522         *o = 0;
6523         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(outbuf);
6524 }
6525
6526
6527 // surface querying
6528
6529 static dp_model_t *getmodel(prvm_edict_t *ed)
6530 {
6531         switch(PRVM_GetProgNr())
6532         {
6533                 case PRVM_SERVERPROG:
6534                         return SV_GetModelFromEdict(ed);
6535                 case PRVM_CLIENTPROG:
6536                         return CL_GetModelFromEdict(ed);
6537                 default:
6538                         return NULL;
6539         }
6540 }
6541
6542 typedef struct
6543 {
6544         unsigned int progid;
6545         dp_model_t *model;
6546         frameblend_t frameblend[MAX_FRAMEBLENDS];
6547         skeleton_t *skeleton_p;
6548         skeleton_t skeleton;
6549         float *data_vertex3f;
6550         float *data_svector3f;
6551         float *data_tvector3f;
6552         float *data_normal3f;
6553         int max_vertices;
6554         float *buf_vertex3f;
6555         float *buf_svector3f;
6556         float *buf_tvector3f;
6557         float *buf_normal3f;
6558 }
6559 animatemodel_cache_t;
6560 static animatemodel_cache_t animatemodel_cache;
6561
6562 void animatemodel(dp_model_t *model, prvm_edict_t *ed)
6563 {
6564         skeleton_t *skeleton;
6565         int skeletonindex = -1;
6566         qboolean need = false;
6567         if(!(model->surfmesh.isanimated && model->AnimateVertices))
6568         {
6569                 animatemodel_cache.data_vertex3f = model->surfmesh.data_vertex3f;
6570                 animatemodel_cache.data_svector3f = model->surfmesh.data_svector3f;
6571                 animatemodel_cache.data_tvector3f = model->surfmesh.data_tvector3f;
6572                 animatemodel_cache.data_normal3f = model->surfmesh.data_normal3f;
6573                 return;
6574         }
6575         if(animatemodel_cache.progid != prog->id)
6576                 memset(&animatemodel_cache, 0, sizeof(animatemodel_cache));
6577         need |= (animatemodel_cache.model != model);
6578         VM_GenerateFrameGroupBlend(ed->priv.server->framegroupblend, ed);
6579         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model);
6580         need |= (memcmp(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6581         skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
6582         if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6583                 skeleton = NULL;
6584         need |= (animatemodel_cache.skeleton_p != skeleton);
6585         if(skeleton)
6586                 need |= (memcmp(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6587         if(!need)
6588                 return;
6589         if(model->surfmesh.num_vertices > animatemodel_cache.max_vertices)
6590         {
6591                 animatemodel_cache.max_vertices = model->surfmesh.num_vertices * 2;
6592                 if(animatemodel_cache.buf_vertex3f) Mem_Free(animatemodel_cache.buf_vertex3f);
6593                 if(animatemodel_cache.buf_svector3f) Mem_Free(animatemodel_cache.buf_svector3f);
6594                 if(animatemodel_cache.buf_tvector3f) Mem_Free(animatemodel_cache.buf_tvector3f);
6595                 if(animatemodel_cache.buf_normal3f) Mem_Free(animatemodel_cache.buf_normal3f);
6596                 animatemodel_cache.buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6597                 animatemodel_cache.buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6598                 animatemodel_cache.buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6599                 animatemodel_cache.buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6600         }
6601         animatemodel_cache.data_vertex3f = animatemodel_cache.buf_vertex3f;
6602         animatemodel_cache.data_svector3f = animatemodel_cache.buf_svector3f;
6603         animatemodel_cache.data_tvector3f = animatemodel_cache.buf_tvector3f;
6604         animatemodel_cache.data_normal3f = animatemodel_cache.buf_normal3f;
6605         VM_UpdateEdictSkeleton(ed, model, ed->priv.server->frameblend);
6606         model->AnimateVertices(model, ed->priv.server->frameblend, &ed->priv.server->skeleton, animatemodel_cache.data_vertex3f, animatemodel_cache.data_normal3f, animatemodel_cache.data_svector3f, animatemodel_cache.data_tvector3f);
6607         animatemodel_cache.progid = prog->id;
6608         animatemodel_cache.model = model;
6609         memcpy(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6610         animatemodel_cache.skeleton_p = skeleton;
6611         if(skeleton)
6612                 memcpy(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6613 }
6614
6615 static void getmatrix(prvm_edict_t *ed, matrix4x4_t *out)
6616 {
6617         switch(PRVM_GetProgNr())
6618         {
6619                 case PRVM_SERVERPROG:
6620                         SV_GetEntityMatrix(ed, out, false);
6621                         break;
6622                 case PRVM_CLIENTPROG:
6623                         CL_GetEntityMatrix(ed, out, false);
6624                         break;
6625                 default:
6626                         *out = identitymatrix;
6627                         break;
6628         }
6629 }
6630
6631 static void applytransform_forward(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6632 {
6633         matrix4x4_t m;
6634         getmatrix(ed, &m);
6635         Matrix4x4_Transform(&m, in, out);
6636 }
6637
6638 static void applytransform_forward_direction(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6639 {
6640         matrix4x4_t m;
6641         getmatrix(ed, &m);
6642         Matrix4x4_Transform3x3(&m, in, out);
6643 }
6644
6645 static void applytransform_inverted(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6646 {
6647         matrix4x4_t m, n;
6648         getmatrix(ed, &m);
6649         Matrix4x4_Invert_Full(&n, &m);
6650         Matrix4x4_Transform3x3(&n, in, out);
6651 }
6652
6653 static void applytransform_forward_normal(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6654 {
6655         matrix4x4_t m;
6656         float p[4];
6657         getmatrix(ed, &m);
6658         Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6659         VectorCopy(p, out);
6660 }
6661
6662 static void clippointtosurface(prvm_edict_t *ed, dp_model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6663 {
6664         int i, j, k;
6665         float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6666         const int *e;
6667         animatemodel(model, ed);
6668         bestdist = 1000000000;
6669         VectorCopy(p, out);
6670         for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6671         {
6672                 // clip original point to each triangle of the surface and find the
6673                 // triangle that is closest
6674                 v[0] = animatemodel_cache.data_vertex3f + e[0] * 3;
6675                 v[1] = animatemodel_cache.data_vertex3f + e[1] * 3;
6676                 v[2] = animatemodel_cache.data_vertex3f + e[2] * 3;
6677                 TriangleNormal(v[0], v[1], v[2], facenormal);
6678                 VectorNormalize(facenormal);
6679                 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6680                 VectorMA(p, offsetdist, facenormal, temp);
6681                 for (j = 0, k = 2;j < 3;k = j, j++)
6682                 {
6683                         VectorSubtract(v[k], v[j], edgenormal);
6684                         CrossProduct(edgenormal, facenormal, sidenormal);
6685                         VectorNormalize(sidenormal);
6686                         offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6687                         if (offsetdist < 0)
6688                                 VectorMA(temp, offsetdist, sidenormal, temp);
6689                 }
6690                 dist = VectorDistance2(temp, p);
6691                 if (bestdist > dist)
6692                 {
6693                         bestdist = dist;
6694                         VectorCopy(temp, out);
6695                 }
6696         }
6697 }
6698
6699 static msurface_t *getsurface(dp_model_t *model, int surfacenum)
6700 {
6701         if (surfacenum < 0 || surfacenum >= model->nummodelsurfaces)
6702                 return NULL;
6703         return model->data_surfaces + surfacenum + model->firstmodelsurface;
6704 }
6705
6706
6707 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6708 void VM_getsurfacenumpoints(void)
6709 {
6710         dp_model_t *model;
6711         msurface_t *surface;
6712         VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6713         // return 0 if no such surface
6714         if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6715         {
6716                 PRVM_G_FLOAT(OFS_RETURN) = 0;
6717                 return;
6718         }
6719
6720         // note: this (incorrectly) assumes it is a simple polygon
6721         PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6722 }
6723 //PF_getsurfacepoint,     // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6724 void VM_getsurfacepoint(void)
6725 {
6726         prvm_edict_t *ed;
6727         dp_model_t *model;
6728         msurface_t *surface;
6729         int pointnum;
6730         VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6731         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6732         ed = PRVM_G_EDICT(OFS_PARM0);
6733         if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6734                 return;
6735         // note: this (incorrectly) assumes it is a simple polygon
6736         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6737         if (pointnum < 0 || pointnum >= surface->num_vertices)
6738                 return;
6739         animatemodel(model, ed);
6740         applytransform_forward(&(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6741 }
6742 //PF_getsurfacepointattribute,     // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6743 // float SPA_POSITION = 0;
6744 // float SPA_S_AXIS = 1;
6745 // float SPA_T_AXIS = 2;
6746 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6747 // float SPA_TEXCOORDS0 = 4;
6748 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6749 // float SPA_LIGHTMAP0_COLOR = 6;
6750 void VM_getsurfacepointattribute(void)
6751 {
6752         prvm_edict_t *ed;
6753         dp_model_t *model;
6754         msurface_t *surface;
6755         int pointnum;
6756         int attributetype;
6757
6758         VM_SAFEPARMCOUNT(4, VM_getsurfacepoint);
6759         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6760         ed = PRVM_G_EDICT(OFS_PARM0);
6761         if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6762                 return;
6763         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6764         if (pointnum < 0 || pointnum >= surface->num_vertices)
6765                 return;
6766         attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6767
6768         animatemodel(model, ed);
6769
6770         switch( attributetype ) {
6771                 // float SPA_POSITION = 0;
6772                 case 0:
6773                         applytransform_forward(&(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6774                         break;
6775                 // float SPA_S_AXIS = 1;
6776                 case 1:
6777                         applytransform_forward_direction(&(animatemodel_cache.data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6778                         break;
6779                 // float SPA_T_AXIS = 2;
6780                 case 2:
6781                         applytransform_forward_direction(&(animatemodel_cache.data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6782                         break;
6783                 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6784                 case 3:
6785                         applytransform_forward_direction(&(animatemodel_cache.data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6786                         break;
6787                 // float SPA_TEXCOORDS0 = 4;
6788                 case 4: {
6789                         float *ret = PRVM_G_VECTOR(OFS_RETURN);
6790                         float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6791                         ret[0] = texcoord[0];
6792                         ret[1] = texcoord[1];
6793                         ret[2] = 0.0f;
6794                         break;
6795                 }
6796                 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6797                 case 5: {
6798                         float *ret = PRVM_G_VECTOR(OFS_RETURN);
6799                         float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6800                         ret[0] = texcoord[0];
6801                         ret[1] = texcoord[1];
6802                         ret[2] = 0.0f;
6803                         break;
6804                 }
6805                 // float SPA_LIGHTMAP0_COLOR = 6;
6806                 case 6:
6807                         // ignore alpha for now..
6808                         VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6809                         break;
6810                 default:
6811                         VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6812                         break;
6813         }
6814 }
6815 //PF_getsurfacenormal,    // #436 vector(entity e, float s) getsurfacenormal = #436;
6816 void VM_getsurfacenormal(void)
6817 {
6818         dp_model_t *model;
6819         msurface_t *surface;
6820         vec3_t normal;
6821         VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6822         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6823         if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6824                 return;
6825         // note: this only returns the first triangle, so it doesn't work very
6826         // well for curved surfaces or arbitrary meshes
6827         animatemodel(model, PRVM_G_EDICT(OFS_PARM0));
6828         TriangleNormal((animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex), (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 3, (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 6, normal);
6829         applytransform_forward_normal(normal, PRVM_G_EDICT(OFS_PARM0), PRVM_G_VECTOR(OFS_RETURN));
6830         VectorNormalize(PRVM_G_VECTOR(OFS_RETURN));
6831 }
6832 //PF_getsurfacetexture,   // #437 string(entity e, float s) getsurfacetexture = #437;
6833 void VM_getsurfacetexture(void)
6834 {
6835         dp_model_t *model;
6836         msurface_t *surface;
6837         VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6838         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6839         if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6840                 return;
6841         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(surface->texture->name);
6842 }
6843 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6844 void VM_getsurfacenearpoint(void)
6845 {
6846         int surfacenum, best;
6847         vec3_t clipped, p;
6848         vec_t dist, bestdist;
6849         prvm_edict_t *ed;
6850         dp_model_t *model;
6851         msurface_t *surface;
6852         vec_t *point;
6853         VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6854         PRVM_G_FLOAT(OFS_RETURN) = -1;
6855         ed = PRVM_G_EDICT(OFS_PARM0);
6856         point = PRVM_G_VECTOR(OFS_PARM1);
6857
6858         if (!ed || ed->priv.server->free)
6859                 return;
6860         model = getmodel(ed);
6861         if (!model || !model->num_surfaces)
6862                 return;
6863
6864         animatemodel(model, ed);
6865
6866         applytransform_inverted(point, ed, p);
6867         best = -1;
6868         bestdist = 1000000000;
6869         for (surfacenum = 0;surfacenum < model->nummodelsurfaces;surfacenum++)
6870         {
6871                 surface = model->data_surfaces + surfacenum + model->firstmodelsurface;
6872                 // first see if the nearest point on the surface's box is closer than the previous match
6873                 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6874                 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6875                 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6876                 dist = VectorLength2(clipped);
6877                 if (dist < bestdist)
6878                 {
6879                         // it is, check the nearest point on the actual geometry
6880                         clippointtosurface(ed, model, surface, p, clipped);
6881                         VectorSubtract(clipped, p, clipped);
6882                         dist += VectorLength2(clipped);
6883                         if (dist < bestdist)
6884                         {
6885                                 // that's closer too, store it as the best match
6886                                 best = surfacenum;
6887                                 bestdist = dist;
6888                         }
6889                 }
6890         }
6891         PRVM_G_FLOAT(OFS_RETURN) = best;
6892 }
6893 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6894 void VM_getsurfaceclippedpoint(void)
6895 {
6896         prvm_edict_t *ed;
6897         dp_model_t *model;
6898         msurface_t *surface;
6899         vec3_t p, out;
6900         VM_SAFEPARMCOUNT(3, VM_te_getsurfaceclippedpoint);
6901         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6902         ed = PRVM_G_EDICT(OFS_PARM0);
6903         if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6904                 return;
6905         animatemodel(model, ed);
6906         applytransform_inverted(PRVM_G_VECTOR(OFS_PARM2), ed, p);
6907         clippointtosurface(ed, model, surface, p, out);
6908         VectorAdd(out, PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_RETURN));
6909 }
6910
6911 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6912 void VM_getsurfacenumtriangles(void)
6913 {
6914        dp_model_t *model;
6915        msurface_t *surface;
6916        VM_SAFEPARMCOUNT(2, VM_SV_getsurfacenumtriangles);
6917        // return 0 if no such surface
6918        if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6919        {
6920                PRVM_G_FLOAT(OFS_RETURN) = 0;
6921                return;
6922        }
6923
6924        // note: this (incorrectly) assumes it is a simple polygon
6925        PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6926 }
6927 //PF_getsurfacetriangle,     // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6928 void VM_getsurfacetriangle(void)
6929 {
6930        const vec3_t d = {-1, -1, -1};
6931        prvm_edict_t *ed;
6932        dp_model_t *model;
6933        msurface_t *surface;
6934        int trinum;
6935        VM_SAFEPARMCOUNT(3, VM_SV_getsurfacetriangle);
6936        VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6937        ed = PRVM_G_EDICT(OFS_PARM0);
6938        if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6939                return;
6940        trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6941        if (trinum < 0 || trinum >= surface->num_triangles)
6942                return;
6943        // FIXME: implement rotation/scaling
6944        VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6945 }
6946
6947 //
6948 // physics builtins
6949 //
6950
6951 void World_Physics_ApplyCmd(prvm_edict_t *ed, edict_odefunc_t *f);
6952
6953 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(ed, f); else World_Physics_ApplyCmd(ed, f)
6954
6955 edict_odefunc_t *VM_physics_newstackfunction(prvm_edict_t *ed, edict_odefunc_t *f)
6956 {
6957         edict_odefunc_t *newfunc, *func;
6958
6959         newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6960         memcpy(newfunc, f, sizeof(edict_odefunc_t));
6961         newfunc->next = NULL;
6962         if (!ed->priv.server->ode_func)
6963                 ed->priv.server->ode_func = newfunc;
6964         else
6965         {
6966                 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6967                 func->next = newfunc;
6968         }
6969         return newfunc;
6970 }
6971
6972 // void(entity e, float physics_enabled) physics_enable = #;
6973 void VM_physics_enable(void)
6974 {
6975         prvm_edict_t *ed;
6976         edict_odefunc_t f;
6977         
6978         VM_SAFEPARMCOUNT(2, VM_physics_enable);
6979         ed = PRVM_G_EDICT(OFS_PARM0);
6980         if (!ed)
6981         {
6982                 if (developer.integer > 0)
6983                         VM_Warning("VM_physics_enable: null entity!\n");
6984                 return;
6985         }
6986         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6987         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6988         {
6989                 VM_Warning("VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
6990                 return;
6991         }
6992         f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
6993         VM_physics_ApplyCmd(ed, &f);
6994 }
6995
6996 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
6997 void VM_physics_addforce(void)
6998 {
6999         prvm_edict_t *ed;
7000         edict_odefunc_t f;
7001         
7002         VM_SAFEPARMCOUNT(3, VM_physics_addforce);
7003         ed = PRVM_G_EDICT(OFS_PARM0);
7004         if (!ed)
7005         {
7006                 if (developer.integer > 0)
7007                         VM_Warning("VM_physics_addforce: null entity!\n");
7008                 return;
7009         }
7010         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
7011         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
7012         {
7013                 VM_Warning("VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
7014                 return;
7015         }
7016         f.type = ODEFUNC_RELFORCEATPOS;
7017         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
7018         VectorSubtract(PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_PARM2), f.v2);
7019         VM_physics_ApplyCmd(ed, &f);
7020 }
7021
7022 // void(entity e, vector torque) physics_addtorque = #;
7023 void VM_physics_addtorque(void)
7024 {
7025         prvm_edict_t *ed;
7026         edict_odefunc_t f;
7027         
7028         VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
7029         ed = PRVM_G_EDICT(OFS_PARM0);
7030         if (!ed)
7031         {
7032                 if (developer.integer > 0)
7033                         VM_Warning("VM_physics_addtorque: null entity!\n");
7034                 return;
7035         }
7036         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
7037         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
7038         {
7039                 VM_Warning("VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
7040                 return;
7041         }
7042         f.type = ODEFUNC_RELTORQUE;
7043         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
7044         VM_physics_ApplyCmd(ed, &f);
7045 }