Try to fix a dedicated server crash by moving the two csqc_ cvar initializations
[divverent/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 "prvm_cmds.h"
8
9 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
10 void VM_Warning(const char *fmt, ...)
11 {
12         va_list argptr;
13         char msg[MAX_INPUTLINE];
14
15         va_start(argptr,fmt);
16         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
17         va_end(argptr);
18
19         Con_Print(msg);
20         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
21         //PRVM_PrintState();
22 }
23
24
25 //============================================================================
26 // Common
27
28 // temp string handling
29 // LordHavoc: added this to semi-fix the problem of using many ftos calls in a print
30 static char vm_string_temp[VM_STRINGTEMP_BUFFERS][VM_STRINGTEMP_LENGTH];
31 static int vm_string_tempindex = 0;
32
33 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct)
34 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
35 char *VM_GetTempString(void)
36 {
37         char *s;
38         s = vm_string_temp[vm_string_tempindex];
39         vm_string_tempindex = (vm_string_tempindex + 1) % VM_STRINGTEMP_BUFFERS;
40         return s;
41 }
42
43 void VM_CheckEmptyString (const char *s)
44 {
45         if (s[0] <= ' ')
46                 PRVM_ERROR ("%s: Bad string", PRVM_NAME);
47 }
48
49 //============================================================================
50 //BUILT-IN FUNCTIONS
51
52 void VM_VarString(int first, char *out, int outlength)
53 {
54         int i;
55         const char *s;
56         char *outend;
57
58         outend = out + outlength - 1;
59         for (i = first;i < prog->argc && out < outend;i++)
60         {
61                 s = PRVM_G_STRING((OFS_PARM0+i*3));
62                 while (out < outend && *s)
63                         *out++ = *s++;
64         }
65         *out++ = 0;
66 }
67
68 /*
69 =================
70 VM_checkextension
71
72 returns true if the extension is supported by the server
73
74 checkextension(extensionname)
75 =================
76 */
77
78 // kind of helper function
79 static qboolean checkextension(const char *name)
80 {
81         int len;
82         char *e, *start;
83         len = (int)strlen(name);
84
85         for (e = prog->extensionstring;*e;e++)
86         {
87                 while (*e == ' ')
88                         e++;
89                 if (!*e)
90                         break;
91                 start = e;
92                 while (*e && *e != ' ')
93                         e++;
94                 if ((e - start) == len && !strncasecmp(start, name, len))
95                         return true;
96         }
97         return false;
98 }
99
100 void VM_checkextension (void)
101 {
102         VM_SAFEPARMCOUNT(1,VM_checkextension);
103
104         PRVM_G_FLOAT(OFS_RETURN) = checkextension(PRVM_G_STRING(OFS_PARM0));
105 }
106
107 /*
108 =================
109 VM_error
110
111 This is a TERMINAL error, which will kill off the entire prog.
112 Dumps self.
113
114 error(value)
115 =================
116 */
117 void VM_error (void)
118 {
119         prvm_edict_t    *ed;
120         char string[VM_STRINGTEMP_LENGTH];
121
122         VM_VarString(0, string, sizeof(string));
123         Con_Printf("======%s ERROR in %s:\n%s\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
124         if(prog->self)
125         {
126                 ed = PRVM_G_EDICT(prog->self->ofs);
127                 PRVM_ED_Print(ed);
128         }
129
130         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);
131 }
132
133 /*
134 =================
135 VM_objerror
136
137 Dumps out self, then an error message.  The program is aborted and self is
138 removed, but the level can continue.
139
140 objerror(value)
141 =================
142 */
143 void VM_objerror (void)
144 {
145         prvm_edict_t    *ed;
146         char string[VM_STRINGTEMP_LENGTH];
147
148         VM_VarString(0, string, sizeof(string));
149         Con_Printf("======OBJECT ERROR======\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
150         if(prog->self)
151         {
152                 ed = PRVM_G_EDICT (prog->self->ofs);
153                 PRVM_ED_Print(ed);
154
155                 PRVM_ED_Free (ed);
156         }
157         else
158                 // objerror has to display the object fields -> else call
159                 PRVM_ERROR ("VM_objecterror: self not defined !");
160         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);
161 }
162
163 /*
164 =================
165 VM_print (actually used only by client and menu)
166
167 print to console
168
169 print(string)
170 =================
171 */
172 void VM_print (void)
173 {
174         char string[VM_STRINGTEMP_LENGTH];
175
176         VM_VarString(0, string, sizeof(string));
177         Con_Print(string);
178 }
179
180 /*
181 =================
182 VM_bprint
183
184 broadcast print to everyone on server
185
186 bprint(...[string])
187 =================
188 */
189 void VM_bprint (void)
190 {
191         char string[VM_STRINGTEMP_LENGTH];
192
193         if(!sv.active)
194         {
195                 VM_Warning("VM_bprint: game is not server(%s) !\n", PRVM_NAME);
196                 return;
197         }
198
199         VM_VarString(0, string, sizeof(string));
200         SV_BroadcastPrint(string);
201 }
202
203 /*
204 =================
205 VM_sprint (menu & client but only if server.active == true)
206
207 single print to a specific client
208
209 sprint(float clientnum,...[string])
210 =================
211 */
212 void VM_sprint (void)
213 {
214         client_t        *client;
215         int                     clientnum;
216         char string[VM_STRINGTEMP_LENGTH];
217
218         //find client for this entity
219         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
220         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
221         {
222                 VM_Warning("VM_sprint: %s: invalid client or server is not active !\n", PRVM_NAME);
223                 return;
224         }
225
226         client = svs.clients + clientnum;
227         if (!client->netconnection)
228                 return;
229
230         VM_VarString(1, string, sizeof(string));
231         MSG_WriteChar(&client->netconnection->message,svc_print);
232         MSG_WriteString(&client->netconnection->message, string);
233 }
234
235 /*
236 =================
237 VM_centerprint
238
239 single print to the screen
240
241 centerprint(clientent, value)
242 =================
243 */
244 void VM_centerprint (void)
245 {
246         char string[VM_STRINGTEMP_LENGTH];
247
248         VM_VarString(0, string, sizeof(string));
249         SCR_CenterPrint(string);
250 }
251
252 /*
253 =================
254 VM_normalize
255
256 vector normalize(vector)
257 =================
258 */
259 void VM_normalize (void)
260 {
261         float   *value1;
262         vec3_t  newvalue;
263         double  f;
264
265         VM_SAFEPARMCOUNT(1,VM_normalize);
266
267         value1 = PRVM_G_VECTOR(OFS_PARM0);
268
269         f = VectorLength2(value1);
270         if (f)
271         {
272                 f = 1.0 / sqrt(f);
273                 VectorScale(value1, f, newvalue);
274         }
275         else
276                 VectorClear(newvalue);
277
278         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
279 }
280
281 /*
282 =================
283 VM_vlen
284
285 scalar vlen(vector)
286 =================
287 */
288 void VM_vlen (void)
289 {
290         VM_SAFEPARMCOUNT(1,VM_vlen);
291         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
292 }
293
294 /*
295 =================
296 VM_vectoyaw
297
298 float vectoyaw(vector)
299 =================
300 */
301 void VM_vectoyaw (void)
302 {
303         float   *value1;
304         float   yaw;
305
306         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
307
308         value1 = PRVM_G_VECTOR(OFS_PARM0);
309
310         if (value1[1] == 0 && value1[0] == 0)
311                 yaw = 0;
312         else
313         {
314                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
315                 if (yaw < 0)
316                         yaw += 360;
317         }
318
319         PRVM_G_FLOAT(OFS_RETURN) = yaw;
320 }
321
322
323 /*
324 =================
325 VM_vectoangles
326
327 vector vectoangles(vector)
328 =================
329 */
330 void VM_vectoangles (void)
331 {
332         float   *value1;
333         float   forward;
334         float   yaw, pitch;
335
336         VM_SAFEPARMCOUNT(1,VM_vectoangles);
337
338         value1 = PRVM_G_VECTOR(OFS_PARM0);
339
340         if (value1[1] == 0 && value1[0] == 0)
341         {
342                 yaw = 0;
343                 if (value1[2] > 0)
344                         pitch = 90;
345                 else
346                         pitch = 270;
347         }
348         else
349         {
350                 // LordHavoc: optimized a bit
351                 if (value1[0])
352                 {
353                         yaw = (atan2(value1[1], value1[0]) * 180 / M_PI);
354                         if (yaw < 0)
355                                 yaw += 360;
356                 }
357                 else if (value1[1] > 0)
358                         yaw = 90;
359                 else
360                         yaw = 270;
361
362                 forward = sqrt(value1[0]*value1[0] + value1[1]*value1[1]);
363                 pitch = (atan2(value1[2], forward) * 180 / M_PI);
364                 if (pitch < 0)
365                         pitch += 360;
366         }
367
368         PRVM_G_FLOAT(OFS_RETURN+0) = pitch;
369         PRVM_G_FLOAT(OFS_RETURN+1) = yaw;
370         PRVM_G_FLOAT(OFS_RETURN+2) = 0;
371 }
372
373 /*
374 =================
375 VM_random
376
377 Returns a number from 0<= num < 1
378
379 float random()
380 =================
381 */
382 void VM_random (void)
383 {
384         VM_SAFEPARMCOUNT(0,VM_random);
385
386         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
387 }
388
389 /*
390 =================
391 PF_sound
392
393 Each entity can have eight independant sound sources, like voice,
394 weapon, feet, etc.
395
396 Channel 0 is an auto-allocate channel, the others override anything
397 already running on that entity/channel pair.
398
399 An attenuation of 0 will play full volume everywhere in the level.
400 Larger attenuations will drop off.
401
402 =================
403 */
404 /*
405 void PF_sound (void)
406 {
407         char            *sample;
408         int                     channel;
409         prvm_edict_t            *entity;
410         int             volume;
411         float attenuation;
412
413         entity = PRVM_G_EDICT(OFS_PARM0);
414         channel = PRVM_G_FLOAT(OFS_PARM1);
415         sample = PRVM_G_STRING(OFS_PARM2);
416         volume = PRVM_G_FLOAT(OFS_PARM3) * 255;
417         attenuation = PRVM_G_FLOAT(OFS_PARM4);
418
419         if (volume < 0 || volume > 255)
420                 Host_Error ("SV_StartSound: volume = %i", volume);
421
422         if (attenuation < 0 || attenuation > 4)
423                 Host_Error ("SV_StartSound: attenuation = %f", attenuation);
424
425         if (channel < 0 || channel > 7)
426                 Host_Error ("SV_StartSound: channel = %i", channel);
427
428         SV_StartSound (entity, channel, sample, volume, attenuation);
429 }
430 */
431
432 /*
433 =========
434 VM_localsound
435
436 localsound(string sample)
437 =========
438 */
439 void VM_localsound(void)
440 {
441         const char *s;
442
443         VM_SAFEPARMCOUNT(1,VM_localsound);
444
445         s = PRVM_G_STRING(OFS_PARM0);
446
447         if(!S_LocalSound (s))
448         {
449                 PRVM_G_FLOAT(OFS_RETURN) = -4;
450                 VM_Warning("VM_localsound: Failed to play %s for %s !\n", s, PRVM_NAME);
451                 return;
452         }
453
454         PRVM_G_FLOAT(OFS_RETURN) = 1;
455 }
456
457 /*
458 =================
459 VM_break
460
461 break()
462 =================
463 */
464 void VM_break (void)
465 {
466         PRVM_ERROR ("%s: break statement", PRVM_NAME);
467 }
468
469 //============================================================================
470
471 /*
472 =================
473 VM_localcmd
474
475 Sends text over to the client's execution buffer
476
477 [localcmd (string, ...) or]
478 cmd (string, ...)
479 =================
480 */
481 void VM_localcmd (void)
482 {
483         char string[VM_STRINGTEMP_LENGTH];
484         VM_VarString(0, string, sizeof(string));
485         Cbuf_AddText(string);
486 }
487
488 /*
489 =================
490 VM_cvar
491
492 float cvar (string)
493 =================
494 */
495 void VM_cvar (void)
496 {
497         VM_SAFEPARMCOUNT(1,VM_cvar);
498
499         PRVM_G_FLOAT(OFS_RETURN) = Cvar_VariableValue(PRVM_G_STRING(OFS_PARM0));
500 }
501
502 /*
503 =================
504 VM_cvar_string
505
506 const string    VM_cvar_string (string)
507 =================
508 */
509 void VM_cvar_string(void)
510 {
511         char *out;
512         const char *name;
513         const char *cvar_string;
514         VM_SAFEPARMCOUNT(1,VM_cvar_string);
515
516         name = PRVM_G_STRING(OFS_PARM0);
517
518         if(!name)
519                 PRVM_ERROR("VM_cvar_string: %s: null string", PRVM_NAME);
520
521         VM_CheckEmptyString(name);
522
523         out = VM_GetTempString();
524
525         cvar_string = Cvar_VariableString(name);
526
527         strlcpy(out, cvar_string, VM_STRINGTEMP_LENGTH);
528
529         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(out);
530 }
531
532
533 /*
534 ========================
535 VM_cvar_defstring
536
537 const string    VM_cvar_defstring (string)
538 ========================
539 */
540 void VM_cvar_defstring (void)
541 {
542         char *out;
543         const char *name;
544         const char *cvar_string;
545         VM_SAFEPARMCOUNT(1,VM_cvar_string);
546
547         name = PRVM_G_STRING(OFS_PARM0);
548
549         if(!name)
550                 PRVM_ERROR("VM_cvar_defstring: %s: null string", PRVM_NAME);
551
552         VM_CheckEmptyString(name);
553
554         out = VM_GetTempString();
555
556         cvar_string = Cvar_VariableDefString(name);
557
558         strlcpy(out, cvar_string, VM_STRINGTEMP_LENGTH);
559
560         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(out);
561 }
562 /*
563 =================
564 VM_cvar_set
565
566 void cvar_set (string,string)
567 =================
568 */
569 void VM_cvar_set (void)
570 {
571         VM_SAFEPARMCOUNT(2,VM_cvar_set);
572
573         Cvar_Set(PRVM_G_STRING(OFS_PARM0), PRVM_G_STRING(OFS_PARM1));
574 }
575
576 /*
577 =========
578 VM_dprint
579
580 dprint(...[string])
581 =========
582 */
583 void VM_dprint (void)
584 {
585         char string[VM_STRINGTEMP_LENGTH];
586         if (developer.integer)
587         {
588                 VM_VarString(0, string, sizeof(string));
589 #if 1
590                 Con_Printf("%s", string);
591 #else
592                 Con_Printf("%s: %s", PRVM_NAME, string);
593 #endif
594         }
595 }
596
597 /*
598 =========
599 VM_ftos
600
601 string  ftos(float)
602 =========
603 */
604
605 void VM_ftos (void)
606 {
607         float v;
608         char *s;
609
610         VM_SAFEPARMCOUNT(1, VM_ftos);
611
612         v = PRVM_G_FLOAT(OFS_PARM0);
613
614         s = VM_GetTempString();
615         if ((float)((int)v) == v)
616                 sprintf(s, "%i", (int)v);
617         else
618                 sprintf(s, "%f", v);
619         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(s);
620 }
621
622 /*
623 =========
624 VM_fabs
625
626 float   fabs(float)
627 =========
628 */
629
630 void VM_fabs (void)
631 {
632         float   v;
633
634         VM_SAFEPARMCOUNT(1,VM_fabs);
635
636         v = PRVM_G_FLOAT(OFS_PARM0);
637         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
638 }
639
640 /*
641 =========
642 VM_vtos
643
644 string  vtos(vector)
645 =========
646 */
647
648 void VM_vtos (void)
649 {
650         char *s;
651
652         VM_SAFEPARMCOUNT(1,VM_vtos);
653
654         s = VM_GetTempString();
655         sprintf (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]);
656         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(s);
657 }
658
659 /*
660 =========
661 VM_etos
662
663 string  etos(entity)
664 =========
665 */
666
667 void VM_etos (void)
668 {
669         char *s;
670
671         VM_SAFEPARMCOUNT(1, VM_etos);
672
673         s = VM_GetTempString();
674         sprintf (s, "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
675         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(s);
676 }
677
678 /*
679 =========
680 VM_stof
681
682 float stof(...[string])
683 =========
684 */
685 void VM_stof(void)
686 {
687         char string[VM_STRINGTEMP_LENGTH];
688         VM_VarString(0, string, sizeof(string));
689         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
690 }
691
692 /*
693 ========================
694 VM_itof
695
696 float itof(intt ent)
697 ========================
698 */
699 void VM_itof(void)
700 {
701         VM_SAFEPARMCOUNT(1, VM_itof);
702         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
703 }
704
705 /*
706 ========================
707 VM_ftoe
708
709 entity ftoe(float num)
710 ========================
711 */
712 void VM_ftoe(void)
713 {
714         int ent;
715         VM_SAFEPARMCOUNT(1, VM_ftoe);
716
717         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
718         if (ent < 0 || ent >= MAX_EDICTS || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
719                 ent = 0; // return world instead of a free or invalid entity
720
721         PRVM_G_INT(OFS_RETURN) = ent;
722 }
723
724 /*
725 =========
726 VM_spawn
727
728 entity spawn()
729 =========
730 */
731
732 void VM_spawn (void)
733 {
734         prvm_edict_t    *ed;
735         prog->xfunction->builtinsprofile += 20;
736         ed = PRVM_ED_Alloc();
737         VM_RETURN_EDICT(ed);
738 }
739
740 /*
741 =========
742 VM_remove
743
744 remove(entity e)
745 =========
746 */
747
748 void VM_remove (void)
749 {
750         prvm_edict_t    *ed;
751         prog->xfunction->builtinsprofile += 20;
752
753         VM_SAFEPARMCOUNT(1, VM_remove);
754
755         ed = PRVM_G_EDICT(OFS_PARM0);
756         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
757         {
758                 if (developer.integer >= 1)
759                         VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
760         }
761         else if( ed->priv.required->free )
762         {
763                 if (developer.integer >= 1)
764                         VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
765         }
766         else
767                 PRVM_ED_Free (ed);
768 //      if (ed == prog->edicts)
769 //              PRVM_ERROR ("remove: tried to remove world");
770 //      if (PRVM_NUM_FOR_EDICT(ed) <= sv.maxclients)
771 //              Host_Error("remove: tried to remove a client");
772 }
773
774 /*
775 =========
776 VM_find
777
778 entity  find(entity start, .string field, string match)
779 =========
780 */
781
782 void VM_find (void)
783 {
784         int             e;
785         int             f;
786         const char      *s, *t;
787         prvm_edict_t    *ed;
788
789         VM_SAFEPARMCOUNT(3,VM_find);
790
791         e = PRVM_G_EDICTNUM(OFS_PARM0);
792         f = PRVM_G_INT(OFS_PARM1);
793         s = PRVM_G_STRING(OFS_PARM2);
794
795         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
796         // expects it to find all the monsters, so we must be careful to support
797         // searching for ""
798         if (!s)
799                 s = "";
800
801         for (e++ ; e < prog->num_edicts ; e++)
802         {
803                 prog->xfunction->builtinsprofile++;
804                 ed = PRVM_EDICT_NUM(e);
805                 if (ed->priv.required->free)
806                         continue;
807                 t = PRVM_E_STRING(ed,f);
808                 if (!t)
809                         t = "";
810                 if (!strcmp(t,s))
811                 {
812                         VM_RETURN_EDICT(ed);
813                         return;
814                 }
815         }
816
817         VM_RETURN_EDICT(prog->edicts);
818 }
819
820 /*
821 =========
822 VM_findfloat
823
824   entity        findfloat(entity start, .float field, float match)
825   entity        findentity(entity start, .entity field, entity match)
826 =========
827 */
828 // LordHavoc: added this for searching float, int, and entity reference fields
829 void VM_findfloat (void)
830 {
831         int             e;
832         int             f;
833         float   s;
834         prvm_edict_t    *ed;
835
836         VM_SAFEPARMCOUNT(3,VM_findfloat);
837
838         e = PRVM_G_EDICTNUM(OFS_PARM0);
839         f = PRVM_G_INT(OFS_PARM1);
840         s = PRVM_G_FLOAT(OFS_PARM2);
841
842         for (e++ ; e < prog->num_edicts ; e++)
843         {
844                 prog->xfunction->builtinsprofile++;
845                 ed = PRVM_EDICT_NUM(e);
846                 if (ed->priv.required->free)
847                         continue;
848                 if (PRVM_E_FLOAT(ed,f) == s)
849                 {
850                         VM_RETURN_EDICT(ed);
851                         return;
852                 }
853         }
854
855         VM_RETURN_EDICT(prog->edicts);
856 }
857
858 /*
859 =========
860 VM_findchain
861
862 entity  findchain(.string field, string match)
863 =========
864 */
865 // chained search for strings in entity fields
866 // entity(.string field, string match) findchain = #402;
867 void VM_findchain (void)
868 {
869         int             i;
870         int             f;
871         int             chain_of;
872         const char      *s, *t;
873         prvm_edict_t    *ent, *chain;
874
875         VM_SAFEPARMCOUNT(2,VM_findchain);
876
877         // is the same like !(prog->flag & PRVM_FE_CHAIN) - even if the operator precedence is another
878         if(!prog->flag & PRVM_FE_CHAIN)
879                 PRVM_ERROR("VM_findchain: %s doesnt have a chain field !", PRVM_NAME);
880
881         chain_of = PRVM_ED_FindField("chain")->ofs;
882
883         chain = prog->edicts;
884
885         f = PRVM_G_INT(OFS_PARM0);
886         s = PRVM_G_STRING(OFS_PARM1);
887
888         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
889         // expects it to find all the monsters, so we must be careful to support
890         // searching for ""
891         if (!s)
892                 s = "";
893
894         ent = PRVM_NEXT_EDICT(prog->edicts);
895         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
896         {
897                 prog->xfunction->builtinsprofile++;
898                 if (ent->priv.required->free)
899                         continue;
900                 t = PRVM_E_STRING(ent,f);
901                 if (!t)
902                         t = "";
903                 if (strcmp(t,s))
904                         continue;
905
906                 PRVM_E_INT(ent,chain_of) = PRVM_NUM_FOR_EDICT(chain);
907                 chain = ent;
908         }
909
910         VM_RETURN_EDICT(chain);
911 }
912
913 /*
914 =========
915 VM_findchainfloat
916
917 entity  findchainfloat(.string field, float match)
918 entity  findchainentity(.string field, entity match)
919 =========
920 */
921 // LordHavoc: chained search for float, int, and entity reference fields
922 // entity(.string field, float match) findchainfloat = #403;
923 void VM_findchainfloat (void)
924 {
925         int             i;
926         int             f;
927         int             chain_of;
928         float   s;
929         prvm_edict_t    *ent, *chain;
930
931         VM_SAFEPARMCOUNT(2, VM_findchainfloat);
932
933         if(!prog->flag & PRVM_FE_CHAIN)
934                 PRVM_ERROR("VM_findchainfloat: %s doesnt have a chain field !", PRVM_NAME);
935
936         chain_of = PRVM_ED_FindField("chain")->ofs;
937
938         chain = (prvm_edict_t *)prog->edicts;
939
940         f = PRVM_G_INT(OFS_PARM0);
941         s = PRVM_G_FLOAT(OFS_PARM1);
942
943         ent = PRVM_NEXT_EDICT(prog->edicts);
944         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
945         {
946                 prog->xfunction->builtinsprofile++;
947                 if (ent->priv.required->free)
948                         continue;
949                 if (PRVM_E_FLOAT(ent,f) != s)
950                         continue;
951
952                 PRVM_E_INT(ent,chain_of) = PRVM_EDICT_TO_PROG(chain);
953                 chain = ent;
954         }
955
956         VM_RETURN_EDICT(chain);
957 }
958
959 /*
960 ========================
961 VM_findflags
962
963 entity  findflags(entity start, .float field, float match)
964 ========================
965 */
966 // LordHavoc: search for flags in float fields
967 void VM_findflags (void)
968 {
969         int             e;
970         int             f;
971         int             s;
972         prvm_edict_t    *ed;
973
974         VM_SAFEPARMCOUNT(3, VM_findflags);
975
976
977         e = PRVM_G_EDICTNUM(OFS_PARM0);
978         f = PRVM_G_INT(OFS_PARM1);
979         s = (int)PRVM_G_FLOAT(OFS_PARM2);
980
981         for (e++ ; e < prog->num_edicts ; e++)
982         {
983                 prog->xfunction->builtinsprofile++;
984                 ed = PRVM_EDICT_NUM(e);
985                 if (ed->priv.required->free)
986                         continue;
987                 if (!PRVM_E_FLOAT(ed,f))
988                         continue;
989                 if ((int)PRVM_E_FLOAT(ed,f) & s)
990                 {
991                         VM_RETURN_EDICT(ed);
992                         return;
993                 }
994         }
995
996         VM_RETURN_EDICT(prog->edicts);
997 }
998
999 /*
1000 ========================
1001 VM_findchainflags
1002
1003 entity  findchainflags(.float field, float match)
1004 ========================
1005 */
1006 // LordHavoc: chained search for flags in float fields
1007 void VM_findchainflags (void)
1008 {
1009         int             i;
1010         int             f;
1011         int             s;
1012         int             chain_of;
1013         prvm_edict_t    *ent, *chain;
1014
1015         VM_SAFEPARMCOUNT(2, VM_findchainflags);
1016
1017         if(!prog->flag & PRVM_FE_CHAIN)
1018                 PRVM_ERROR("VM_findchainflags: %s doesnt have a chain field !", PRVM_NAME);
1019
1020         chain_of = PRVM_ED_FindField("chain")->ofs;
1021
1022         chain = (prvm_edict_t *)prog->edicts;
1023
1024         f = PRVM_G_INT(OFS_PARM0);
1025         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1026
1027         ent = PRVM_NEXT_EDICT(prog->edicts);
1028         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1029         {
1030                 prog->xfunction->builtinsprofile++;
1031                 if (ent->priv.required->free)
1032                         continue;
1033                 if (!PRVM_E_FLOAT(ent,f))
1034                         continue;
1035                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1036                         continue;
1037
1038                 PRVM_E_INT(ent,chain_of) = PRVM_EDICT_TO_PROG(chain);
1039                 chain = ent;
1040         }
1041
1042         VM_RETURN_EDICT(chain);
1043 }
1044
1045 /*
1046 =========
1047 VM_coredump
1048
1049 coredump()
1050 =========
1051 */
1052 void VM_coredump (void)
1053 {
1054         VM_SAFEPARMCOUNT(0,VM_coredump);
1055
1056         Cbuf_AddText("prvm_edicts ");
1057         Cbuf_AddText(PRVM_NAME);
1058         Cbuf_AddText("\n");
1059 }
1060
1061 /*
1062 =========
1063 VM_stackdump
1064
1065 stackdump()
1066 =========
1067 */
1068 void PRVM_StackTrace(void);
1069 void VM_stackdump (void)
1070 {
1071         VM_SAFEPARMCOUNT(0, VM_stackdump);
1072
1073         PRVM_StackTrace();
1074 }
1075
1076 /*
1077 =========
1078 VM_crash
1079
1080 crash()
1081 =========
1082 */
1083
1084 void VM_crash(void)
1085 {
1086         VM_SAFEPARMCOUNT(0, VM_crash);
1087
1088         PRVM_ERROR("Crash called by %s",PRVM_NAME);
1089 }
1090
1091 /*
1092 =========
1093 VM_traceon
1094
1095 traceon()
1096 =========
1097 */
1098 void VM_traceon (void)
1099 {
1100         VM_SAFEPARMCOUNT(0,VM_traceon);
1101
1102         prog->trace = true;
1103 }
1104
1105 /*
1106 =========
1107 VM_traceoff
1108
1109 traceoff()
1110 =========
1111 */
1112 void VM_traceoff (void)
1113 {
1114         VM_SAFEPARMCOUNT(0,VM_traceoff);
1115
1116         prog->trace = false;
1117 }
1118
1119 /*
1120 =========
1121 VM_eprint
1122
1123 eprint(entity e)
1124 =========
1125 */
1126 void VM_eprint (void)
1127 {
1128         VM_SAFEPARMCOUNT(1,VM_eprint);
1129
1130         PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0));
1131 }
1132
1133 /*
1134 =========
1135 VM_rint
1136
1137 float   rint(float)
1138 =========
1139 */
1140 void VM_rint (void)
1141 {
1142         float f;
1143         VM_SAFEPARMCOUNT(1,VM_rint);
1144
1145         f = PRVM_G_FLOAT(OFS_PARM0);
1146         if (f > 0)
1147                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1148         else
1149                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1150 }
1151
1152 /*
1153 =========
1154 VM_floor
1155
1156 float   floor(float)
1157 =========
1158 */
1159 void VM_floor (void)
1160 {
1161         VM_SAFEPARMCOUNT(1,VM_floor);
1162
1163         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1164 }
1165
1166 /*
1167 =========
1168 VM_ceil
1169
1170 float   ceil(float)
1171 =========
1172 */
1173 void VM_ceil (void)
1174 {
1175         VM_SAFEPARMCOUNT(1,VM_ceil);
1176
1177         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1178 }
1179
1180
1181 /*
1182 =============
1183 VM_nextent
1184
1185 entity  nextent(entity)
1186 =============
1187 */
1188 void VM_nextent (void)
1189 {
1190         int             i;
1191         prvm_edict_t    *ent;
1192
1193         i = PRVM_G_EDICTNUM(OFS_PARM0);
1194         while (1)
1195         {
1196                 prog->xfunction->builtinsprofile++;
1197                 i++;
1198                 if (i == prog->num_edicts)
1199                 {
1200                         VM_RETURN_EDICT(prog->edicts);
1201                         return;
1202                 }
1203                 ent = PRVM_EDICT_NUM(i);
1204                 if (!ent->priv.required->free)
1205                 {
1206                         VM_RETURN_EDICT(ent);
1207                         return;
1208                 }
1209         }
1210 }
1211
1212 //=============================================================================
1213
1214 /*
1215 ==============
1216 VM_changelevel
1217 server and menu
1218
1219 changelevel(string map)
1220 ==============
1221 */
1222 void VM_changelevel (void)
1223 {
1224         const char      *s;
1225
1226         VM_SAFEPARMCOUNT(1, VM_changelevel);
1227
1228         if(!sv.active)
1229         {
1230                 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1231                 return;
1232         }
1233
1234 // make sure we don't issue two changelevels
1235         if (svs.changelevel_issued)
1236                 return;
1237         svs.changelevel_issued = true;
1238
1239         s = PRVM_G_STRING(OFS_PARM0);
1240         Cbuf_AddText (va("changelevel %s\n",s));
1241 }
1242
1243 /*
1244 =========
1245 VM_sin
1246
1247 float   sin(float)
1248 =========
1249 */
1250 void VM_sin (void)
1251 {
1252         VM_SAFEPARMCOUNT(1,VM_sin);
1253         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1254 }
1255
1256 /*
1257 =========
1258 VM_cos
1259 float   cos(float)
1260 =========
1261 */
1262 void VM_cos (void)
1263 {
1264         VM_SAFEPARMCOUNT(1,VM_cos);
1265         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1266 }
1267
1268 /*
1269 =========
1270 VM_sqrt
1271
1272 float   sqrt(float)
1273 =========
1274 */
1275 void VM_sqrt (void)
1276 {
1277         VM_SAFEPARMCOUNT(1,VM_sqrt);
1278         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1279 }
1280
1281 /*
1282 =================
1283 VM_randomvec
1284
1285 Returns a vector of length < 1 and > 0
1286
1287 vector randomvec()
1288 =================
1289 */
1290 void VM_randomvec (void)
1291 {
1292         vec3_t          temp;
1293         //float         length;
1294
1295         VM_SAFEPARMCOUNT(0, VM_randomvec);
1296
1297         //// WTF ??
1298         do
1299         {
1300                 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1301                 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1302                 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1303         }
1304         while (DotProduct(temp, temp) >= 1);
1305         VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1306
1307         /*
1308         temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1309         temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1310         temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1311         // length returned always > 0
1312         length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1313         VectorScale(temp,length, temp);*/
1314         //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1315 }
1316
1317 //=============================================================================
1318
1319 /*
1320 =========
1321 VM_registercvar
1322
1323 float   registercvar (string name, string value, float flags)
1324 =========
1325 */
1326 void VM_registercvar (void)
1327 {
1328         const char *name, *value;
1329         int     flags;
1330
1331         VM_SAFEPARMCOUNT(3,VM_registercvar);
1332
1333         name = PRVM_G_STRING(OFS_PARM0);
1334         value = PRVM_G_STRING(OFS_PARM1);
1335         flags = (int)PRVM_G_FLOAT(OFS_PARM2);
1336         PRVM_G_FLOAT(OFS_RETURN) = 0;
1337
1338         if(flags > CVAR_MAXFLAGSVAL)
1339                 return;
1340
1341 // first check to see if it has already been defined
1342         if (Cvar_FindVar (name))
1343                 return;
1344
1345 // check for overlap with a command
1346         if (Cmd_Exists (name))
1347         {
1348                 VM_Warning("VM_registercvar: %s is a command\n", name);
1349                 return;
1350         }
1351
1352         Cvar_Get(name, value, flags);
1353
1354         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1355 }
1356
1357 /*
1358 =================
1359 VM_min
1360
1361 returns the minimum of two supplied floats
1362
1363 float min(float a, float b, ...[float])
1364 =================
1365 */
1366 void VM_min (void)
1367 {
1368         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1369         if (prog->argc == 2)
1370                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1371         else if (prog->argc >= 3)
1372         {
1373                 int i;
1374                 float f = PRVM_G_FLOAT(OFS_PARM0);
1375                 for (i = 1;i < prog->argc;i++)
1376                         if (PRVM_G_FLOAT((OFS_PARM0+i*3)) < f)
1377                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1378                 PRVM_G_FLOAT(OFS_RETURN) = f;
1379         }
1380         else
1381                 PRVM_ERROR("VM_min: %s must supply at least 2 floats", PRVM_NAME);
1382 }
1383
1384 /*
1385 =================
1386 VM_max
1387
1388 returns the maximum of two supplied floats
1389
1390 float   max(float a, float b, ...[float])
1391 =================
1392 */
1393 void VM_max (void)
1394 {
1395         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1396         if (prog->argc == 2)
1397                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1398         else if (prog->argc >= 3)
1399         {
1400                 int i;
1401                 float f = PRVM_G_FLOAT(OFS_PARM0);
1402                 for (i = 1;i < prog->argc;i++)
1403                         if (PRVM_G_FLOAT((OFS_PARM0+i*3)) > f)
1404                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1405                 PRVM_G_FLOAT(OFS_RETURN) = f;
1406         }
1407         else
1408                 PRVM_ERROR("VM_max: %s must supply at least 2 floats", PRVM_NAME);
1409 }
1410
1411 /*
1412 =================
1413 VM_bound
1414
1415 returns number bounded by supplied range
1416
1417 float   bound(float min, float value, float max)
1418 =================
1419 */
1420 void VM_bound (void)
1421 {
1422         VM_SAFEPARMCOUNT(3,VM_bound);
1423         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1424 }
1425
1426 /*
1427 =================
1428 VM_pow
1429
1430 returns a raised to power b
1431
1432 float   pow(float a, float b)
1433 =================
1434 */
1435 void VM_pow (void)
1436 {
1437         VM_SAFEPARMCOUNT(2,VM_pow);
1438         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1439 }
1440
1441 /*
1442 =================
1443 VM_copyentity
1444
1445 copies data from one entity to another
1446
1447 copyentity(entity src, entity dst)
1448 =================
1449 */
1450 void VM_copyentity (void)
1451 {
1452         prvm_edict_t *in, *out;
1453         VM_SAFEPARMCOUNT(2,VM_copyentity);
1454         in = PRVM_G_EDICT(OFS_PARM0);
1455         out = PRVM_G_EDICT(OFS_PARM1);
1456         memcpy(out->fields.vp, in->fields.vp, prog->progs->entityfields * 4);
1457 }
1458
1459 /*
1460 =================
1461 VM_setcolor
1462
1463 sets the color of a client and broadcasts the update to all connected clients
1464
1465 setcolor(clientent, value)
1466 =================
1467 */
1468 /*void PF_setcolor (void)
1469 {
1470         client_t *client;
1471         int entnum, i;
1472         prvm_eval_t *val;
1473
1474         entnum = PRVM_G_EDICTNUM(OFS_PARM0);
1475         i = PRVM_G_FLOAT(OFS_PARM1);
1476
1477         if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active)
1478         {
1479                 Con_Print("tried to setcolor a non-client\n");
1480                 return;
1481         }
1482
1483         client = svs.clients + entnum-1;
1484         if ((val = PRVM_GETEDICTFIELDVALUE(client->edict, eval_clientcolors)))
1485                 val->_float = i;
1486         client->colors = i;
1487         client->old_colors = i;
1488         client->edict->fields.server->team = (i & 15) + 1;
1489
1490         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
1491         MSG_WriteByte (&sv.reliable_datagram, entnum - 1);
1492         MSG_WriteByte (&sv.reliable_datagram, i);
1493 }*/
1494
1495 void VM_Files_Init(void)
1496 {
1497         int i;
1498         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1499                 prog->openfiles[i] = NULL;
1500 }
1501
1502 void VM_Files_CloseAll(void)
1503 {
1504         int i;
1505         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1506         {
1507                 if (prog->openfiles[i])
1508                         FS_Close(prog->openfiles[i]);
1509                 prog->openfiles[i] = NULL;
1510         }
1511 }
1512
1513 qfile_t *VM_GetFileHandle( int index )
1514 {
1515         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1516         {
1517                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1518                 return NULL;
1519         }
1520         if (prog->openfiles[index] == NULL)
1521         {
1522                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1523                 return NULL;
1524         }
1525         return prog->openfiles[index];
1526 }
1527
1528 /*
1529 =========
1530 VM_fopen
1531
1532 float   fopen(string filename, float mode)
1533 =========
1534 */
1535 // float(string filename, float mode) fopen = #110;
1536 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1537 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1538 void VM_fopen(void)
1539 {
1540         int filenum, mode;
1541         const char *modestring, *filename;
1542
1543         VM_SAFEPARMCOUNT(2,VM_fopen);
1544
1545         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1546                 if (prog->openfiles[filenum] == NULL)
1547                         break;
1548         if (filenum >= PRVM_MAX_OPENFILES)
1549         {
1550                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1551                 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENFILES);
1552                 return;
1553         }
1554         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1555         switch(mode)
1556         {
1557         case 0: // FILE_READ
1558                 modestring = "rb";
1559                 break;
1560         case 1: // FILE_APPEND
1561                 modestring = "ab";
1562                 break;
1563         case 2: // FILE_WRITE
1564                 modestring = "wb";
1565                 break;
1566         default:
1567                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1568                 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1569                 return;
1570         }
1571         filename = PRVM_G_STRING(OFS_PARM0);
1572
1573         prog->openfiles[filenum] = FS_Open(va("data/%s", filename), modestring, false, false);
1574         if (prog->openfiles[filenum] == NULL && mode == 0)
1575                 prog->openfiles[filenum] = FS_Open(va("%s", filename), modestring, false, false);
1576
1577         if (prog->openfiles[filenum] == NULL)
1578         {
1579                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1580                 if (developer.integer >= 10)
1581                         VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1582         }
1583         else
1584         {
1585                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1586                 if (developer.integer >= 10)
1587                         VM_Warning("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1588         }
1589 }
1590
1591 /*
1592 =========
1593 VM_fclose
1594
1595 fclose(float fhandle)
1596 =========
1597 */
1598 //void(float fhandle) fclose = #111; // closes a file
1599 void VM_fclose(void)
1600 {
1601         int filenum;
1602
1603         VM_SAFEPARMCOUNT(1,VM_fclose);
1604
1605         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1606         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1607         {
1608                 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1609                 return;
1610         }
1611         if (prog->openfiles[filenum] == NULL)
1612         {
1613                 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1614                 return;
1615         }
1616         FS_Close(prog->openfiles[filenum]);
1617         prog->openfiles[filenum] = NULL;
1618         if (developer.integer >= 10)
1619                 VM_Warning("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1620 }
1621
1622 /*
1623 =========
1624 VM_fgets
1625
1626 string  fgets(float fhandle)
1627 =========
1628 */
1629 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1630 void VM_fgets(void)
1631 {
1632         int c, end;
1633         static char string[VM_STRINGTEMP_LENGTH];
1634         int filenum;
1635
1636         VM_SAFEPARMCOUNT(1,VM_fgets);
1637
1638         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1639         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1640         {
1641                 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1642                 return;
1643         }
1644         if (prog->openfiles[filenum] == NULL)
1645         {
1646                 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1647                 return;
1648         }
1649         end = 0;
1650         for (;;)
1651         {
1652                 c = FS_Getc(prog->openfiles[filenum]);
1653                 if (c == '\r' || c == '\n' || c < 0)
1654                         break;
1655                 if (end < VM_STRINGTEMP_LENGTH - 1)
1656                         string[end++] = c;
1657         }
1658         string[end] = 0;
1659         // remove \n following \r
1660         if (c == '\r')
1661         {
1662                 c = FS_Getc(prog->openfiles[filenum]);
1663                 if (c != '\n')
1664                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1665         }
1666         if (developer.integer >= 100)
1667                 Con_Printf("fgets: %s: %s\n", PRVM_NAME, string);
1668         if (c >= 0 || end)
1669                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(string);
1670         else
1671                 PRVM_G_INT(OFS_RETURN) = 0;
1672 }
1673
1674 /*
1675 =========
1676 VM_fputs
1677
1678 fputs(float fhandle, string s)
1679 =========
1680 */
1681 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1682 void VM_fputs(void)
1683 {
1684         int stringlength;
1685         char string[VM_STRINGTEMP_LENGTH];
1686         int filenum;
1687
1688         VM_SAFEPARMCOUNT(2,VM_fputs);
1689
1690         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1691         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1692         {
1693                 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1694                 return;
1695         }
1696         if (prog->openfiles[filenum] == NULL)
1697         {
1698                 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1699                 return;
1700         }
1701         VM_VarString(1, string, sizeof(string));
1702         if ((stringlength = (int)strlen(string)))
1703                 FS_Write(prog->openfiles[filenum], string, stringlength);
1704         if (developer.integer >= 100)
1705                 Con_Printf("fputs: %s: %s\n", PRVM_NAME, string);
1706 }
1707
1708 /*
1709 =========
1710 VM_strlen
1711
1712 float   strlen(string s)
1713 =========
1714 */
1715 //float(string s) strlen = #114; // returns how many characters are in a string
1716 void VM_strlen(void)
1717 {
1718         const char *s;
1719
1720         VM_SAFEPARMCOUNT(1,VM_strlen);
1721
1722         s = PRVM_G_STRING(OFS_PARM0);
1723         if (s)
1724                 PRVM_G_FLOAT(OFS_RETURN) = strlen(s);
1725         else
1726                 PRVM_G_FLOAT(OFS_RETURN) = 0;
1727 }
1728
1729 /*
1730 =========
1731 VM_strcat
1732
1733 string strcat(string,string,...[string])
1734 =========
1735 */
1736 //string(string s1, string s2) strcat = #115;
1737 // concatenates two strings (for example "abc", "def" would return "abcdef")
1738 // and returns as a tempstring
1739 void VM_strcat(void)
1740 {
1741         char *s;
1742
1743         if(prog->argc < 1)
1744                 PRVM_ERROR("VM_strcat wrong parameter count (min. 1 expected ) !");
1745
1746         s = VM_GetTempString();
1747         VM_VarString(0, s, VM_STRINGTEMP_LENGTH);
1748         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(s);
1749 }
1750
1751 /*
1752 =========
1753 VM_substring
1754
1755 string  substring(string s, float start, float length)
1756 =========
1757 */
1758 // string(string s, float start, float length) substring = #116;
1759 // returns a section of a string as a tempstring
1760 void VM_substring(void)
1761 {
1762         int i, start, length;
1763         const char *s;
1764         char *string;
1765
1766         VM_SAFEPARMCOUNT(3,VM_substring);
1767
1768         string = VM_GetTempString();
1769         s = PRVM_G_STRING(OFS_PARM0);
1770         start = (int)PRVM_G_FLOAT(OFS_PARM1);
1771         length = (int)PRVM_G_FLOAT(OFS_PARM2);
1772         if (!s)
1773                 s = "";
1774         for (i = 0;i < start && *s;i++, s++);
1775         for (i = 0;i < VM_STRINGTEMP_LENGTH - 1 && *s && i < length;i++, s++)
1776                 string[i] = *s;
1777         string[i] = 0;
1778         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(string);
1779 }
1780
1781 /*
1782 =========
1783 VM_stov
1784
1785 vector  stov(string s)
1786 =========
1787 */
1788 //vector(string s) stov = #117; // returns vector value from a string
1789 void VM_stov(void)
1790 {
1791         char string[VM_STRINGTEMP_LENGTH];
1792
1793         VM_SAFEPARMCOUNT(1,VM_stov);
1794
1795         VM_VarString(0, string, sizeof(string));
1796         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
1797 }
1798
1799 /*
1800 =========
1801 VM_strzone
1802
1803 string  strzone(string s)
1804 =========
1805 */
1806 //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)
1807 void VM_strzone(void)
1808 {
1809         char *out;
1810         char string[VM_STRINGTEMP_LENGTH];
1811         size_t alloclen;
1812
1813         VM_SAFEPARMCOUNT(1,VM_strzone);
1814
1815         VM_VarString(0, string, sizeof(string));
1816         alloclen = strlen(string) + 1;
1817         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
1818         memcpy(out, string, alloclen);
1819 }
1820
1821 /*
1822 =========
1823 VM_strunzone
1824
1825 strunzone(string s)
1826 =========
1827 */
1828 //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!!!)
1829 void VM_strunzone(void)
1830 {
1831         VM_SAFEPARMCOUNT(1,VM_strunzone);
1832         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
1833 }
1834
1835 /*
1836 =========
1837 VM_command (used by client and menu)
1838
1839 clientcommand(float client, string s) (for client and menu)
1840 =========
1841 */
1842 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
1843 //this function originally written by KrimZon, made shorter by LordHavoc
1844 void VM_clcommand (void)
1845 {
1846         client_t *temp_client;
1847         int i;
1848
1849         VM_SAFEPARMCOUNT(2,VM_clcommand);
1850
1851         i = (int)PRVM_G_FLOAT(OFS_PARM0);
1852         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
1853         {
1854                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
1855                 return;
1856         }
1857
1858         temp_client = host_client;
1859         host_client = svs.clients + i;
1860         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
1861         host_client = temp_client;
1862 }
1863
1864
1865 /*
1866 =========
1867 VM_tokenize
1868
1869 float tokenize(string s)
1870 =========
1871 */
1872 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
1873 //this function originally written by KrimZon, made shorter by LordHavoc
1874 //20040203: rewritten by LordHavoc (no longer uses allocations)
1875 int num_tokens = 0;
1876 char *tokens[256], tokenbuf[MAX_INPUTLINE];
1877 void VM_tokenize (void)
1878 {
1879         size_t pos;
1880         const char *p;
1881
1882         VM_SAFEPARMCOUNT(1,VM_tokenize);
1883
1884         p = PRVM_G_STRING(OFS_PARM0);
1885
1886         num_tokens = 0;
1887         pos = 0;
1888         while(COM_ParseToken(&p, false))
1889         {
1890                 size_t tokenlen;
1891                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
1892                         break;
1893                 tokenlen = strlen(com_token) + 1;
1894                 if (pos + tokenlen > sizeof(tokenbuf))
1895                         break;
1896                 tokens[num_tokens++] = tokenbuf + pos;
1897                 memcpy(tokenbuf + pos, com_token, tokenlen);
1898                 pos += tokenlen;
1899         }
1900
1901         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
1902 }
1903
1904 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
1905 //this function originally written by KrimZon, made shorter by LordHavoc
1906 void VM_argv (void)
1907 {
1908         int token_num;
1909
1910         VM_SAFEPARMCOUNT(1,VM_argv);
1911
1912         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
1913
1914         if (token_num >= 0 && token_num < num_tokens)
1915                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tokens[token_num]);
1916         else
1917                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(NULL);
1918 }
1919
1920 /*
1921 //void(entity e, entity tagentity, string tagname) setattachment = #443; // attachs e to a tag on tagentity (note: use "" to attach to entity origin/angles instead of a tag)
1922 void PF_setattachment (void)
1923 {
1924         prvm_edict_t *e = PRVM_G_EDICT(OFS_PARM0);
1925         prvm_edict_t *tagentity = PRVM_G_EDICT(OFS_PARM1);
1926         char *tagname = PRVM_G_STRING(OFS_PARM2);
1927         prvm_eval_t *v;
1928         int i, modelindex;
1929         model_t *model;
1930
1931         if (tagentity == NULL)
1932                 tagentity = prog->edicts;
1933
1934         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_entity);
1935         if (v)
1936                 fields.server->edict = PRVM_EDICT_TO_PROG(tagentity);
1937
1938         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_index);
1939         if (v)
1940                 fields.server->_float = 0;
1941         if (tagentity != NULL && tagentity != prog->edicts && tagname && tagname[0])
1942         {
1943                 modelindex = (int)tagentity->fields.server->modelindex;
1944                 if (modelindex >= 0 && modelindex < MAX_MODELS)
1945                 {
1946                         model = sv.models[modelindex];
1947                         if (model->data_overridetagnamesforskin && (unsigned int)tagentity->fields.server->skin < (unsigned int)model->numskins && model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].num_overridetagnames)
1948                                 for (i = 0;i < model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].num_overridetagnames;i++)
1949                                         if (!strcmp(tagname, model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].data_overridetagnames[i].name))
1950                                                 fields.server->_float = i + 1;
1951                         // FIXME: use a model function to get tag info (need to handle skeletal)
1952                         if (fields.server->_float == 0 && model->num_tags)
1953                                 for (i = 0;i < model->num_tags;i++)
1954                                         if (!strcmp(tagname, model->data_tags[i].name))
1955                                                 fields.server->_float = i + 1;
1956                         if (fields.server->_float == 0)
1957                                 Con_DPrintf("setattachment(edict %i, edict %i, string \"%s\"): tried to find tag named \"%s\" on entity %i (model \"%s\") but could not find it\n", PRVM_NUM_FOR_EDICT(e), PRVM_NUM_FOR_EDICT(tagentity), tagname, tagname, PRVM_NUM_FOR_EDICT(tagentity), model->name);
1958                 }
1959                 else
1960                         Con_DPrintf("setattachment(edict %i, edict %i, string \"%s\"): tried to find tag named \"%s\" on entity %i but it has no model\n", PRVM_NUM_FOR_EDICT(e), PRVM_NUM_FOR_EDICT(tagentity), tagname, tagname, PRVM_NUM_FOR_EDICT(tagentity));
1961         }
1962 }*/
1963
1964 /*
1965 =========
1966 VM_isserver
1967
1968 float   isserver()
1969 =========
1970 */
1971 void VM_isserver(void)
1972 {
1973         VM_SAFEPARMCOUNT(0,VM_serverstate);
1974
1975         PRVM_G_FLOAT(OFS_RETURN) = sv.active;
1976 }
1977
1978 /*
1979 =========
1980 VM_clientcount
1981
1982 float   clientcount()
1983 =========
1984 */
1985 void VM_clientcount(void)
1986 {
1987         VM_SAFEPARMCOUNT(0,VM_clientcount);
1988
1989         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
1990 }
1991
1992 /*
1993 =========
1994 VM_clientstate
1995
1996 float   clientstate()
1997 =========
1998 */
1999 void VM_clientstate(void)
2000 {
2001         VM_SAFEPARMCOUNT(0,VM_clientstate);
2002
2003         PRVM_G_FLOAT(OFS_RETURN) = cls.state;
2004 }
2005
2006 /*
2007 =========
2008 VM_getostype
2009
2010 float   getostype(void)
2011 =========
2012 */ // not used at the moment -> not included in the common list
2013 void VM_getostype(void)
2014 {
2015         VM_SAFEPARMCOUNT(0,VM_getostype);
2016
2017         /*
2018         OS_WINDOWS
2019         OS_LINUX
2020         OS_MAC - not supported
2021         */
2022
2023 #ifdef WIN32
2024         PRVM_G_FLOAT(OFS_RETURN) = 0;
2025 #elif defined(MACOSX)
2026         PRVM_G_FLOAT(OFS_RETURN) = 2;
2027 #else
2028         PRVM_G_FLOAT(OFS_RETURN) = 1;
2029 #endif
2030 }
2031
2032 /*
2033 =========
2034 VM_getmousepos
2035
2036 vector  getmousepos()
2037 =========
2038 */
2039 void VM_getmousepos(void)
2040 {
2041
2042         VM_SAFEPARMCOUNT(0,VM_getmousepos);
2043
2044         PRVM_G_VECTOR(OFS_RETURN)[0] = in_mouse_x * vid_conwidth.integer / vid.width;
2045         PRVM_G_VECTOR(OFS_RETURN)[1] = in_mouse_y * vid_conheight.integer / vid.height;
2046         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2047 }
2048
2049 /*
2050 =========
2051 VM_gettime
2052
2053 float   gettime(void)
2054 =========
2055 */
2056 void VM_gettime(void)
2057 {
2058         VM_SAFEPARMCOUNT(0,VM_gettime);
2059
2060         PRVM_G_FLOAT(OFS_RETURN) = (float) *prog->time;
2061 }
2062
2063 /*
2064 =========
2065 VM_loadfromdata
2066
2067 loadfromdata(string data)
2068 =========
2069 */
2070 void VM_loadfromdata(void)
2071 {
2072         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2073
2074         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2075 }
2076
2077 /*
2078 ========================
2079 VM_parseentitydata
2080
2081 parseentitydata(entity ent, string data)
2082 ========================
2083 */
2084 void VM_parseentitydata(void)
2085 {
2086         prvm_edict_t *ent;
2087         const char *data;
2088
2089         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2090
2091     // get edict and test it
2092         ent = PRVM_G_EDICT(OFS_PARM0);
2093         if (ent->priv.required->free)
2094                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2095
2096         data = PRVM_G_STRING(OFS_PARM1);
2097
2098     // parse the opening brace
2099         if (!COM_ParseTokenConsole(&data) || com_token[0] != '{' )
2100                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2101
2102         PRVM_ED_ParseEdict (data, ent);
2103 }
2104
2105 /*
2106 =========
2107 VM_loadfromfile
2108
2109 loadfromfile(string file)
2110 =========
2111 */
2112 void VM_loadfromfile(void)
2113 {
2114         const char *filename;
2115         char *data;
2116
2117         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
2118
2119         filename = PRVM_G_STRING(OFS_PARM0);
2120         // .. is parent directory on many platforms
2121         // / is parent directory on Amiga
2122         // : is root of drive on Amiga (also used as a directory separator on Mac, but / works there too, so that's a bad idea)
2123         // \ is a windows-ism (so it's naughty to use it, / works on all platforms)
2124         if ((filename[0] == '.' && filename[1] == '.') || filename[0] == '/' || strrchr(filename, ':') || strrchr(filename, '\\'))
2125         {
2126                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2127                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
2128                 return;
2129         }
2130
2131         // not conform with VM_fopen
2132         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
2133         if (data == NULL)
2134                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2135
2136         PRVM_ED_LoadFromFile(data);
2137
2138         if(data)
2139                 Mem_Free(data);
2140 }
2141
2142
2143 /*
2144 =========
2145 VM_modulo
2146
2147 float   mod(float val, float m)
2148 =========
2149 */
2150 void VM_modulo(void)
2151 {
2152         int val, m;
2153         VM_SAFEPARMCOUNT(2,VM_module);
2154
2155         val = (int) PRVM_G_FLOAT(OFS_PARM0);
2156         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
2157
2158         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
2159 }
2160
2161 void VM_Search_Init(void)
2162 {
2163         int i;
2164         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
2165                 prog->opensearches[i] = NULL;
2166 }
2167
2168 void VM_Search_Reset(void)
2169 {
2170         int i;
2171         // reset the fssearch list
2172         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
2173         {
2174                 if(prog->opensearches[i])
2175                         FS_FreeSearch(prog->opensearches[i]);
2176                 prog->opensearches[i] = NULL;
2177         }
2178 }
2179
2180 /*
2181 =========
2182 VM_search_begin
2183
2184 float search_begin(string pattern, float caseinsensitive, float quiet)
2185 =========
2186 */
2187 void VM_search_begin(void)
2188 {
2189         int handle;
2190         const char *pattern;
2191         int caseinsens, quiet;
2192
2193         VM_SAFEPARMCOUNT(3, VM_search_begin);
2194
2195         pattern = PRVM_G_STRING(OFS_PARM0);
2196
2197         VM_CheckEmptyString(pattern);
2198
2199         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
2200         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
2201
2202         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
2203                 if(!prog->opensearches[handle])
2204                         break;
2205
2206         if(handle >= PRVM_MAX_OPENSEARCHES)
2207         {
2208                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2209                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
2210                 return;
2211         }
2212
2213         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
2214                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2215         else
2216                 PRVM_G_FLOAT(OFS_RETURN) = handle;
2217 }
2218
2219 /*
2220 =========
2221 VM_search_end
2222
2223 void    search_end(float handle)
2224 =========
2225 */
2226 void VM_search_end(void)
2227 {
2228         int handle;
2229         VM_SAFEPARMCOUNT(1, VM_search_end);
2230
2231         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2232
2233         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2234         {
2235                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
2236                 return;
2237         }
2238         if(prog->opensearches[handle] == NULL)
2239         {
2240                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
2241                 return;
2242         }
2243
2244         FS_FreeSearch(prog->opensearches[handle]);
2245         prog->opensearches[handle] = NULL;
2246 }
2247
2248 /*
2249 =========
2250 VM_search_getsize
2251
2252 float   search_getsize(float handle)
2253 =========
2254 */
2255 void VM_search_getsize(void)
2256 {
2257         int handle;
2258         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
2259
2260         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2261
2262         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2263         {
2264                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
2265                 return;
2266         }
2267         if(prog->opensearches[handle] == NULL)
2268         {
2269                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
2270                 return;
2271         }
2272
2273         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
2274 }
2275
2276 /*
2277 =========
2278 VM_search_getfilename
2279
2280 string  search_getfilename(float handle, float num)
2281 =========
2282 */
2283 void VM_search_getfilename(void)
2284 {
2285         int handle, filenum;
2286         char *tmp;
2287         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
2288
2289         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2290         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
2291
2292         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2293         {
2294                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
2295                 return;
2296         }
2297         if(prog->opensearches[handle] == NULL)
2298         {
2299                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
2300                 return;
2301         }
2302         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
2303         {
2304                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
2305                 return;
2306         }
2307
2308         tmp = VM_GetTempString();
2309         strlcpy(tmp, prog->opensearches[handle]->filenames[filenum], VM_STRINGTEMP_LENGTH);
2310
2311         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2312 }
2313
2314 /*
2315 =========
2316 VM_chr
2317
2318 string  chr(float ascii)
2319 =========
2320 */
2321 void VM_chr(void)
2322 {
2323         char *tmp;
2324         VM_SAFEPARMCOUNT(1, VM_chr);
2325
2326         tmp = VM_GetTempString();
2327         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
2328         tmp[1] = 0;
2329
2330         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2331 }
2332
2333 //=============================================================================
2334 // Draw builtins (client & menu)
2335
2336 /*
2337 =========
2338 VM_iscachedpic
2339
2340 float   iscachedpic(string pic)
2341 =========
2342 */
2343 void VM_iscachedpic(void)
2344 {
2345         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
2346
2347         // drawq hasnt such a function, thus always return true
2348         PRVM_G_FLOAT(OFS_RETURN) = false;
2349 }
2350
2351 /*
2352 =========
2353 VM_precache_pic
2354
2355 string  precache_pic(string pic)
2356 =========
2357 */
2358 void VM_precache_pic(void)
2359 {
2360         const char      *s;
2361
2362         VM_SAFEPARMCOUNT(1, VM_precache_pic);
2363
2364         s = PRVM_G_STRING(OFS_PARM0);
2365         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
2366
2367         if(!s)
2368                 PRVM_ERROR ("VM_precache_pic: %s: NULL", PRVM_NAME);
2369
2370         VM_CheckEmptyString (s);
2371
2372         // AK Draw_CachePic is supposed to always return a valid pointer
2373         if( Draw_CachePic(s, false)->tex == r_texture_notexture )
2374                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(NULL);
2375 }
2376
2377 /*
2378 =========
2379 VM_freepic
2380
2381 freepic(string s)
2382 =========
2383 */
2384 void VM_freepic(void)
2385 {
2386         const char *s;
2387
2388         VM_SAFEPARMCOUNT(1,VM_freepic);
2389
2390         s = PRVM_G_STRING(OFS_PARM0);
2391
2392         if(!s)
2393                 PRVM_ERROR ("VM_freepic: %s: NULL");
2394
2395         VM_CheckEmptyString (s);
2396
2397         Draw_FreePic(s);
2398 }
2399
2400 /*
2401 =========
2402 VM_drawcharacter
2403
2404 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
2405 =========
2406 */
2407 void VM_drawcharacter(void)
2408 {
2409         float *pos,*scale,*rgb;
2410         char   character;
2411         int flag;
2412         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
2413
2414         character = (char) PRVM_G_FLOAT(OFS_PARM1);
2415         if(character == 0)
2416         {
2417                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2418                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
2419                 return;
2420         }
2421
2422         pos = PRVM_G_VECTOR(OFS_PARM0);
2423         scale = PRVM_G_VECTOR(OFS_PARM2);
2424         rgb = PRVM_G_VECTOR(OFS_PARM3);
2425         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2426
2427         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2428         {
2429                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2430                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2431                 return;
2432         }
2433
2434         if(pos[2] || scale[2])
2435                 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")));
2436
2437         if(!scale[0] || !scale[1])
2438         {
2439                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2440                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2441                 return;
2442         }
2443
2444         DrawQ_String (pos[0], pos[1], &character, 1, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2445         PRVM_G_FLOAT(OFS_RETURN) = 1;
2446 }
2447
2448 /*
2449 =========
2450 VM_drawstring
2451
2452 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
2453 =========
2454 */
2455 void VM_drawstring(void)
2456 {
2457         float *pos,*scale,*rgb;
2458         const char  *string;
2459         int flag;
2460         VM_SAFEPARMCOUNT(6,VM_drawstring);
2461
2462         string = PRVM_G_STRING(OFS_PARM1);
2463         if(!string)
2464         {
2465                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2466                 VM_Warning("VM_drawstring: %s passed null string !\n",PRVM_NAME);
2467                 return;
2468         }
2469
2470         //VM_CheckEmptyString(string); Why should it be checked - perhaps the menu wants to support the precolored letters, too?
2471
2472         pos = PRVM_G_VECTOR(OFS_PARM0);
2473         scale = PRVM_G_VECTOR(OFS_PARM2);
2474         rgb = PRVM_G_VECTOR(OFS_PARM3);
2475         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2476
2477         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2478         {
2479                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2480                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2481                 return;
2482         }
2483
2484         if(!scale[0] || !scale[1])
2485         {
2486                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2487                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2488                 return;
2489         }
2490
2491         if(pos[2] || scale[2])
2492                 Con_Printf("VM_drawstring: z value%c from %s discarded\n",(pos[2] && scale[2]) ? 's' : 0,((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
2493
2494         DrawQ_String (pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2495         PRVM_G_FLOAT(OFS_RETURN) = 1;
2496 }
2497 /*
2498 =========
2499 VM_drawpic
2500
2501 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
2502 =========
2503 */
2504 void VM_drawpic(void)
2505 {
2506         const char *picname;
2507         float *size, *pos, *rgb;
2508         int flag;
2509
2510         VM_SAFEPARMCOUNT(6,VM_drawpic);
2511
2512         picname = PRVM_G_STRING(OFS_PARM1);
2513
2514         if(!picname)
2515         {
2516                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2517                 VM_Warning("VM_drawpic: %s passed null picture name !\n", PRVM_NAME);
2518                 return;
2519         }
2520
2521         VM_CheckEmptyString (picname);
2522
2523         // is pic cached ? no function yet for that
2524         if(!1)
2525         {
2526                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2527                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
2528                 return;
2529         }
2530
2531         pos = PRVM_G_VECTOR(OFS_PARM0);
2532         size = PRVM_G_VECTOR(OFS_PARM2);
2533         rgb = PRVM_G_VECTOR(OFS_PARM3);
2534         flag = (int) PRVM_G_FLOAT(OFS_PARM5);
2535
2536         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2537         {
2538                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2539                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2540                 return;
2541         }
2542
2543         if(pos[2] || size[2])
2544                 Con_Printf("VM_drawstring: z value%c from %s discarded\n",(pos[2] && size[2]) ? 's' : 0,((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
2545
2546         DrawQ_Pic(pos[0], pos[1], Draw_CachePic(picname, true), size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2547         PRVM_G_FLOAT(OFS_RETURN) = 1;
2548 }
2549
2550 /*
2551 =========
2552 VM_drawfill
2553
2554 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
2555 =========
2556 */
2557 void VM_drawfill(void)
2558 {
2559         float *size, *pos, *rgb;
2560         int flag;
2561
2562         VM_SAFEPARMCOUNT(5,VM_drawfill);
2563
2564
2565         pos = PRVM_G_VECTOR(OFS_PARM0);
2566         size = PRVM_G_VECTOR(OFS_PARM1);
2567         rgb = PRVM_G_VECTOR(OFS_PARM2);
2568         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
2569
2570         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2571         {
2572                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2573                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2574                 return;
2575         }
2576
2577         if(pos[2] || size[2])
2578                 Con_Printf("VM_drawstring: z value%c from %s discarded\n",(pos[2] && size[2]) ? 's' : 0,((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
2579
2580         DrawQ_Pic(pos[0], pos[1], NULL, size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
2581         PRVM_G_FLOAT(OFS_RETURN) = 1;
2582 }
2583
2584 /*
2585 =========
2586 VM_drawsetcliparea
2587
2588 drawsetcliparea(float x, float y, float width, float height)
2589 =========
2590 */
2591 void VM_drawsetcliparea(void)
2592 {
2593         float x,y,w,h;
2594         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
2595
2596         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
2597         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
2598         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
2599         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
2600
2601         DrawQ_SetClipArea(x, y, w, h);
2602 }
2603
2604 /*
2605 =========
2606 VM_drawresetcliparea
2607
2608 drawresetcliparea()
2609 =========
2610 */
2611 void VM_drawresetcliparea(void)
2612 {
2613         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
2614
2615         DrawQ_ResetClipArea();
2616 }
2617
2618 /*
2619 =========
2620 VM_getimagesize
2621
2622 vector  getimagesize(string pic)
2623 =========
2624 */
2625 void VM_getimagesize(void)
2626 {
2627         const char *p;
2628         cachepic_t *pic;
2629
2630         VM_SAFEPARMCOUNT(1,VM_getimagesize);
2631
2632         p = PRVM_G_STRING(OFS_PARM0);
2633
2634         if(!p)
2635                 PRVM_ERROR("VM_getimagepos: %s passed null picture name !", PRVM_NAME);
2636
2637         VM_CheckEmptyString (p);
2638
2639         pic = Draw_CachePic (p, false);
2640
2641         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
2642         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
2643         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2644 }
2645
2646 /*
2647 =========
2648 VM_keynumtostring
2649
2650 string keynumtostring(float keynum)
2651 =========
2652 */
2653 void VM_keynumtostring (void)
2654 {
2655         int keynum;
2656         char *tmp;
2657         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
2658
2659         keynum = (int)PRVM_G_FLOAT(OFS_PARM0);
2660
2661         tmp = VM_GetTempString();
2662
2663         strlcpy(tmp, Key_KeynumToString(keynum), VM_STRINGTEMP_LENGTH);
2664
2665         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2666 }
2667
2668 /*
2669 =========
2670 VM_stringtokeynum
2671
2672 float stringtokeynum(string key)
2673 =========
2674 */
2675 void VM_stringtokeynum (void)
2676 {
2677         const char *str;
2678         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
2679
2680         str = PRVM_G_STRING( OFS_PARM0 );
2681
2682         PRVM_G_INT(OFS_RETURN) = Key_StringToKeynum( str );
2683 }
2684
2685 // CL_Video interface functions
2686
2687 /*
2688 ========================
2689 VM_cin_open
2690
2691 float cin_open(string file, string name)
2692 ========================
2693 */
2694 void VM_cin_open( void )
2695 {
2696         const char *file;
2697         const char *name;
2698
2699         VM_SAFEPARMCOUNT( 2, VM_cin_open );
2700
2701         file = PRVM_G_STRING( OFS_PARM0 );
2702         name = PRVM_G_STRING( OFS_PARM1 );
2703
2704         VM_CheckEmptyString( file );
2705     VM_CheckEmptyString( name );
2706
2707         if( CL_OpenVideo( file, name, MENUOWNER ) )
2708                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
2709         else
2710                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2711 }
2712
2713 /*
2714 ========================
2715 VM_cin_close
2716
2717 void cin_close(string name)
2718 ========================
2719 */
2720 void VM_cin_close( void )
2721 {
2722         const char *name;
2723
2724         VM_SAFEPARMCOUNT( 1, VM_cin_close );
2725
2726         name = PRVM_G_STRING( OFS_PARM0 );
2727         VM_CheckEmptyString( name );
2728
2729         CL_CloseVideo( CL_GetVideoByName( name ) );
2730 }
2731
2732 /*
2733 ========================
2734 VM_cin_setstate
2735 void cin_setstate(string name, float type)
2736 ========================
2737 */
2738 void VM_cin_setstate( void )
2739 {
2740         const char *name;
2741         clvideostate_t  state;
2742         clvideo_t               *video;
2743
2744         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
2745
2746         name = PRVM_G_STRING( OFS_PARM0 );
2747         VM_CheckEmptyString( name );
2748
2749         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
2750
2751         video = CL_GetVideoByName( name );
2752         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
2753                 CL_SetVideoState( video, state );
2754 }
2755
2756 /*
2757 ========================
2758 VM_cin_getstate
2759
2760 float cin_getstate(string name)
2761 ========================
2762 */
2763 void VM_cin_getstate( void )
2764 {
2765         const char *name;
2766         clvideo_t               *video;
2767
2768         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
2769
2770         name = PRVM_G_STRING( OFS_PARM0 );
2771         VM_CheckEmptyString( name );
2772
2773         video = CL_GetVideoByName( name );
2774         if( video )
2775                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
2776         else
2777                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2778 }
2779
2780 /*
2781 ========================
2782 VM_cin_restart
2783
2784 void cin_restart(string name)
2785 ========================
2786 */
2787 void VM_cin_restart( void )
2788 {
2789         const char *name;
2790         clvideo_t               *video;
2791
2792         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
2793
2794         name = PRVM_G_STRING( OFS_PARM0 );
2795         VM_CheckEmptyString( name );
2796
2797         video = CL_GetVideoByName( name );
2798         if( video )
2799                 CL_RestartVideo( video );
2800 }
2801
2802 /*
2803 ==============
2804 VM_vectorvectors
2805
2806 Writes new values for v_forward, v_up, and v_right based on the given forward vector
2807 vectorvectors(vector, vector)
2808 ==============
2809 */
2810 void VM_vectorvectors (void)
2811 {
2812         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), prog->globals.server->v_forward);
2813         VectorVectors(prog->globals.server->v_forward, prog->globals.server->v_right, prog->globals.server->v_up);
2814 }
2815
2816 /*
2817 ========================
2818 VM_drawline
2819
2820 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
2821 ========================
2822 */
2823 void VM_drawline (void)
2824 {
2825         float   *c1, *c2, *rgb;
2826         float   alpha, width;
2827         unsigned char   flags;
2828
2829         VM_SAFEPARMCOUNT(6, VM_drawline);
2830         width   = PRVM_G_FLOAT(OFS_PARM0);
2831         c1              = PRVM_G_VECTOR(OFS_PARM1);
2832         c2              = PRVM_G_VECTOR(OFS_PARM2);
2833         rgb             = PRVM_G_VECTOR(OFS_PARM3);
2834         alpha   = PRVM_G_FLOAT(OFS_PARM4);
2835         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
2836         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
2837 }
2838
2839 //====================
2840 //QC POLYGON functions
2841 //====================
2842
2843 typedef struct
2844 {
2845         rtexture_t              *tex;
2846         float                   data[36];       //[515]: enough for polygons
2847         unsigned char                   flags;  //[515]: + VM_POLYGON_2D and VM_POLYGON_FL4V flags
2848 }vm_polygon_t;
2849
2850 //static float                  vm_polygon_linewidth = 1;
2851 static mempool_t                *vm_polygons_pool = NULL;
2852 static unsigned char                    vm_current_vertices = 0;
2853 static qboolean                 vm_polygons_initialized = false;
2854 static vm_polygon_t             *vm_polygons = NULL;
2855 static unsigned long    vm_polygons_num = 0, vm_drawpolygons_num = 0;   //[515]: ok long on 64bit ?
2856 static qboolean                 vm_polygonbegin = false;        //[515]: for "no-crap-on-the-screen" check
2857 #define VM_DEFPOLYNUM 64        //[515]: enough for default ?
2858
2859 #define VM_POLYGON_FL3V         16      //more than 2 vertices (used only for lines)
2860 #define VM_POLYGON_FLLINES      32
2861 #define VM_POLYGON_FL2D         64
2862 #define VM_POLYGON_FL4V         128     //4 vertices
2863
2864 void VM_InitPolygons (void)
2865 {
2866         vm_polygons_pool = Mem_AllocPool("VMPOLY", 0, NULL);
2867         vm_polygons = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2868         memset(vm_polygons, 0, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2869         vm_polygons_num = VM_DEFPOLYNUM;
2870         vm_drawpolygons_num = 0;
2871         vm_polygonbegin = false;
2872         vm_polygons_initialized = true;
2873 }
2874
2875 void VM_DrawPolygonCallback (const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2876 {
2877         int surfacelistindex;
2878         // LordHavoc: FIXME: this is stupid code
2879         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
2880         {
2881                 const vm_polygon_t      *p = &vm_polygons[surfacelist[surfacelistindex]];
2882                 int                                     flags = p->flags & 0x0f;
2883
2884                 if(flags == DRAWFLAG_ADDITIVE)
2885                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2886                 else if(flags == DRAWFLAG_MODULATE)
2887                         GL_BlendFunc(GL_DST_COLOR, GL_ZERO);
2888                 else if(flags == DRAWFLAG_2XMODULATE)
2889                         GL_BlendFunc(GL_DST_COLOR,GL_SRC_COLOR);
2890                 else
2891                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2892
2893                 R_Mesh_TexBind(0, R_GetTexture(p->tex));
2894
2895                 CHECKGLERROR
2896                 //[515]: is speed is max ?
2897                 if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
2898                 {
2899                         qglLineWidth(p->data[13]);CHECKGLERROR
2900                         qglBegin(GL_LINE_LOOP);
2901                                 qglTexCoord1f   (p->data[12]);
2902                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
2903                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
2904
2905                                 qglTexCoord1f   (p->data[14]);
2906                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
2907                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
2908
2909                                 if(p->flags & VM_POLYGON_FL3V)
2910                                 {
2911                                         qglTexCoord1f   (p->data[16]);
2912                                         qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
2913                                         qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
2914
2915                                         if(p->flags & VM_POLYGON_FL4V)
2916                                         {
2917                                                 qglTexCoord1f   (p->data[18]);
2918                                                 qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
2919                                                 qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
2920                                         }
2921                                 }
2922                         qglEnd();
2923                         CHECKGLERROR
2924                 }
2925                 else
2926                 {
2927                         qglBegin(GL_POLYGON);
2928                                 qglTexCoord2f   (p->data[12], p->data[13]);
2929                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
2930                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
2931
2932                                 qglTexCoord2f   (p->data[14], p->data[15]);
2933                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
2934                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
2935
2936                                 qglTexCoord2f   (p->data[16], p->data[17]);
2937                                 qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
2938                                 qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
2939
2940                                 if(p->flags & VM_POLYGON_FL4V)
2941                                 {
2942                                         qglTexCoord2f   (p->data[18], p->data[19]);
2943                                         qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
2944                                         qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
2945                                 }
2946                         qglEnd();
2947                         CHECKGLERROR
2948                 }
2949         }
2950 }
2951
2952 void VM_AddPolygonTo2DScene (vm_polygon_t *p)
2953 {
2954         drawqueuemesh_t mesh;
2955         static int              picelements[6] = {0, 1, 2, 0, 2, 3};
2956
2957         mesh.texture = p->tex;
2958         mesh.data_element3i = picelements;
2959         mesh.data_vertex3f = p->data;
2960         mesh.data_texcoord2f = p->data + 12;
2961         mesh.data_color4f = p->data + 20;
2962         if(p->flags & VM_POLYGON_FL4V)
2963         {
2964                 mesh.num_vertices = 4;
2965                 mesh.num_triangles = 2;
2966         }
2967         else
2968         {
2969                 mesh.num_vertices = 3;
2970                 mesh.num_triangles = 1;
2971         }
2972         if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
2973                 DrawQ_LineLoop (&mesh, (p->flags&0x0f));
2974         else
2975                 DrawQ_Mesh (&mesh, (p->flags&0x0f));
2976 }
2977
2978 //void(string texturename, float flag, float 2d, float lines) R_BeginPolygon
2979 void VM_R_PolygonBegin (void)
2980 {
2981         vm_polygon_t    *p;
2982         const char              *picname;
2983         if(prog->argc < 2)
2984                 VM_SAFEPARMCOUNT(2, VM_R_PolygonBegin);
2985
2986         if(!vm_polygons_initialized)
2987                 VM_InitPolygons();
2988         if(vm_polygonbegin)
2989         {
2990                 VM_Warning("VM_R_PolygonBegin: called twice without VM_R_PolygonEnd after first\n");
2991                 return;
2992         }
2993         if(vm_drawpolygons_num >= vm_polygons_num)
2994         {
2995                 p = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, 2 * vm_polygons_num * sizeof(vm_polygon_t));
2996                 memset(p, 0, 2 * vm_polygons_num * sizeof(vm_polygon_t));
2997                 memcpy(p, vm_polygons, vm_polygons_num * sizeof(vm_polygon_t));
2998                 Mem_Free(vm_polygons);
2999                 vm_polygons = p;
3000                 vm_polygons_num *= 2;
3001         }
3002         p = &vm_polygons[vm_drawpolygons_num];
3003         picname = PRVM_G_STRING(OFS_PARM0);
3004         if(picname[0])
3005                 p->tex = Draw_CachePic(picname, true)->tex;
3006         else
3007                 p->tex = r_texture_white;
3008         p->flags = (unsigned char)PRVM_G_FLOAT(OFS_PARM1);
3009         vm_current_vertices = 0;
3010         vm_polygonbegin = true;
3011         if(prog->argc >= 3)
3012         {
3013                 if(PRVM_G_FLOAT(OFS_PARM2))
3014                         p->flags |= VM_POLYGON_FL2D;
3015                 if(prog->argc >= 4 && PRVM_G_FLOAT(OFS_PARM3))
3016                 {
3017                         p->data[13] = PRVM_G_FLOAT(OFS_PARM3);  //[515]: linewidth
3018                         p->flags |= VM_POLYGON_FLLINES;
3019                 }
3020         }
3021 }
3022
3023 //void(vector org, vector texcoords, vector rgb, float alpha) R_PolygonVertex
3024 void VM_R_PolygonVertex (void)
3025 {
3026         float                   *coords, *tx, *rgb, alpha;
3027         vm_polygon_t    *p;
3028         VM_SAFEPARMCOUNT(4, VM_R_PolygonVertex);
3029
3030         if(!vm_polygonbegin)
3031         {
3032                 VM_Warning("VM_R_PolygonVertex: VM_R_PolygonBegin wasn't called\n");
3033                 return;
3034         }
3035         coords  = PRVM_G_VECTOR(OFS_PARM0);
3036         tx              = PRVM_G_VECTOR(OFS_PARM1);
3037         rgb             = PRVM_G_VECTOR(OFS_PARM2);
3038         alpha = PRVM_G_FLOAT(OFS_PARM3);
3039
3040         p = &vm_polygons[vm_drawpolygons_num];
3041         if(vm_current_vertices > 4)
3042         {
3043                 VM_Warning("VM_R_PolygonVertex: may have 4 vertices max\n");
3044                 return;
3045         }
3046
3047         p->data[vm_current_vertices*3]          = coords[0];
3048         p->data[1+vm_current_vertices*3]        = coords[1];
3049         p->data[2+vm_current_vertices*3]        = coords[2];
3050
3051         p->data[12+vm_current_vertices*2]       = tx[0];
3052         if(!(p->flags & VM_POLYGON_FLLINES))
3053                 p->data[13+vm_current_vertices*2]       = tx[1];
3054
3055         p->data[20+vm_current_vertices*4]       = rgb[0];
3056         p->data[21+vm_current_vertices*4]       = rgb[1];
3057         p->data[22+vm_current_vertices*4]       = rgb[2];
3058         p->data[23+vm_current_vertices*4]       = alpha;
3059
3060         vm_current_vertices++;
3061         if(vm_current_vertices == 4)
3062                 p->flags |= VM_POLYGON_FL4V;
3063         else
3064                 if(vm_current_vertices == 3)
3065                         p->flags |= VM_POLYGON_FL3V;
3066 }
3067
3068 //void() R_EndPolygon
3069 void VM_R_PolygonEnd (void)
3070 {
3071         if(!vm_polygonbegin)
3072         {
3073                 VM_Warning("VM_R_PolygonEnd: VM_R_PolygonBegin wasn't called\n");
3074                 return;
3075         }
3076         vm_polygonbegin = false;
3077         if(vm_current_vertices > 2 || (vm_current_vertices >= 2 && vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FLLINES))
3078         {
3079                 if(vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FL2D)    //[515]: don't use qcpolygons memory if 2D
3080                         VM_AddPolygonTo2DScene(&vm_polygons[vm_drawpolygons_num]);
3081                 else
3082                         vm_drawpolygons_num++;
3083         }
3084         else
3085                 VM_Warning("VM_R_PolygonEnd: %i vertices isn't a good choice\n", vm_current_vertices);
3086 }
3087
3088 void VM_AddPolygonsToMeshQueue (void)
3089 {
3090         unsigned int i;
3091         if(!vm_drawpolygons_num)
3092                 return;
3093         for(i = 0;i < vm_drawpolygons_num;i++)
3094                 VM_DrawPolygonCallback(NULL, NULL, i, NULL);
3095         vm_drawpolygons_num = 0;
3096 }
3097
3098
3099
3100
3101 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3102 void VM_bitshift (void)
3103 {
3104         int n1, n2;
3105         VM_SAFEPARMCOUNT(2, VM_bitshift);
3106
3107         n1 = (int)fabs((int)PRVM_G_FLOAT(OFS_PARM0));
3108         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
3109         if(!n1)
3110                 PRVM_G_FLOAT(OFS_RETURN) = n1;
3111         else
3112         if(n2 < 0)
3113                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3114         else
3115                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3116 }
3117
3118 ////////////////////////////////////////
3119 // AltString functions
3120 ////////////////////////////////////////
3121
3122 /*
3123 ========================
3124 VM_altstr_count
3125
3126 float altstr_count(string)
3127 ========================
3128 */
3129 void VM_altstr_count( void )
3130 {
3131         const char *altstr, *pos;
3132         int     count;
3133
3134         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3135
3136         altstr = PRVM_G_STRING( OFS_PARM0 );
3137         //VM_CheckEmptyString( altstr );
3138
3139         for( count = 0, pos = altstr ; *pos ; pos++ ) {
3140                 if( *pos == '\\' ) {
3141                         if( !*++pos ) {
3142                                 break;
3143                         }
3144                 } else if( *pos == '\'' ) {
3145                         count++;
3146                 }
3147         }
3148
3149         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
3150 }
3151
3152 /*
3153 ========================
3154 VM_altstr_prepare
3155
3156 string altstr_prepare(string)
3157 ========================
3158 */
3159 void VM_altstr_prepare( void )
3160 {
3161         char *outstr, *out;
3162         const char *instr, *in;
3163         int size;
3164
3165         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3166
3167         instr = PRVM_G_STRING( OFS_PARM0 );
3168         //VM_CheckEmptyString( instr );
3169         outstr = VM_GetTempString();
3170
3171         for( out = outstr, in = instr, size = VM_STRINGTEMP_LENGTH - 1 ; size && *in ; size--, in++, out++ )
3172                 if( *in == '\'' ) {
3173                         *out++ = '\\';
3174                         *out = '\'';
3175                         size--;
3176                 } else
3177                         *out = *in;
3178         *out = 0;
3179
3180         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3181 }
3182
3183 /*
3184 ========================
3185 VM_altstr_get
3186
3187 string altstr_get(string, float)
3188 ========================
3189 */
3190 void VM_altstr_get( void )
3191 {
3192         const char *altstr, *pos;
3193         char *outstr, *out;
3194         int count, size;
3195
3196         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3197
3198         altstr = PRVM_G_STRING( OFS_PARM0 );
3199         //VM_CheckEmptyString( altstr );
3200
3201         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3202         count = count * 2 + 1;
3203
3204         for( pos = altstr ; *pos && count ; pos++ )
3205                 if( *pos == '\\' ) {
3206                         if( !*++pos )
3207                                 break;
3208                 } else if( *pos == '\'' )
3209                         count--;
3210
3211         if( !*pos ) {
3212                 PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( NULL );
3213                 return;
3214         }
3215
3216     outstr = VM_GetTempString();
3217         for( out = outstr, size = VM_STRINGTEMP_LENGTH - 1 ; size && *pos ; size--, pos++, out++ )
3218                 if( *pos == '\\' ) {
3219                         if( !*++pos )
3220                                 break;
3221                         *out = *pos;
3222                         size--;
3223                 } else if( *pos == '\'' )
3224                         break;
3225                 else
3226                         *out = *pos;
3227
3228         *out = 0;
3229         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3230 }
3231
3232 /*
3233 ========================
3234 VM_altstr_set
3235
3236 string altstr_set(string altstr, float num, string set)
3237 ========================
3238 */
3239 void VM_altstr_set( void )
3240 {
3241     int num;
3242         const char *altstr, *str;
3243         const char *in;
3244         char *outstr, *out;
3245
3246         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3247
3248         altstr = PRVM_G_STRING( OFS_PARM0 );
3249         //VM_CheckEmptyString( altstr );
3250
3251         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3252
3253         str = PRVM_G_STRING( OFS_PARM2 );
3254         //VM_CheckEmptyString( str );
3255
3256         outstr = out = VM_GetTempString();
3257         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3258                 if( *in == '\\' ) {
3259                         if( !*++in ) {
3260                                 break;
3261                         }
3262                 } else if( *in == '\'' ) {
3263                         num--;
3264                 }
3265
3266         if( !in ) {
3267                 PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( altstr );
3268                 return;
3269         }
3270         // copy set in
3271         for( ; *str; *out++ = *str++ );
3272         // now jump over the old content
3273         for( ; *in ; in++ )
3274                 if( *in == '\'' || (*in == '\\' && !*++in) )
3275                         break;
3276
3277         if( !in ) {
3278                 PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( NULL );
3279                 return;
3280         }
3281
3282         strlcpy(out, in, VM_STRINGTEMP_LENGTH);
3283         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3284 }
3285
3286 /*
3287 ========================
3288 VM_altstr_ins
3289 insert after num
3290 string  altstr_ins(string altstr, float num, string set)
3291 ========================
3292 */
3293 void VM_altstr_ins(void)
3294 {
3295         int num;
3296         const char *setstr;
3297         const char *set;
3298         const char *instr;
3299         const char *in;
3300         char *outstr;
3301         char *out;
3302
3303         in = instr = PRVM_G_STRING( OFS_PARM0 );
3304         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3305         set = setstr = PRVM_G_STRING( OFS_PARM2 );
3306
3307         out = outstr = VM_GetTempString();
3308         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3309                 if( *in == '\\' ) {
3310                         if( !*++in ) {
3311                                 break;
3312                         }
3313                 } else if( *in == '\'' ) {
3314                         num--;
3315                 }
3316
3317         *out++ = '\'';
3318         for( ; *set ; *out++ = *set++ );
3319         *out++ = '\'';
3320
3321         strlcpy(out, in, VM_STRINGTEMP_LENGTH);
3322         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3323 }
3324
3325
3326 ////////////////////////////////////////
3327 // BufString functions
3328 ////////////////////////////////////////
3329 //[515]: string buffers support
3330 #define MAX_QCSTR_BUFFERS 128
3331 #define MAX_QCSTR_STRINGS 1024
3332
3333 typedef struct
3334 {
3335         int             num_strings;
3336         char    *strings[MAX_QCSTR_STRINGS];
3337 }qcstrbuffer_t;
3338
3339 static qcstrbuffer_t    *qcstringbuffers[MAX_QCSTR_BUFFERS];
3340 static int                              num_qcstringbuffers;
3341 static int                              buf_sortpower;
3342
3343 #define BUFSTR_BUFFER(a) (a>=MAX_QCSTR_BUFFERS) ? NULL : (qcstringbuffers[a])
3344 #define BUFSTR_ISFREE(a) (a<MAX_QCSTR_BUFFERS&&qcstringbuffers[a]&&qcstringbuffers[a]->num_strings<=0) ? 1 : 0
3345
3346 static int BufStr_FindFreeBuffer (void)
3347 {
3348         int     i;
3349         if(num_qcstringbuffers == MAX_QCSTR_BUFFERS)
3350                 return -1;
3351         for(i=0;i<MAX_QCSTR_BUFFERS;i++)
3352                 if(!qcstringbuffers[i])
3353                 {
3354                         qcstringbuffers[i] = (qcstrbuffer_t *)Z_Malloc(sizeof(qcstrbuffer_t));
3355                         memset(qcstringbuffers[i], 0, sizeof(qcstrbuffer_t));
3356                         return i;
3357                 }
3358         return -1;
3359 }
3360
3361 static void BufStr_ClearBuffer (int index)
3362 {
3363         qcstrbuffer_t   *b = qcstringbuffers[index];
3364         int                             i;
3365
3366         if(b)
3367         {
3368                 if(b->num_strings > 0)
3369                 {
3370                         for(i=0;i<b->num_strings;i++)
3371                                 if(b->strings[i])
3372                                         Z_Free(b->strings[i]);
3373                         num_qcstringbuffers--;
3374                 }
3375                 Z_Free(qcstringbuffers[index]);
3376                 qcstringbuffers[index] = NULL;
3377         }
3378 }
3379
3380 static int BufStr_FindFreeString (qcstrbuffer_t *b)
3381 {
3382         int                             i;
3383         for(i=0;i<b->num_strings;i++)
3384                 if(!b->strings[i] || !b->strings[i][0])
3385                         return i;
3386         if(i == MAX_QCSTR_STRINGS)      return -1;
3387         else                                            return i;
3388 }
3389
3390 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3391 {
3392         const char *a, *b;
3393         a = *((const char **) in1);
3394         b = *((const char **) in2);
3395         if(!a[0])       return 1;
3396         if(!b[0])       return -1;
3397         return strncmp(a, b, buf_sortpower);
3398 }
3399
3400 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3401 {
3402         const char *a, *b;
3403         a = *((const char **) in1);
3404         b = *((const char **) in2);
3405         if(!a[0])       return 1;
3406         if(!b[0])       return -1;
3407         return strncmp(b, a, buf_sortpower);
3408 }
3409
3410 #ifdef REMOVETHIS
3411 static void VM_BufStr_Init (void)
3412 {
3413         memset(qcstringbuffers, 0, sizeof(qcstringbuffers));
3414         num_qcstringbuffers = 0;
3415 }
3416
3417 static void VM_BufStr_ShutDown (void)
3418 {
3419         int i;
3420         for(i=0;i<MAX_QCSTR_BUFFERS && num_qcstringbuffers;i++)
3421                 BufStr_ClearBuffer(i);
3422 }
3423 #endif
3424
3425 /*
3426 ========================
3427 VM_buf_create
3428 creates new buffer, and returns it's index, returns -1 if failed
3429 float buf_create(void) = #460;
3430 ========================
3431 */
3432 void VM_buf_create (void)
3433 {
3434         int i;
3435         VM_SAFEPARMCOUNT(0, VM_buf_create);
3436         i = BufStr_FindFreeBuffer();
3437         if(i >= 0)
3438                 num_qcstringbuffers++;
3439         //else
3440                 //Con_Printf("VM_buf_create: buffers overflow in %s\n", PRVM_NAME);
3441         PRVM_G_FLOAT(OFS_RETURN) = i;
3442 }
3443
3444 /*
3445 ========================
3446 VM_buf_del
3447 deletes buffer and all strings in it
3448 void buf_del(float bufhandle) = #461;
3449 ========================
3450 */
3451 void VM_buf_del (void)
3452 {
3453         VM_SAFEPARMCOUNT(1, VM_buf_del);
3454         if(BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0)))
3455                 BufStr_ClearBuffer((int)PRVM_G_FLOAT(OFS_PARM0));
3456         else
3457         {
3458                 VM_Warning("VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3459                 return;
3460         }
3461 }
3462
3463 /*
3464 ========================
3465 VM_buf_getsize
3466 how many strings are stored in buffer
3467 float buf_getsize(float bufhandle) = #462;
3468 ========================
3469 */
3470 void VM_buf_getsize (void)
3471 {
3472         qcstrbuffer_t   *b;
3473         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
3474
3475         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3476         if(!b)
3477         {
3478                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3479                 VM_Warning("VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3480                 return;
3481         }
3482         else
3483                 PRVM_G_FLOAT(OFS_RETURN) = b->num_strings;
3484 }
3485
3486 /*
3487 ========================
3488 VM_buf_copy
3489 copy all content from one buffer to another, make sure it exists
3490 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
3491 ========================
3492 */
3493 void VM_buf_copy (void)
3494 {
3495         qcstrbuffer_t   *b1, *b2;
3496         int                             i;
3497         VM_SAFEPARMCOUNT(2, VM_buf_copy);
3498
3499         b1 = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3500         if(!b1)
3501         {
3502                 VM_Warning("VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3503                 return;
3504         }
3505         i = (int)PRVM_G_FLOAT(OFS_PARM1);
3506         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
3507         {
3508                 VM_Warning("VM_buf_copy: source == destination (%i) in %s\n", i, PRVM_NAME);
3509                 return;
3510         }
3511         b2 = BUFSTR_BUFFER(i);
3512         if(!b2)
3513         {
3514                 VM_Warning("VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
3515                 return;
3516         }
3517
3518         BufStr_ClearBuffer(i);
3519         qcstringbuffers[i] = (qcstrbuffer_t *)Z_Malloc(sizeof(qcstrbuffer_t));
3520         memset(qcstringbuffers[i], 0, sizeof(qcstrbuffer_t));
3521         b2->num_strings = b1->num_strings;
3522
3523         for(i=0;i<b1->num_strings;i++)
3524                 if(b1->strings[i] && b1->strings[i][0])
3525                 {
3526                         size_t stringlen;
3527                         stringlen = strlen(b1->strings[i]) + 1;
3528                         b2->strings[i] = (char *)Z_Malloc(stringlen);
3529                         if(!b2->strings[i])
3530                         {
3531                                 VM_Warning("VM_buf_copy: not enough memory for buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
3532                                 break;
3533                         }
3534                         memcpy(b2->strings[i], b1->strings[i], stringlen);
3535                 }
3536 }
3537
3538 /*
3539 ========================
3540 VM_buf_sort
3541 sort buffer by beginnings of strings (sortpower defaults it's lenght)
3542 "backward == TRUE" means that sorting goes upside-down
3543 void buf_sort(float bufhandle, float sortpower, float backward) = #464;
3544 ========================
3545 */
3546 void VM_buf_sort (void)
3547 {
3548         qcstrbuffer_t   *b;
3549         int                             i;
3550         VM_SAFEPARMCOUNT(3, VM_buf_sort);
3551
3552         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3553         if(!b)
3554         {
3555                 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3556                 return;
3557         }
3558         if(b->num_strings <= 0)
3559         {
3560                 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3561                 return;
3562         }
3563         buf_sortpower = (int)PRVM_G_FLOAT(OFS_PARM1);
3564         if(buf_sortpower <= 0)
3565                 buf_sortpower = 99999999;
3566
3567         if(!PRVM_G_FLOAT(OFS_PARM2))
3568                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsUP);
3569         else
3570                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
3571
3572         for(i=b->num_strings-1;i>=0;i--)        //[515]: delete empty lines
3573                 if(b->strings)
3574                 {
3575                         if(b->strings[i][0])
3576                                 break;
3577                         else
3578                         {
3579                                 Z_Free(b->strings[i]);
3580                                 --b->num_strings;
3581                                 b->strings[i] = NULL;
3582                         }
3583                 }
3584                 else
3585                         --b->num_strings;
3586 }
3587
3588 /*
3589 ========================
3590 VM_buf_implode
3591 concantenates all buffer string into one with "glue" separator and returns it as tempstring
3592 string buf_implode(float bufhandle, string glue) = #465;
3593 ========================
3594 */
3595 void VM_buf_implode (void)
3596 {
3597         qcstrbuffer_t   *b;
3598         char                    *k;
3599         const char              *sep;
3600         int                             i;
3601         size_t                  l;
3602         VM_SAFEPARMCOUNT(2, VM_buf_implode);
3603
3604         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3605         PRVM_G_INT(OFS_RETURN) = 0;
3606         if(!b)
3607         {
3608                 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3609                 return;
3610         }
3611         if(!b->num_strings)
3612                 return;
3613         sep = PRVM_G_STRING(OFS_PARM1);
3614         k = VM_GetTempString();
3615         k[0] = 0;
3616         for(l=i=0;i<b->num_strings;i++)
3617                 if(b->strings[i])
3618                 {
3619                         l += strlen(b->strings[i]);
3620                         if(l>=4095)
3621                                 break;
3622                         strlcat(k, b->strings[i], VM_STRINGTEMP_LENGTH);
3623                         if(sep && (i != b->num_strings-1))
3624                         {
3625                                 l += strlen(sep);
3626                                 if(l>=4095)
3627                                         break;
3628                                 strlcat(k, sep, VM_STRINGTEMP_LENGTH);
3629                         }
3630                 }
3631         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(k);
3632 }
3633
3634 /*
3635 ========================
3636 VM_bufstr_get
3637 get a string from buffer, returns direct pointer, dont str_unzone it!
3638 string bufstr_get(float bufhandle, float string_index) = #465;
3639 ========================
3640 */
3641 void VM_bufstr_get (void)
3642 {
3643         qcstrbuffer_t   *b;
3644         int                             strindex;
3645         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
3646
3647         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3648         if(!b)
3649         {
3650                 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3651                 return;
3652         }
3653         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3654         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3655         {
3656                 VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3657                 return;
3658         }
3659         PRVM_G_INT(OFS_RETURN) = 0;
3660         if(b->num_strings <= strindex)
3661                 return;
3662         if(b->strings[strindex])
3663                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(b->strings[strindex]);
3664 }
3665
3666 /*
3667 ========================
3668 VM_bufstr_set
3669 copies a string into selected slot of buffer
3670 void bufstr_set(float bufhandle, float string_index, string str) = #466;
3671 ========================
3672 */
3673 void VM_bufstr_set (void)
3674 {
3675         int                             bufindex, strindex;
3676         qcstrbuffer_t   *b;
3677         const char              *news;
3678         size_t                  alloclen;
3679
3680         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
3681
3682         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3683         b = BUFSTR_BUFFER(bufindex);
3684         if(!b)
3685         {
3686                 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3687                 return;
3688         }
3689         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3690         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3691         {
3692                 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3693                 return;
3694         }
3695         news = PRVM_G_STRING(OFS_PARM2);
3696         if(!news)
3697         {
3698                 VM_Warning("VM_bufstr_set: null string used in %s\n", PRVM_NAME);
3699                 return;
3700         }
3701         if(b->strings[strindex])
3702                 Z_Free(b->strings[strindex]);
3703         alloclen = strlen(news) + 1;
3704         b->strings[strindex] = (char *)Z_Malloc(alloclen);
3705         memcpy(b->strings[strindex], news, alloclen);
3706 }
3707
3708 /*
3709 ========================
3710 VM_bufstr_add
3711 adds string to buffer in nearest free slot and returns it
3712 "order == TRUE" means that string will be added after last "full" slot
3713 float bufstr_add(float bufhandle, string str, float order) = #467;
3714 ========================
3715 */
3716 void VM_bufstr_add (void)
3717 {
3718         int                             bufindex, order, strindex;
3719         qcstrbuffer_t   *b;
3720         const char              *string;
3721         size_t                  alloclen;
3722
3723         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
3724
3725         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3726         b = BUFSTR_BUFFER(bufindex);
3727         PRVM_G_FLOAT(OFS_RETURN) = -1;
3728         if(!b)
3729         {
3730                 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3731                 return;
3732         }
3733         string = PRVM_G_STRING(OFS_PARM1);
3734         if(!string)
3735         {
3736                 VM_Warning("VM_bufstr_add: null string used in %s\n", PRVM_NAME);
3737                 return;
3738         }
3739
3740         order = (int)PRVM_G_FLOAT(OFS_PARM2);
3741         if(order)
3742                 strindex = b->num_strings;
3743         else
3744         {
3745                 strindex = BufStr_FindFreeString(b);
3746                 if(strindex < 0)
3747                 {
3748                         VM_Warning("VM_bufstr_add: buffer %i has no free string slots in %s\n", bufindex, PRVM_NAME);
3749                         return;
3750                 }
3751         }
3752
3753         while(b->num_strings <= strindex)
3754         {
3755                 if(b->num_strings == MAX_QCSTR_STRINGS)
3756                 {
3757                         VM_Warning("VM_bufstr_add: buffer %i has no free string slots in %s\n", bufindex, PRVM_NAME);
3758                         return;
3759                 }
3760                 b->strings[b->num_strings] = NULL;
3761                 b->num_strings++;
3762         }
3763         if(b->strings[strindex])
3764                 Z_Free(b->strings[strindex]);
3765         alloclen = strlen(string) + 1;
3766         b->strings[strindex] = (char *)Z_Malloc(alloclen);
3767         memcpy(b->strings[strindex], string, alloclen);
3768         PRVM_G_FLOAT(OFS_RETURN) = strindex;
3769 }
3770
3771 /*
3772 ========================
3773 VM_bufstr_free