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