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