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