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