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