]> icculus.org git repositories - divverent/darkplaces.git/blob - prvm_cmds.c
CSQC fixes (less broken, still not spec compliant)
[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         strlcpy(out, cvar_string, VM_STRINGTEMP_LENGTH);
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         strlcpy(out, cvar_string, VM_STRINGTEMP_LENGTH);
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_ftoe
719
720 entity ftoe(float num)
721 ========================
722 */
723 void VM_ftoe(void)
724 {
725         int ent;
726         VM_SAFEPARMCOUNT(1, VM_ftoe);
727
728         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
729         if (ent < 0 || ent >= MAX_EDICTS || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
730                 ent = 0; // return world instead of a free or invalid entity
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                 if (developer.integer >= 1)
770                         VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
771         }
772         else if( ed->priv.required->free )
773         {
774                 if (developer.integer >= 1)
775                         VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
776         }
777         else
778                 PRVM_ED_Free (ed);
779 //      if (ed == prog->edicts)
780 //              PRVM_ERROR ("remove: tried to remove world");
781 //      if (PRVM_NUM_FOR_EDICT(ed) <= sv.maxclients)
782 //              Host_Error("remove: tried to remove a client");
783 }
784
785 /*
786 =========
787 VM_find
788
789 entity  find(entity start, .string field, string match)
790 =========
791 */
792
793 void VM_find (void)
794 {
795         int             e;
796         int             f;
797         const char      *s, *t;
798         prvm_edict_t    *ed;
799
800         VM_SAFEPARMCOUNT(3,VM_find);
801
802         e = PRVM_G_EDICTNUM(OFS_PARM0);
803         f = PRVM_G_INT(OFS_PARM1);
804         s = PRVM_G_STRING(OFS_PARM2);
805
806         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
807         // expects it to find all the monsters, so we must be careful to support
808         // searching for ""
809         if (!s)
810                 s = "";
811
812         for (e++ ; e < prog->num_edicts ; e++)
813         {
814                 prog->xfunction->builtinsprofile++;
815                 ed = PRVM_EDICT_NUM(e);
816                 if (ed->priv.required->free)
817                         continue;
818                 t = PRVM_E_STRING(ed,f);
819                 if (!t)
820                         t = "";
821                 if (!strcmp(t,s))
822                 {
823                         VM_RETURN_EDICT(ed);
824                         return;
825                 }
826         }
827
828         VM_RETURN_EDICT(prog->edicts);
829 }
830
831 /*
832 =========
833 VM_findfloat
834
835   entity        findfloat(entity start, .float field, float match)
836   entity        findentity(entity start, .entity field, entity match)
837 =========
838 */
839 // LordHavoc: added this for searching float, int, and entity reference fields
840 void VM_findfloat (void)
841 {
842         int             e;
843         int             f;
844         float   s;
845         prvm_edict_t    *ed;
846
847         VM_SAFEPARMCOUNT(3,VM_findfloat);
848
849         e = PRVM_G_EDICTNUM(OFS_PARM0);
850         f = PRVM_G_INT(OFS_PARM1);
851         s = PRVM_G_FLOAT(OFS_PARM2);
852
853         for (e++ ; e < prog->num_edicts ; e++)
854         {
855                 prog->xfunction->builtinsprofile++;
856                 ed = PRVM_EDICT_NUM(e);
857                 if (ed->priv.required->free)
858                         continue;
859                 if (PRVM_E_FLOAT(ed,f) == s)
860                 {
861                         VM_RETURN_EDICT(ed);
862                         return;
863                 }
864         }
865
866         VM_RETURN_EDICT(prog->edicts);
867 }
868
869 /*
870 =========
871 VM_findchain
872
873 entity  findchain(.string field, string match)
874 =========
875 */
876 // chained search for strings in entity fields
877 // entity(.string field, string match) findchain = #402;
878 void VM_findchain (void)
879 {
880         int             i;
881         int             f;
882         int             chain_of;
883         const char      *s, *t;
884         prvm_edict_t    *ent, *chain;
885
886         VM_SAFEPARMCOUNT(2,VM_findchain);
887
888         // is the same like !(prog->flag & PRVM_FE_CHAIN) - even if the operator precedence is another
889         if(!prog->flag & PRVM_FE_CHAIN)
890                 PRVM_ERROR("VM_findchain: %s doesnt have a chain field !", PRVM_NAME);
891
892         chain_of = PRVM_ED_FindField("chain")->ofs;
893
894         chain = prog->edicts;
895
896         f = PRVM_G_INT(OFS_PARM0);
897         s = PRVM_G_STRING(OFS_PARM1);
898
899         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
900         // expects it to find all the monsters, so we must be careful to support
901         // searching for ""
902         if (!s)
903                 s = "";
904
905         ent = PRVM_NEXT_EDICT(prog->edicts);
906         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
907         {
908                 prog->xfunction->builtinsprofile++;
909                 if (ent->priv.required->free)
910                         continue;
911                 t = PRVM_E_STRING(ent,f);
912                 if (!t)
913                         t = "";
914                 if (strcmp(t,s))
915                         continue;
916
917                 PRVM_E_INT(ent,chain_of) = PRVM_NUM_FOR_EDICT(chain);
918                 chain = ent;
919         }
920
921         VM_RETURN_EDICT(chain);
922 }
923
924 /*
925 =========
926 VM_findchainfloat
927
928 entity  findchainfloat(.string field, float match)
929 entity  findchainentity(.string field, entity match)
930 =========
931 */
932 // LordHavoc: chained search for float, int, and entity reference fields
933 // entity(.string field, float match) findchainfloat = #403;
934 void VM_findchainfloat (void)
935 {
936         int             i;
937         int             f;
938         int             chain_of;
939         float   s;
940         prvm_edict_t    *ent, *chain;
941
942         VM_SAFEPARMCOUNT(2, VM_findchainfloat);
943
944         if(!prog->flag & PRVM_FE_CHAIN)
945                 PRVM_ERROR("VM_findchainfloat: %s doesnt have a chain field !", PRVM_NAME);
946
947         chain_of = PRVM_ED_FindField("chain")->ofs;
948
949         chain = (prvm_edict_t *)prog->edicts;
950
951         f = PRVM_G_INT(OFS_PARM0);
952         s = PRVM_G_FLOAT(OFS_PARM1);
953
954         ent = PRVM_NEXT_EDICT(prog->edicts);
955         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
956         {
957                 prog->xfunction->builtinsprofile++;
958                 if (ent->priv.required->free)
959                         continue;
960                 if (PRVM_E_FLOAT(ent,f) != s)
961                         continue;
962
963                 PRVM_E_INT(ent,chain_of) = PRVM_EDICT_TO_PROG(chain);
964                 chain = ent;
965         }
966
967         VM_RETURN_EDICT(chain);
968 }
969
970 /*
971 ========================
972 VM_findflags
973
974 entity  findflags(entity start, .float field, float match)
975 ========================
976 */
977 // LordHavoc: search for flags in float fields
978 void VM_findflags (void)
979 {
980         int             e;
981         int             f;
982         int             s;
983         prvm_edict_t    *ed;
984
985         VM_SAFEPARMCOUNT(3, VM_findflags);
986
987
988         e = PRVM_G_EDICTNUM(OFS_PARM0);
989         f = PRVM_G_INT(OFS_PARM1);
990         s = (int)PRVM_G_FLOAT(OFS_PARM2);
991
992         for (e++ ; e < prog->num_edicts ; e++)
993         {
994                 prog->xfunction->builtinsprofile++;
995                 ed = PRVM_EDICT_NUM(e);
996                 if (ed->priv.required->free)
997                         continue;
998                 if (!PRVM_E_FLOAT(ed,f))
999                         continue;
1000                 if ((int)PRVM_E_FLOAT(ed,f) & s)
1001                 {
1002                         VM_RETURN_EDICT(ed);
1003                         return;
1004                 }
1005         }
1006
1007         VM_RETURN_EDICT(prog->edicts);
1008 }
1009
1010 /*
1011 ========================
1012 VM_findchainflags
1013
1014 entity  findchainflags(.float field, float match)
1015 ========================
1016 */
1017 // LordHavoc: chained search for flags in float fields
1018 void VM_findchainflags (void)
1019 {
1020         int             i;
1021         int             f;
1022         int             s;
1023         int             chain_of;
1024         prvm_edict_t    *ent, *chain;
1025
1026         VM_SAFEPARMCOUNT(2, VM_findchainflags);
1027
1028         if(!prog->flag & PRVM_FE_CHAIN)
1029                 PRVM_ERROR("VM_findchainflags: %s doesnt have a chain field !", PRVM_NAME);
1030
1031         chain_of = PRVM_ED_FindField("chain")->ofs;
1032
1033         chain = (prvm_edict_t *)prog->edicts;
1034
1035         f = PRVM_G_INT(OFS_PARM0);
1036         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1037
1038         ent = PRVM_NEXT_EDICT(prog->edicts);
1039         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1040         {
1041                 prog->xfunction->builtinsprofile++;
1042                 if (ent->priv.required->free)
1043                         continue;
1044                 if (!PRVM_E_FLOAT(ent,f))
1045                         continue;
1046                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1047                         continue;
1048
1049                 PRVM_E_INT(ent,chain_of) = PRVM_EDICT_TO_PROG(chain);
1050                 chain = ent;
1051         }
1052
1053         VM_RETURN_EDICT(chain);
1054 }
1055
1056 /*
1057 =========
1058 VM_coredump
1059
1060 coredump()
1061 =========
1062 */
1063 void VM_coredump (void)
1064 {
1065         VM_SAFEPARMCOUNT(0,VM_coredump);
1066
1067         Cbuf_AddText("prvm_edicts ");
1068         Cbuf_AddText(PRVM_NAME);
1069         Cbuf_AddText("\n");
1070 }
1071
1072 /*
1073 =========
1074 VM_stackdump
1075
1076 stackdump()
1077 =========
1078 */
1079 void PRVM_StackTrace(void);
1080 void VM_stackdump (void)
1081 {
1082         VM_SAFEPARMCOUNT(0, VM_stackdump);
1083
1084         PRVM_StackTrace();
1085 }
1086
1087 /*
1088 =========
1089 VM_crash
1090
1091 crash()
1092 =========
1093 */
1094
1095 void VM_crash(void)
1096 {
1097         VM_SAFEPARMCOUNT(0, VM_crash);
1098
1099         PRVM_ERROR("Crash called by %s",PRVM_NAME);
1100 }
1101
1102 /*
1103 =========
1104 VM_traceon
1105
1106 traceon()
1107 =========
1108 */
1109 void VM_traceon (void)
1110 {
1111         VM_SAFEPARMCOUNT(0,VM_traceon);
1112
1113         prog->trace = true;
1114 }
1115
1116 /*
1117 =========
1118 VM_traceoff
1119
1120 traceoff()
1121 =========
1122 */
1123 void VM_traceoff (void)
1124 {
1125         VM_SAFEPARMCOUNT(0,VM_traceoff);
1126
1127         prog->trace = false;
1128 }
1129
1130 /*
1131 =========
1132 VM_eprint
1133
1134 eprint(entity e)
1135 =========
1136 */
1137 void VM_eprint (void)
1138 {
1139         VM_SAFEPARMCOUNT(1,VM_eprint);
1140
1141         PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0));
1142 }
1143
1144 /*
1145 =========
1146 VM_rint
1147
1148 float   rint(float)
1149 =========
1150 */
1151 void VM_rint (void)
1152 {
1153         float f;
1154         VM_SAFEPARMCOUNT(1,VM_rint);
1155
1156         f = PRVM_G_FLOAT(OFS_PARM0);
1157         if (f > 0)
1158                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1159         else
1160                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1161 }
1162
1163 /*
1164 =========
1165 VM_floor
1166
1167 float   floor(float)
1168 =========
1169 */
1170 void VM_floor (void)
1171 {
1172         VM_SAFEPARMCOUNT(1,VM_floor);
1173
1174         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1175 }
1176
1177 /*
1178 =========
1179 VM_ceil
1180
1181 float   ceil(float)
1182 =========
1183 */
1184 void VM_ceil (void)
1185 {
1186         VM_SAFEPARMCOUNT(1,VM_ceil);
1187
1188         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1189 }
1190
1191
1192 /*
1193 =============
1194 VM_nextent
1195
1196 entity  nextent(entity)
1197 =============
1198 */
1199 void VM_nextent (void)
1200 {
1201         int             i;
1202         prvm_edict_t    *ent;
1203
1204         i = PRVM_G_EDICTNUM(OFS_PARM0);
1205         while (1)
1206         {
1207                 prog->xfunction->builtinsprofile++;
1208                 i++;
1209                 if (i == prog->num_edicts)
1210                 {
1211                         VM_RETURN_EDICT(prog->edicts);
1212                         return;
1213                 }
1214                 ent = PRVM_EDICT_NUM(i);
1215                 if (!ent->priv.required->free)
1216                 {
1217                         VM_RETURN_EDICT(ent);
1218                         return;
1219                 }
1220         }
1221 }
1222
1223 //=============================================================================
1224
1225 /*
1226 ==============
1227 VM_changelevel
1228 server and menu
1229
1230 changelevel(string map)
1231 ==============
1232 */
1233 void VM_changelevel (void)
1234 {
1235         const char      *s;
1236
1237         VM_SAFEPARMCOUNT(1, VM_changelevel);
1238
1239         if(!sv.active)
1240         {
1241                 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1242                 return;
1243         }
1244
1245 // make sure we don't issue two changelevels
1246         if (svs.changelevel_issued)
1247                 return;
1248         svs.changelevel_issued = true;
1249
1250         s = PRVM_G_STRING(OFS_PARM0);
1251         Cbuf_AddText (va("changelevel %s\n",s));
1252 }
1253
1254 /*
1255 =========
1256 VM_sin
1257
1258 float   sin(float)
1259 =========
1260 */
1261 void VM_sin (void)
1262 {
1263         VM_SAFEPARMCOUNT(1,VM_sin);
1264         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1265 }
1266
1267 /*
1268 =========
1269 VM_cos
1270 float   cos(float)
1271 =========
1272 */
1273 void VM_cos (void)
1274 {
1275         VM_SAFEPARMCOUNT(1,VM_cos);
1276         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1277 }
1278
1279 /*
1280 =========
1281 VM_sqrt
1282
1283 float   sqrt(float)
1284 =========
1285 */
1286 void VM_sqrt (void)
1287 {
1288         VM_SAFEPARMCOUNT(1,VM_sqrt);
1289         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1290 }
1291
1292 /*
1293 =================
1294 VM_randomvec
1295
1296 Returns a vector of length < 1 and > 0
1297
1298 vector randomvec()
1299 =================
1300 */
1301 void VM_randomvec (void)
1302 {
1303         vec3_t          temp;
1304         //float         length;
1305
1306         VM_SAFEPARMCOUNT(0, VM_randomvec);
1307
1308         //// WTF ??
1309         do
1310         {
1311                 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1312                 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1313                 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1314         }
1315         while (DotProduct(temp, temp) >= 1);
1316         VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1317
1318         /*
1319         temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1320         temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1321         temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1322         // length returned always > 0
1323         length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1324         VectorScale(temp,length, temp);*/
1325         //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1326 }
1327
1328 //=============================================================================
1329
1330 /*
1331 =========
1332 VM_registercvar
1333
1334 float   registercvar (string name, string value, float flags)
1335 =========
1336 */
1337 void VM_registercvar (void)
1338 {
1339         const char *name, *value;
1340         int     flags;
1341
1342         VM_SAFEPARMCOUNT(3,VM_registercvar);
1343
1344         name = PRVM_G_STRING(OFS_PARM0);
1345         value = PRVM_G_STRING(OFS_PARM1);
1346         flags = (int)PRVM_G_FLOAT(OFS_PARM2);
1347         PRVM_G_FLOAT(OFS_RETURN) = 0;
1348
1349         if(flags > CVAR_MAXFLAGSVAL)
1350                 return;
1351
1352 // first check to see if it has already been defined
1353         if (Cvar_FindVar (name))
1354                 return;
1355
1356 // check for overlap with a command
1357         if (Cmd_Exists (name))
1358         {
1359                 VM_Warning("VM_registercvar: %s is a command\n", name);
1360                 return;
1361         }
1362
1363         Cvar_Get(name, value, flags);
1364
1365         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1366 }
1367
1368 /*
1369 =================
1370 VM_min
1371
1372 returns the minimum of two supplied floats
1373
1374 float min(float a, float b, ...[float])
1375 =================
1376 */
1377 void VM_min (void)
1378 {
1379         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1380         if (prog->argc == 2)
1381                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1382         else if (prog->argc >= 3)
1383         {
1384                 int i;
1385                 float f = PRVM_G_FLOAT(OFS_PARM0);
1386                 for (i = 1;i < prog->argc;i++)
1387                         if (PRVM_G_FLOAT((OFS_PARM0+i*3)) < f)
1388                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1389                 PRVM_G_FLOAT(OFS_RETURN) = f;
1390         }
1391         else
1392                 PRVM_ERROR("VM_min: %s must supply at least 2 floats", PRVM_NAME);
1393 }
1394
1395 /*
1396 =================
1397 VM_max
1398
1399 returns the maximum of two supplied floats
1400
1401 float   max(float a, float b, ...[float])
1402 =================
1403 */
1404 void VM_max (void)
1405 {
1406         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1407         if (prog->argc == 2)
1408                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1409         else if (prog->argc >= 3)
1410         {
1411                 int i;
1412                 float f = PRVM_G_FLOAT(OFS_PARM0);
1413                 for (i = 1;i < prog->argc;i++)
1414                         if (PRVM_G_FLOAT((OFS_PARM0+i*3)) > f)
1415                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1416                 PRVM_G_FLOAT(OFS_RETURN) = f;
1417         }
1418         else
1419                 PRVM_ERROR("VM_max: %s must supply at least 2 floats", PRVM_NAME);
1420 }
1421
1422 /*
1423 =================
1424 VM_bound
1425
1426 returns number bounded by supplied range
1427
1428 float   bound(float min, float value, float max)
1429 =================
1430 */
1431 void VM_bound (void)
1432 {
1433         VM_SAFEPARMCOUNT(3,VM_bound);
1434         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1435 }
1436
1437 /*
1438 =================
1439 VM_pow
1440
1441 returns a raised to power b
1442
1443 float   pow(float a, float b)
1444 =================
1445 */
1446 void VM_pow (void)
1447 {
1448         VM_SAFEPARMCOUNT(2,VM_pow);
1449         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1450 }
1451
1452 /*
1453 =================
1454 VM_copyentity
1455
1456 copies data from one entity to another
1457
1458 copyentity(entity src, entity dst)
1459 =================
1460 */
1461 void VM_copyentity (void)
1462 {
1463         prvm_edict_t *in, *out;
1464         VM_SAFEPARMCOUNT(2,VM_copyentity);
1465         in = PRVM_G_EDICT(OFS_PARM0);
1466         out = PRVM_G_EDICT(OFS_PARM1);
1467         memcpy(out->fields.vp, in->fields.vp, prog->progs->entityfields * 4);
1468 }
1469
1470 /*
1471 =================
1472 VM_setcolor
1473
1474 sets the color of a client and broadcasts the update to all connected clients
1475
1476 setcolor(clientent, value)
1477 =================
1478 */
1479 /*void PF_setcolor (void)
1480 {
1481         client_t *client;
1482         int entnum, i;
1483         prvm_eval_t *val;
1484
1485         entnum = PRVM_G_EDICTNUM(OFS_PARM0);
1486         i = PRVM_G_FLOAT(OFS_PARM1);
1487
1488         if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active)
1489         {
1490                 Con_Print("tried to setcolor a non-client\n");
1491                 return;
1492         }
1493
1494         client = svs.clients + entnum-1;
1495         if ((val = PRVM_GETEDICTFIELDVALUE(client->edict, eval_clientcolors)))
1496                 val->_float = i;
1497         client->colors = i;
1498         client->old_colors = i;
1499         client->edict->fields.server->team = (i & 15) + 1;
1500
1501         MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
1502         MSG_WriteByte (&sv.reliable_datagram, entnum - 1);
1503         MSG_WriteByte (&sv.reliable_datagram, i);
1504 }*/
1505
1506 void VM_Files_Init(void)
1507 {
1508         memset(VM_FILES, 0, sizeof(qfile_t*[MAX_VMFILES]));
1509 }
1510
1511 void VM_Files_CloseAll(void)
1512 {
1513         int i;
1514         for (i = 0;i < MAX_VMFILES;i++)
1515         {
1516                 if (VM_FILES[i])
1517                         FS_Close(VM_FILES[i]);
1518                 //VM_FILES[i] = NULL;
1519         }
1520         memset(VM_FILES,0,sizeof(qfile_t*[MAX_VMFILES])); // this should be faster (is it ?)
1521 }
1522
1523 qfile_t *VM_GetFileHandle( int index )
1524 {
1525         if (index < 0 || index >= MAX_VMFILES)
1526         {
1527                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1528                 return NULL;
1529         }
1530         if (VM_FILES[index] == NULL)
1531         {
1532                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1533                 return NULL;
1534         }
1535         return VM_FILES[index];
1536 }
1537
1538 /*
1539 =========
1540 VM_fopen
1541
1542 float   fopen(string filename, float mode)
1543 =========
1544 */
1545 // float(string filename, float mode) fopen = #110;
1546 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1547 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1548 void VM_fopen(void)
1549 {
1550         int filenum, mode;
1551         const char *modestring, *filename;
1552
1553         VM_SAFEPARMCOUNT(2,VM_fopen);
1554
1555         for (filenum = 0;filenum < MAX_VMFILES;filenum++)
1556                 if (VM_FILES[filenum] == NULL)
1557                         break;
1558         if (filenum >= MAX_VMFILES)
1559         {
1560                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1561                 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, MAX_VMFILES);
1562                 return;
1563         }
1564         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1565         switch(mode)
1566         {
1567         case 0: // FILE_READ
1568                 modestring = "rb";
1569                 break;
1570         case 1: // FILE_APPEND
1571                 modestring = "ab";
1572                 break;
1573         case 2: // FILE_WRITE
1574                 modestring = "wb";
1575                 break;
1576         default:
1577                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1578                 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1579                 return;
1580         }
1581         filename = PRVM_G_STRING(OFS_PARM0);
1582
1583         VM_FILES[filenum] = FS_Open(va("data/%s", filename), modestring, false, false);
1584         if (VM_FILES[filenum] == NULL && mode == 0)
1585                 VM_FILES[filenum] = FS_Open(va("%s", filename), modestring, false, false);
1586
1587         if (VM_FILES[filenum] == NULL)
1588         {
1589                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1590                 if (developer.integer >= 10)
1591                         VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1592         }
1593         else
1594         {
1595                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1596                 if (developer.integer >= 10)
1597                         VM_Warning("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1598         }
1599 }
1600
1601 /*
1602 =========
1603 VM_fclose
1604
1605 fclose(float fhandle)
1606 =========
1607 */
1608 //void(float fhandle) fclose = #111; // closes a file
1609 void VM_fclose(void)
1610 {
1611         int filenum;
1612
1613         VM_SAFEPARMCOUNT(1,VM_fclose);
1614
1615         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1616         if (filenum < 0 || filenum >= MAX_VMFILES)
1617         {
1618                 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1619                 return;
1620         }
1621         if (VM_FILES[filenum] == NULL)
1622         {
1623                 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1624                 return;
1625         }
1626         FS_Close(VM_FILES[filenum]);
1627         VM_FILES[filenum] = NULL;
1628         if (developer.integer >= 10)
1629                 VM_Warning("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1630 }
1631
1632 /*
1633 =========
1634 VM_fgets
1635
1636 string  fgets(float fhandle)
1637 =========
1638 */
1639 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1640 void VM_fgets(void)
1641 {
1642         int c, end;
1643         static char string[VM_STRINGTEMP_LENGTH];
1644         int filenum;
1645
1646         VM_SAFEPARMCOUNT(1,VM_fgets);
1647
1648         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1649         if (filenum < 0 || filenum >= MAX_VMFILES)
1650         {
1651                 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1652                 return;
1653         }
1654         if (VM_FILES[filenum] == NULL)
1655         {
1656                 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1657                 return;
1658         }
1659         end = 0;
1660         for (;;)
1661         {
1662                 c = FS_Getc(VM_FILES[filenum]);
1663                 if (c == '\r' || c == '\n' || c < 0)
1664                         break;
1665                 if (end < VM_STRINGTEMP_LENGTH - 1)
1666                         string[end++] = c;
1667         }
1668         string[end] = 0;
1669         // remove \n following \r
1670         if (c == '\r')
1671         {
1672                 c = FS_Getc(VM_FILES[filenum]);
1673                 if (c != '\n')
1674                         FS_UnGetc(VM_FILES[filenum], (unsigned char)c);
1675         }
1676         if (developer.integer >= 100)
1677                 Con_Printf("fgets: %s: %s\n", PRVM_NAME, string);
1678         if (c >= 0 || end)
1679                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(string);
1680         else
1681                 PRVM_G_INT(OFS_RETURN) = 0;
1682 }
1683
1684 /*
1685 =========
1686 VM_fputs
1687
1688 fputs(float fhandle, string s)
1689 =========
1690 */
1691 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1692 void VM_fputs(void)
1693 {
1694         int stringlength;
1695         char string[VM_STRINGTEMP_LENGTH];
1696         int filenum;
1697
1698         VM_SAFEPARMCOUNT(2,VM_fputs);
1699
1700         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1701         if (filenum < 0 || filenum >= MAX_VMFILES)
1702         {
1703                 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1704                 return;
1705         }
1706         if (VM_FILES[filenum] == NULL)
1707         {
1708                 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1709                 return;
1710         }
1711         VM_VarString(1, string, sizeof(string));
1712         if ((stringlength = (int)strlen(string)))
1713                 FS_Write(VM_FILES[filenum], string, stringlength);
1714         if (developer.integer >= 100)
1715                 Con_Printf("fputs: %s: %s\n", PRVM_NAME, string);
1716 }
1717
1718 /*
1719 =========
1720 VM_strlen
1721
1722 float   strlen(string s)
1723 =========
1724 */
1725 //float(string s) strlen = #114; // returns how many characters are in a string
1726 void VM_strlen(void)
1727 {
1728         const char *s;
1729
1730         VM_SAFEPARMCOUNT(1,VM_strlen);
1731
1732         s = PRVM_G_STRING(OFS_PARM0);
1733         if (s)
1734                 PRVM_G_FLOAT(OFS_RETURN) = strlen(s);
1735         else
1736                 PRVM_G_FLOAT(OFS_RETURN) = 0;
1737 }
1738
1739 /*
1740 =========
1741 VM_strcat
1742
1743 string strcat(string,string,...[string])
1744 =========
1745 */
1746 //string(string s1, string s2) strcat = #115;
1747 // concatenates two strings (for example "abc", "def" would return "abcdef")
1748 // and returns as a tempstring
1749 void VM_strcat(void)
1750 {
1751         char *s;
1752
1753         if(prog->argc < 1)
1754                 PRVM_ERROR("VM_strcat wrong parameter count (min. 1 expected ) !");
1755
1756         s = VM_GetTempString();
1757         VM_VarString(0, s, VM_STRINGTEMP_LENGTH);
1758         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(s);
1759 }
1760
1761 /*
1762 =========
1763 VM_substring
1764
1765 string  substring(string s, float start, float length)
1766 =========
1767 */
1768 // string(string s, float start, float length) substring = #116;
1769 // returns a section of a string as a tempstring
1770 void VM_substring(void)
1771 {
1772         int i, start, length;
1773         const char *s;
1774         char *string;
1775
1776         VM_SAFEPARMCOUNT(3,VM_substring);
1777
1778         string = VM_GetTempString();
1779         s = PRVM_G_STRING(OFS_PARM0);
1780         start = (int)PRVM_G_FLOAT(OFS_PARM1);
1781         length = (int)PRVM_G_FLOAT(OFS_PARM2);
1782         if (!s)
1783                 s = "";
1784         for (i = 0;i < start && *s;i++, s++);
1785         for (i = 0;i < VM_STRINGTEMP_LENGTH - 1 && *s && i < length;i++, s++)
1786                 string[i] = *s;
1787         string[i] = 0;
1788         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(string);
1789 }
1790
1791 /*
1792 =========
1793 VM_stov
1794
1795 vector  stov(string s)
1796 =========
1797 */
1798 //vector(string s) stov = #117; // returns vector value from a string
1799 void VM_stov(void)
1800 {
1801         char string[VM_STRINGTEMP_LENGTH];
1802
1803         VM_SAFEPARMCOUNT(1,VM_stov);
1804
1805         VM_VarString(0, string, sizeof(string));
1806         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
1807 }
1808
1809 /*
1810 =========
1811 VM_strzone
1812
1813 string  strzone(string s)
1814 =========
1815 */
1816 //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)
1817 void VM_strzone(void)
1818 {
1819         char *out;
1820         char string[VM_STRINGTEMP_LENGTH];
1821         size_t alloclen;
1822
1823         VM_SAFEPARMCOUNT(1,VM_strzone);
1824
1825         VM_VarString(0, string, sizeof(string));
1826         alloclen = strlen(string) + 1;
1827         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
1828         memcpy(out, string, alloclen);
1829 }
1830
1831 /*
1832 =========
1833 VM_strunzone
1834
1835 strunzone(string s)
1836 =========
1837 */
1838 //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!!!)
1839 void VM_strunzone(void)
1840 {
1841         VM_SAFEPARMCOUNT(1,VM_strunzone);
1842         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
1843 }
1844
1845 /*
1846 =========
1847 VM_command (used by client and menu)
1848
1849 clientcommand(float client, string s) (for client and menu)
1850 =========
1851 */
1852 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
1853 //this function originally written by KrimZon, made shorter by LordHavoc
1854 void VM_clcommand (void)
1855 {
1856         client_t *temp_client;
1857         int i;
1858
1859         VM_SAFEPARMCOUNT(2,VM_clcommand);
1860
1861         i = (int)PRVM_G_FLOAT(OFS_PARM0);
1862         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
1863         {
1864                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
1865                 return;
1866         }
1867
1868         temp_client = host_client;
1869         host_client = svs.clients + i;
1870         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
1871         host_client = temp_client;
1872 }
1873
1874
1875 /*
1876 =========
1877 VM_tokenize
1878
1879 float tokenize(string s)
1880 =========
1881 */
1882 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
1883 //this function originally written by KrimZon, made shorter by LordHavoc
1884 //20040203: rewritten by LordHavoc (no longer uses allocations)
1885 int num_tokens = 0;
1886 char *tokens[256], tokenbuf[MAX_INPUTLINE];
1887 void VM_tokenize (void)
1888 {
1889         size_t pos;
1890         const char *p;
1891
1892         VM_SAFEPARMCOUNT(1,VM_tokenize);
1893
1894         p = PRVM_G_STRING(OFS_PARM0);
1895
1896         num_tokens = 0;
1897         pos = 0;
1898         while(COM_ParseToken(&p, false))
1899         {
1900                 size_t tokenlen;
1901                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
1902                         break;
1903                 tokenlen = strlen(com_token) + 1;
1904                 if (pos + tokenlen > sizeof(tokenbuf))
1905                         break;
1906                 tokens[num_tokens++] = tokenbuf + pos;
1907                 memcpy(tokenbuf + pos, com_token, tokenlen);
1908                 pos += tokenlen;
1909         }
1910
1911         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
1912 }
1913
1914 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
1915 //this function originally written by KrimZon, made shorter by LordHavoc
1916 void VM_argv (void)
1917 {
1918         int token_num;
1919
1920         VM_SAFEPARMCOUNT(1,VM_argv);
1921
1922         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
1923
1924         if (token_num >= 0 && token_num < num_tokens)
1925                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tokens[token_num]);
1926         else
1927                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(NULL);
1928 }
1929
1930 /*
1931 //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)
1932 void PF_setattachment (void)
1933 {
1934         prvm_edict_t *e = PRVM_G_EDICT(OFS_PARM0);
1935         prvm_edict_t *tagentity = PRVM_G_EDICT(OFS_PARM1);
1936         char *tagname = PRVM_G_STRING(OFS_PARM2);
1937         prvm_eval_t *v;
1938         int i, modelindex;
1939         model_t *model;
1940
1941         if (tagentity == NULL)
1942                 tagentity = prog->edicts;
1943
1944         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_entity);
1945         if (v)
1946                 fields.server->edict = PRVM_EDICT_TO_PROG(tagentity);
1947
1948         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_index);
1949         if (v)
1950                 fields.server->_float = 0;
1951         if (tagentity != NULL && tagentity != prog->edicts && tagname && tagname[0])
1952         {
1953                 modelindex = (int)tagentity->fields.server->modelindex;
1954                 if (modelindex >= 0 && modelindex < MAX_MODELS)
1955                 {
1956                         model = sv.models[modelindex];
1957                         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)
1958                                 for (i = 0;i < model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].num_overridetagnames;i++)
1959                                         if (!strcmp(tagname, model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].data_overridetagnames[i].name))
1960                                                 fields.server->_float = i + 1;
1961                         // FIXME: use a model function to get tag info (need to handle skeletal)
1962                         if (fields.server->_float == 0 && model->num_tags)
1963                                 for (i = 0;i < model->num_tags;i++)
1964                                         if (!strcmp(tagname, model->data_tags[i].name))
1965                                                 fields.server->_float = i + 1;
1966                         if (fields.server->_float == 0)
1967                                 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);
1968                 }
1969                 else
1970                         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));
1971         }
1972 }*/
1973
1974 /*
1975 =========
1976 VM_isserver
1977
1978 float   isserver()
1979 =========
1980 */
1981 void VM_isserver(void)
1982 {
1983         VM_SAFEPARMCOUNT(0,VM_serverstate);
1984
1985         PRVM_G_FLOAT(OFS_RETURN) = sv.active;
1986 }
1987
1988 /*
1989 =========
1990 VM_clientcount
1991
1992 float   clientcount()
1993 =========
1994 */
1995 void VM_clientcount(void)
1996 {
1997         VM_SAFEPARMCOUNT(0,VM_clientcount);
1998
1999         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2000 }
2001
2002 /*
2003 =========
2004 VM_clientstate
2005
2006 float   clientstate()
2007 =========
2008 */
2009 void VM_clientstate(void)
2010 {
2011         VM_SAFEPARMCOUNT(0,VM_clientstate);
2012
2013         PRVM_G_FLOAT(OFS_RETURN) = cls.state;
2014 }
2015
2016 /*
2017 =========
2018 VM_getostype
2019
2020 float   getostype(void)
2021 =========
2022 */ // not used at the moment -> not included in the common list
2023 void VM_getostype(void)
2024 {
2025         VM_SAFEPARMCOUNT(0,VM_getostype);
2026
2027         /*
2028         OS_WINDOWS
2029         OS_LINUX
2030         OS_MAC - not supported
2031         */
2032
2033 #ifdef WIN32
2034         PRVM_G_FLOAT(OFS_RETURN) = 0;
2035 #elif defined(MACOSX)
2036         PRVM_G_FLOAT(OFS_RETURN) = 2;
2037 #else
2038         PRVM_G_FLOAT(OFS_RETURN) = 1;
2039 #endif
2040 }
2041
2042 /*
2043 =========
2044 VM_getmousepos
2045
2046 vector  getmousepos()
2047 =========
2048 */
2049 void VM_getmousepos(void)
2050 {
2051
2052         VM_SAFEPARMCOUNT(0,VM_getmousepos);
2053
2054         PRVM_G_VECTOR(OFS_RETURN)[0] = in_mouse_x * vid_conwidth.integer / vid.width;
2055         PRVM_G_VECTOR(OFS_RETURN)[1] = in_mouse_y * vid_conheight.integer / vid.height;
2056         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2057 }
2058
2059 /*
2060 =========
2061 VM_gettime
2062
2063 float   gettime(void)
2064 =========
2065 */
2066 void VM_gettime(void)
2067 {
2068         VM_SAFEPARMCOUNT(0,VM_gettime);
2069
2070         PRVM_G_FLOAT(OFS_RETURN) = (float) *prog->time;
2071 }
2072
2073 /*
2074 =========
2075 VM_loadfromdata
2076
2077 loadfromdata(string data)
2078 =========
2079 */
2080 void VM_loadfromdata(void)
2081 {
2082         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2083
2084         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2085 }
2086
2087 /*
2088 ========================
2089 VM_parseentitydata
2090
2091 parseentitydata(entity ent, string data)
2092 ========================
2093 */
2094 void VM_parseentitydata(void)
2095 {
2096         prvm_edict_t *ent;
2097         const char *data;
2098
2099         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2100
2101     // get edict and test it
2102         ent = PRVM_G_EDICT(OFS_PARM0);
2103         if (ent->priv.required->free)
2104                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2105
2106         data = PRVM_G_STRING(OFS_PARM1);
2107
2108     // parse the opening brace
2109         if (!COM_ParseTokenConsole(&data) || com_token[0] != '{' )
2110                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2111
2112         PRVM_ED_ParseEdict (data, ent);
2113 }
2114
2115 /*
2116 =========
2117 VM_loadfromfile
2118
2119 loadfromfile(string file)
2120 =========
2121 */
2122 void VM_loadfromfile(void)
2123 {
2124         const char *filename;
2125         char *data;
2126
2127         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
2128
2129         filename = PRVM_G_STRING(OFS_PARM0);
2130         // .. is parent directory on many platforms
2131         // / is parent directory on Amiga
2132         // : is root of drive on Amiga (also used as a directory separator on Mac, but / works there too, so that's a bad idea)
2133         // \ is a windows-ism (so it's naughty to use it, / works on all platforms)
2134         if ((filename[0] == '.' && filename[1] == '.') || filename[0] == '/' || strrchr(filename, ':') || strrchr(filename, '\\'))
2135         {
2136                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2137                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
2138                 return;
2139         }
2140
2141         // not conform with VM_fopen
2142         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
2143         if (data == NULL)
2144                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2145
2146         PRVM_ED_LoadFromFile(data);
2147
2148         if(data)
2149                 Mem_Free(data);
2150 }
2151
2152
2153 /*
2154 =========
2155 VM_modulo
2156
2157 float   mod(float val, float m)
2158 =========
2159 */
2160 void VM_modulo(void)
2161 {
2162         int val, m;
2163         VM_SAFEPARMCOUNT(2,VM_module);
2164
2165         val = (int) PRVM_G_FLOAT(OFS_PARM0);
2166         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
2167
2168         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
2169 }
2170
2171 void VM_Search_Init(void)
2172 {
2173         memset(VM_SEARCHLIST,0,sizeof(fssearch_t*[MAX_VMSEARCHES]));
2174 }
2175
2176 void VM_Search_Reset(void)
2177 {
2178         int i;
2179         // reset the fssearch list
2180         for(i = 0; i < MAX_VMSEARCHES; i++)
2181                 if(VM_SEARCHLIST[i])
2182                         FS_FreeSearch(VM_SEARCHLIST[i]);
2183         memset(VM_SEARCHLIST,0,sizeof(fssearch_t*[MAX_VMSEARCHES]));
2184 }
2185
2186 /*
2187 =========
2188 VM_search_begin
2189
2190 float search_begin(string pattern, float caseinsensitive, float quiet)
2191 =========
2192 */
2193 void VM_search_begin(void)
2194 {
2195         int handle;
2196         const char *pattern;
2197         int caseinsens, quiet;
2198
2199         VM_SAFEPARMCOUNT(3, VM_search_begin);
2200
2201         pattern = PRVM_G_STRING(OFS_PARM0);
2202
2203         VM_CheckEmptyString(pattern);
2204
2205         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
2206         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
2207
2208         for(handle = 0; handle < MAX_VMSEARCHES; handle++)
2209                 if(!VM_SEARCHLIST[handle])
2210                         break;
2211
2212         if(handle >= MAX_VMSEARCHES)
2213         {
2214                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2215                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, MAX_VMSEARCHES);
2216                 return;
2217         }
2218
2219         if(!(VM_SEARCHLIST[handle] = FS_Search(pattern,caseinsens, quiet)))
2220                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2221         else
2222                 PRVM_G_FLOAT(OFS_RETURN) = handle;
2223 }
2224
2225 /*
2226 =========
2227 VM_search_end
2228
2229 void    search_end(float handle)
2230 =========
2231 */
2232 void VM_search_end(void)
2233 {
2234         int handle;
2235         VM_SAFEPARMCOUNT(1, VM_search_end);
2236
2237         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2238
2239         if(handle < 0 || handle >= MAX_VMSEARCHES)
2240         {
2241                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
2242                 return;
2243         }
2244         if(VM_SEARCHLIST[handle] == NULL)
2245         {
2246                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
2247                 return;
2248         }
2249
2250         FS_FreeSearch(VM_SEARCHLIST[handle]);
2251         VM_SEARCHLIST[handle] = NULL;
2252 }
2253
2254 /*
2255 =========
2256 VM_search_getsize
2257
2258 float   search_getsize(float handle)
2259 =========
2260 */
2261 void VM_search_getsize(void)
2262 {
2263         int handle;
2264         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
2265
2266         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2267
2268         if(handle < 0 || handle >= MAX_VMSEARCHES)
2269         {
2270                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
2271                 return;
2272         }
2273         if(VM_SEARCHLIST[handle] == NULL)
2274         {
2275                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
2276                 return;
2277         }
2278
2279         PRVM_G_FLOAT(OFS_RETURN) = VM_SEARCHLIST[handle]->numfilenames;
2280 }
2281
2282 /*
2283 =========
2284 VM_search_getfilename
2285
2286 string  search_getfilename(float handle, float num)
2287 =========
2288 */
2289 void VM_search_getfilename(void)
2290 {
2291         int handle, filenum;
2292         char *tmp;
2293         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
2294
2295         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2296         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
2297
2298         if(handle < 0 || handle >= MAX_VMSEARCHES)
2299         {
2300                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
2301                 return;
2302         }
2303         if(VM_SEARCHLIST[handle] == NULL)
2304         {
2305                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
2306                 return;
2307         }
2308         if(filenum < 0 || filenum >= VM_SEARCHLIST[handle]->numfilenames)
2309         {
2310                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
2311                 return;
2312         }
2313
2314         tmp = VM_GetTempString();
2315         strlcpy(tmp, VM_SEARCHLIST[handle]->filenames[filenum], VM_STRINGTEMP_LENGTH);
2316
2317         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2318 }
2319
2320 /*
2321 =========
2322 VM_chr
2323
2324 string  chr(float ascii)
2325 =========
2326 */
2327 void VM_chr(void)
2328 {
2329         char *tmp;
2330         VM_SAFEPARMCOUNT(1, VM_chr);
2331
2332         tmp = VM_GetTempString();
2333         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
2334         tmp[1] = 0;
2335
2336         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2337 }
2338
2339 //=============================================================================
2340 // Draw builtins (client & menu)
2341
2342 /*
2343 =========
2344 VM_iscachedpic
2345
2346 float   iscachedpic(string pic)
2347 =========
2348 */
2349 void VM_iscachedpic(void)
2350 {
2351         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
2352
2353         // drawq hasnt such a function, thus always return true
2354         PRVM_G_FLOAT(OFS_RETURN) = false;
2355 }
2356
2357 /*
2358 =========
2359 VM_precache_pic
2360
2361 string  precache_pic(string pic)
2362 =========
2363 */
2364 void VM_precache_pic(void)
2365 {
2366         const char      *s;
2367
2368         VM_SAFEPARMCOUNT(1, VM_precache_pic);
2369
2370         s = PRVM_G_STRING(OFS_PARM0);
2371         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
2372
2373         if(!s)
2374                 PRVM_ERROR ("VM_precache_pic: %s: NULL", PRVM_NAME);
2375
2376         VM_CheckEmptyString (s);
2377
2378         // AK Draw_CachePic is supposed to always return a valid pointer
2379         if( Draw_CachePic(s, false)->tex == r_texture_notexture )
2380                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(NULL);
2381 }
2382
2383 /*
2384 =========
2385 VM_freepic
2386
2387 freepic(string s)
2388 =========
2389 */
2390 void VM_freepic(void)
2391 {
2392         const char *s;
2393
2394         VM_SAFEPARMCOUNT(1,VM_freepic);
2395
2396         s = PRVM_G_STRING(OFS_PARM0);
2397
2398         if(!s)
2399                 PRVM_ERROR ("VM_freepic: %s: NULL");
2400
2401         VM_CheckEmptyString (s);
2402
2403         Draw_FreePic(s);
2404 }
2405
2406 /*
2407 =========
2408 VM_drawcharacter
2409
2410 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
2411 =========
2412 */
2413 void VM_drawcharacter(void)
2414 {
2415         float *pos,*scale,*rgb;
2416         char   character;
2417         int flag;
2418         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
2419
2420         character = (char) PRVM_G_FLOAT(OFS_PARM1);
2421         if(character == 0)
2422         {
2423                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2424                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
2425                 return;
2426         }
2427
2428         pos = PRVM_G_VECTOR(OFS_PARM0);
2429         scale = PRVM_G_VECTOR(OFS_PARM2);
2430         rgb = PRVM_G_VECTOR(OFS_PARM3);
2431         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2432
2433         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2434         {
2435                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2436                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2437                 return;
2438         }
2439
2440         if(pos[2] || scale[2])
2441                 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")));
2442
2443         if(!scale[0] || !scale[1])
2444         {
2445                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2446                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2447                 return;
2448         }
2449
2450         DrawQ_String (pos[0], pos[1], &character, 1, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2451         PRVM_G_FLOAT(OFS_RETURN) = 1;
2452 }
2453
2454 /*
2455 =========
2456 VM_drawstring
2457
2458 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
2459 =========
2460 */
2461 void VM_drawstring(void)
2462 {
2463         float *pos,*scale,*rgb;
2464         const char  *string;
2465         int flag;
2466         VM_SAFEPARMCOUNT(6,VM_drawstring);
2467
2468         string = PRVM_G_STRING(OFS_PARM1);
2469         if(!string)
2470         {
2471                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2472                 VM_Warning("VM_drawstring: %s passed null string !\n",PRVM_NAME);
2473                 return;
2474         }
2475
2476         //VM_CheckEmptyString(string); Why should it be checked - perhaps the menu wants to support the precolored letters, too?
2477
2478         pos = PRVM_G_VECTOR(OFS_PARM0);
2479         scale = PRVM_G_VECTOR(OFS_PARM2);
2480         rgb = PRVM_G_VECTOR(OFS_PARM3);
2481         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2482
2483         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2484         {
2485                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2486                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2487                 return;
2488         }
2489
2490         if(!scale[0] || !scale[1])
2491         {
2492                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2493                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2494                 return;
2495         }
2496
2497         if(pos[2] || scale[2])
2498                 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")));
2499
2500         DrawQ_String (pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2501         PRVM_G_FLOAT(OFS_RETURN) = 1;
2502 }
2503 /*
2504 =========
2505 VM_drawpic
2506
2507 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
2508 =========
2509 */
2510 void VM_drawpic(void)
2511 {
2512         const char *picname;
2513         float *size, *pos, *rgb;
2514         int flag;
2515
2516         VM_SAFEPARMCOUNT(6,VM_drawpic);
2517
2518         picname = PRVM_G_STRING(OFS_PARM1);
2519
2520         if(!picname)
2521         {
2522                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2523                 VM_Warning("VM_drawpic: %s passed null picture name !\n", PRVM_NAME);
2524                 return;
2525         }
2526
2527         VM_CheckEmptyString (picname);
2528
2529         // is pic cached ? no function yet for that
2530         if(!1)
2531         {
2532                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2533                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
2534                 return;
2535         }
2536
2537         pos = PRVM_G_VECTOR(OFS_PARM0);
2538         size = PRVM_G_VECTOR(OFS_PARM2);
2539         rgb = PRVM_G_VECTOR(OFS_PARM3);
2540         flag = (int) PRVM_G_FLOAT(OFS_PARM5);
2541
2542         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2543         {
2544                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2545                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2546                 return;
2547         }
2548
2549         if(pos[2] || size[2])
2550                 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")));
2551
2552         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);
2553         PRVM_G_FLOAT(OFS_RETURN) = 1;
2554 }
2555
2556 /*
2557 =========
2558 VM_drawfill
2559
2560 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
2561 =========
2562 */
2563 void VM_drawfill(void)
2564 {
2565         float *size, *pos, *rgb;
2566         int flag;
2567
2568         VM_SAFEPARMCOUNT(5,VM_drawfill);
2569
2570
2571         pos = PRVM_G_VECTOR(OFS_PARM0);
2572         size = PRVM_G_VECTOR(OFS_PARM1);
2573         rgb = PRVM_G_VECTOR(OFS_PARM2);
2574         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
2575
2576         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2577         {
2578                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2579                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2580                 return;
2581         }
2582
2583         if(pos[2] || size[2])
2584                 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")));
2585
2586         DrawQ_Pic(pos[0], pos[1], NULL, size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
2587         PRVM_G_FLOAT(OFS_RETURN) = 1;
2588 }
2589
2590 /*
2591 =========
2592 VM_drawsetcliparea
2593
2594 drawsetcliparea(float x, float y, float width, float height)
2595 =========
2596 */
2597 void VM_drawsetcliparea(void)
2598 {
2599         float x,y,w,h;
2600         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
2601
2602         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
2603         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
2604         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
2605         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
2606
2607         DrawQ_SetClipArea(x, y, w, h);
2608 }
2609
2610 /*
2611 =========
2612 VM_drawresetcliparea
2613
2614 drawresetcliparea()
2615 =========
2616 */
2617 void VM_drawresetcliparea(void)
2618 {
2619         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
2620
2621         DrawQ_ResetClipArea();
2622 }
2623
2624 /*
2625 =========
2626 VM_getimagesize
2627
2628 vector  getimagesize(string pic)
2629 =========
2630 */
2631 void VM_getimagesize(void)
2632 {
2633         const char *p;
2634         cachepic_t *pic;
2635
2636         VM_SAFEPARMCOUNT(1,VM_getimagesize);
2637
2638         p = PRVM_G_STRING(OFS_PARM0);
2639
2640         if(!p)
2641                 PRVM_ERROR("VM_getimagepos: %s passed null picture name !", PRVM_NAME);
2642
2643         VM_CheckEmptyString (p);
2644
2645         pic = Draw_CachePic (p, false);
2646
2647         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
2648         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
2649         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2650 }
2651
2652 /*
2653 =========
2654 VM_keynumtostring
2655
2656 string keynumtostring(float keynum)
2657 =========
2658 */
2659 void VM_keynumtostring (void)
2660 {
2661         int keynum;
2662         char *tmp;
2663         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
2664
2665         keynum = (int)PRVM_G_FLOAT(OFS_PARM0);
2666
2667         tmp = VM_GetTempString();
2668
2669         strlcpy(tmp, Key_KeynumToString(keynum), VM_STRINGTEMP_LENGTH);
2670
2671         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2672 }
2673
2674 /*
2675 =========
2676 VM_stringtokeynum
2677
2678 float stringtokeynum(string key)
2679 =========
2680 */
2681 void VM_stringtokeynum (void)
2682 {
2683         const char *str;
2684         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
2685
2686         str = PRVM_G_STRING( OFS_PARM0 );
2687
2688         PRVM_G_INT(OFS_RETURN) = Key_StringToKeynum( str );
2689 }
2690
2691 // CL_Video interface functions
2692
2693 /*
2694 ========================
2695 VM_cin_open
2696
2697 float cin_open(string file, string name)
2698 ========================
2699 */
2700 void VM_cin_open( void )
2701 {
2702         const char *file;
2703         const char *name;
2704
2705         VM_SAFEPARMCOUNT( 2, VM_cin_open );
2706
2707         file = PRVM_G_STRING( OFS_PARM0 );
2708         name = PRVM_G_STRING( OFS_PARM1 );
2709
2710         VM_CheckEmptyString( file );
2711     VM_CheckEmptyString( name );
2712
2713         if( CL_OpenVideo( file, name, MENUOWNER ) )
2714                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
2715         else
2716                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2717 }
2718
2719 /*
2720 ========================
2721 VM_cin_close
2722
2723 void cin_close(string name)
2724 ========================
2725 */
2726 void VM_cin_close( void )
2727 {
2728         const char *name;
2729
2730         VM_SAFEPARMCOUNT( 1, VM_cin_close );
2731
2732         name = PRVM_G_STRING( OFS_PARM0 );
2733         VM_CheckEmptyString( name );
2734
2735         CL_CloseVideo( CL_GetVideoByName( name ) );
2736 }
2737
2738 /*
2739 ========================
2740 VM_cin_setstate
2741 void cin_setstate(string name, float type)
2742 ========================
2743 */
2744 void VM_cin_setstate( void )
2745 {
2746         const char *name;
2747         clvideostate_t  state;
2748         clvideo_t               *video;
2749
2750         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
2751
2752         name = PRVM_G_STRING( OFS_PARM0 );
2753         VM_CheckEmptyString( name );
2754
2755         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
2756
2757         video = CL_GetVideoByName( name );
2758         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
2759                 CL_SetVideoState( video, state );
2760 }
2761
2762 /*
2763 ========================
2764 VM_cin_getstate
2765
2766 float cin_getstate(string name)
2767 ========================
2768 */
2769 void VM_cin_getstate( void )
2770 {
2771         const char *name;
2772         clvideo_t               *video;
2773
2774         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
2775
2776         name = PRVM_G_STRING( OFS_PARM0 );
2777         VM_CheckEmptyString( name );
2778
2779         video = CL_GetVideoByName( name );
2780         if( video )
2781                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
2782         else
2783                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2784 }
2785
2786 /*
2787 ========================
2788 VM_cin_restart
2789
2790 void cin_restart(string name)
2791 ========================
2792 */
2793 void VM_cin_restart( void )
2794 {
2795         const char *name;
2796         clvideo_t               *video;
2797
2798         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
2799
2800         name = PRVM_G_STRING( OFS_PARM0 );
2801         VM_CheckEmptyString( name );
2802
2803         video = CL_GetVideoByName( name );
2804         if( video )
2805                 CL_RestartVideo( video );
2806 }
2807
2808 /*
2809 ==============
2810 VM_vectorvectors
2811
2812 Writes new values for v_forward, v_up, and v_right based on the given forward vector
2813 vectorvectors(vector, vector)
2814 ==============
2815 */
2816 void VM_vectorvectors (void)
2817 {
2818         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), prog->globals.server->v_forward);
2819         VectorVectors(prog->globals.server->v_forward, prog->globals.server->v_right, prog->globals.server->v_up);
2820 }
2821
2822 /*
2823 ========================
2824 VM_drawline
2825
2826 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
2827 ========================
2828 */
2829 void VM_drawline (void)
2830 {
2831         float   *c1, *c2, *rgb;
2832         float   alpha, width;
2833         unsigned char   flags;
2834
2835         VM_SAFEPARMCOUNT(6, VM_drawline);
2836         width   = PRVM_G_FLOAT(OFS_PARM0);
2837         c1              = PRVM_G_VECTOR(OFS_PARM1);
2838         c2              = PRVM_G_VECTOR(OFS_PARM2);
2839         rgb             = PRVM_G_VECTOR(OFS_PARM3);
2840         alpha   = PRVM_G_FLOAT(OFS_PARM4);
2841         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
2842         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
2843 }
2844
2845 //====================
2846 //QC POLYGON functions
2847 //====================
2848
2849 typedef struct
2850 {
2851         rtexture_t              *tex;
2852         float                   data[36];       //[515]: enough for polygons
2853         unsigned char                   flags;  //[515]: + VM_POLYGON_2D and VM_POLYGON_FL4V flags
2854 }vm_polygon_t;
2855
2856 //static float                  vm_polygon_linewidth = 1;
2857 static mempool_t                *vm_polygons_pool = NULL;
2858 static unsigned char                    vm_current_vertices = 0;
2859 static qboolean                 vm_polygons_initialized = false;
2860 static vm_polygon_t             *vm_polygons = NULL;
2861 static unsigned long    vm_polygons_num = 0, vm_drawpolygons_num = 0;   //[515]: ok long on 64bit ?
2862 static qboolean                 vm_polygonbegin = false;        //[515]: for "no-crap-on-the-screen" check
2863 #define VM_DEFPOLYNUM 64        //[515]: enough for default ?
2864
2865 #define VM_POLYGON_FL3V         16      //more than 2 vertices (used only for lines)
2866 #define VM_POLYGON_FLLINES      32
2867 #define VM_POLYGON_FL2D         64
2868 #define VM_POLYGON_FL4V         128     //4 vertices
2869
2870 void VM_InitPolygons (void)
2871 {
2872         vm_polygons_pool = Mem_AllocPool("VMPOLY", 0, NULL);
2873         vm_polygons = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2874         memset(vm_polygons, 0, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2875         vm_polygons_num = VM_DEFPOLYNUM;
2876         vm_drawpolygons_num = 0;
2877         vm_polygonbegin = false;
2878         vm_polygons_initialized = true;
2879 }
2880
2881 void VM_DrawPolygonCallback (const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2882 {
2883         int surfacelistindex;
2884         // LordHavoc: FIXME: this is stupid code
2885         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
2886         {
2887                 const vm_polygon_t      *p = &vm_polygons[surfacelist[surfacelistindex]];
2888                 int                                     flags = p->flags & 0x0f;
2889
2890                 if(flags == DRAWFLAG_ADDITIVE)
2891                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2892                 else if(flags == DRAWFLAG_MODULATE)
2893                         GL_BlendFunc(GL_DST_COLOR, GL_ZERO);
2894                 else if(flags == DRAWFLAG_2XMODULATE)
2895                         GL_BlendFunc(GL_DST_COLOR,GL_SRC_COLOR);
2896                 else
2897                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2898
2899                 R_Mesh_TexBind(0, R_GetTexture(p->tex));
2900
2901                 CHECKGLERROR
2902                 //[515]: is speed is max ?
2903                 if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
2904                 {
2905                         qglLineWidth(p->data[13]);CHECKGLERROR
2906                         qglBegin(GL_LINE_LOOP);
2907                                 qglTexCoord1f   (p->data[12]);
2908                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
2909                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
2910
2911                                 qglTexCoord1f   (p->data[14]);
2912                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
2913                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
2914
2915                                 if(p->flags & VM_POLYGON_FL3V)
2916                                 {
2917                                         qglTexCoord1f   (p->data[16]);
2918                                         qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
2919                                         qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
2920
2921                                         if(p->flags & VM_POLYGON_FL4V)
2922                                         {
2923                                                 qglTexCoord1f   (p->data[18]);
2924                                                 qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
2925                                                 qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
2926                                         }
2927                                 }
2928                         qglEnd();
2929                         CHECKGLERROR
2930                 }
2931                 else
2932                 {
2933                         qglBegin(GL_POLYGON);
2934                                 qglTexCoord2f   (p->data[12], p->data[13]);
2935                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
2936                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
2937
2938                                 qglTexCoord2f   (p->data[14], p->data[15]);
2939                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
2940                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
2941
2942                                 qglTexCoord2f   (p->data[16], p->data[17]);
2943                                 qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
2944                                 qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
2945
2946                                 if(p->flags & VM_POLYGON_FL4V)
2947                                 {
2948                                         qglTexCoord2f   (p->data[18], p->data[19]);
2949                                         qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
2950                                         qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
2951                                 }
2952                         qglEnd();
2953                         CHECKGLERROR
2954                 }
2955         }
2956 }
2957
2958 void VM_AddPolygonTo2DScene (vm_polygon_t *p)
2959 {
2960         drawqueuemesh_t mesh;
2961         static int              picelements[6] = {0, 1, 2, 0, 2, 3};
2962
2963         mesh.texture = p->tex;
2964         mesh.data_element3i = picelements;
2965         mesh.data_vertex3f = p->data;
2966         mesh.data_texcoord2f = p->data + 12;
2967         mesh.data_color4f = p->data + 20;
2968         if(p->flags & VM_POLYGON_FL4V)
2969         {
2970                 mesh.num_vertices = 4;
2971                 mesh.num_triangles = 2;
2972         }
2973         else
2974         {
2975                 mesh.num_vertices = 3;
2976                 mesh.num_triangles = 1;
2977         }
2978         if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
2979                 DrawQ_LineLoop (&mesh, (p->flags&0x0f));
2980         else
2981                 DrawQ_Mesh (&mesh, (p->flags&0x0f));
2982 }
2983
2984 //void(string texturename, float flag, float 2d, float lines) R_BeginPolygon
2985 void VM_R_PolygonBegin (void)
2986 {
2987         vm_polygon_t    *p;
2988         const char              *picname;
2989         if(prog->argc < 2)
2990                 VM_SAFEPARMCOUNT(2, VM_R_PolygonBegin);
2991
2992         if(!vm_polygons_initialized)
2993                 VM_InitPolygons();
2994         if(vm_polygonbegin)
2995         {
2996                 VM_Warning("VM_R_PolygonBegin: called twice without VM_R_PolygonEnd after first\n");
2997                 return;
2998         }
2999         if(vm_drawpolygons_num >= vm_polygons_num)
3000         {
3001                 p = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3002                 memset(p, 0, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3003                 memcpy(p, vm_polygons, vm_polygons_num * sizeof(vm_polygon_t));
3004                 Mem_Free(vm_polygons);
3005                 vm_polygons = p;
3006                 vm_polygons_num *= 2;
3007         }
3008         p = &vm_polygons[vm_drawpolygons_num];
3009         picname = PRVM_G_STRING(OFS_PARM0);
3010         if(picname[0])
3011                 p->tex = Draw_CachePic(picname, true)->tex;
3012         else
3013                 p->tex = r_texture_white;
3014         p->flags = (unsigned char)PRVM_G_FLOAT(OFS_PARM1);
3015         vm_current_vertices = 0;
3016         vm_polygonbegin = true;
3017         if(prog->argc >= 3)
3018         {
3019                 if(PRVM_G_FLOAT(OFS_PARM2))
3020                         p->flags |= VM_POLYGON_FL2D;
3021                 if(prog->argc >= 4 && PRVM_G_FLOAT(OFS_PARM3))
3022                 {
3023                         p->data[13] = PRVM_G_FLOAT(OFS_PARM3);  //[515]: linewidth
3024                         p->flags |= VM_POLYGON_FLLINES;
3025                 }
3026         }
3027 }
3028
3029 //void(vector org, vector texcoords, vector rgb, float alpha) R_PolygonVertex
3030 void VM_R_PolygonVertex (void)
3031 {
3032         float                   *coords, *tx, *rgb, alpha;
3033         vm_polygon_t    *p;
3034         VM_SAFEPARMCOUNT(4, VM_R_PolygonVertex);
3035
3036         if(!vm_polygonbegin)
3037         {
3038                 VM_Warning("VM_R_PolygonVertex: VM_R_PolygonBegin wasn't called\n");
3039                 return;
3040         }
3041         coords  = PRVM_G_VECTOR(OFS_PARM0);
3042         tx              = PRVM_G_VECTOR(OFS_PARM1);
3043         rgb             = PRVM_G_VECTOR(OFS_PARM2);
3044         alpha = PRVM_G_FLOAT(OFS_PARM3);
3045
3046         p = &vm_polygons[vm_drawpolygons_num];
3047         if(vm_current_vertices > 4)
3048         {
3049                 VM_Warning("VM_R_PolygonVertex: may have 4 vertices max\n");
3050                 return;
3051         }
3052
3053         p->data[vm_current_vertices*3]          = coords[0];
3054         p->data[1+vm_current_vertices*3]        = coords[1];
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         strlcpy(out, in, VM_STRINGTEMP_LENGTH);
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         strlcpy(out, in, VM_STRINGTEMP_LENGTH);
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                         size_t stringlen;
3533                         stringlen = strlen(b1->strings[i]) + 1;
3534                         b2->strings[i] = (char *)Z_Malloc(stringlen);
3535                         if(!b2->strings[i])
3536                         {
3537                                 VM_Warning("VM_buf_copy: not enough memory for buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
3538                                 break;
3539                         }
3540                         memcpy(b2->strings[i], b1->strings[i], stringlen);
3541                 }
3542 }
3543
3544 /*
3545 ========================
3546 VM_buf_sort
3547 sort buffer by beginnings of strings (sortpower defaults it's lenght)
3548 "backward == TRUE" means that sorting goes upside-down
3549 void buf_sort(float bufhandle, float sortpower, float backward) = #464;
3550 ========================
3551 */
3552 void VM_buf_sort (void)
3553 {
3554         qcstrbuffer_t   *b;
3555         int                             i;
3556         VM_SAFEPARMCOUNT(3, VM_buf_sort);
3557
3558         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3559         if(!b)
3560         {
3561                 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3562                 return;
3563         }
3564         if(b->num_strings <= 0)
3565         {
3566                 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3567                 return;
3568         }
3569         buf_sortpower = (int)PRVM_G_FLOAT(OFS_PARM1);
3570         if(buf_sortpower <= 0)
3571                 buf_sortpower = 99999999;
3572
3573         if(!PRVM_G_FLOAT(OFS_PARM2))
3574                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsUP);
3575         else
3576                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
3577
3578         for(i=b->num_strings-1;i>=0;i--)        //[515]: delete empty lines
3579                 if(b->strings)
3580                 {
3581                         if(b->strings[i][0])
3582                                 break;
3583                         else
3584                         {
3585                                 Z_Free(b->strings[i]);
3586                                 --b->num_strings;
3587                                 b->strings[i] = NULL;
3588                         }
3589                 }
3590                 else
3591                         --b->num_strings;
3592 }
3593
3594 /*
3595 ========================
3596 VM_buf_implode
3597 concantenates all buffer string into one with "glue" separator and returns it as tempstring
3598 string buf_implode(float bufhandle, string glue) = #465;
3599 ========================
3600 */
3601 void VM_buf_implode (void)
3602 {
3603         qcstrbuffer_t   *b;
3604         char                    *k;
3605         const char              *sep;
3606         int                             i;
3607         size_t                  l;
3608         VM_SAFEPARMCOUNT(2, VM_buf_implode);
3609
3610         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3611         PRVM_G_INT(OFS_RETURN) = 0;
3612         if(!b)
3613         {
3614                 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3615                 return;
3616         }
3617         if(!b->num_strings)
3618                 return;
3619         sep = PRVM_G_STRING(OFS_PARM1);
3620         k = VM_GetTempString();
3621         k[0] = 0;
3622         for(l=i=0;i<b->num_strings;i++)
3623                 if(b->strings[i])
3624                 {
3625                         l += strlen(b->strings[i]);
3626                         if(l>=4095)
3627                                 break;
3628                         strlcat(k, b->strings[i], VM_STRINGTEMP_LENGTH);
3629                         if(sep && (i != b->num_strings-1))
3630                         {
3631                                 l += strlen(sep);
3632                                 if(l>=4095)
3633                                         break;
3634                                 strlcat(k, sep, VM_STRINGTEMP_LENGTH);
3635                         }
3636                 }
3637         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(k);
3638 }
3639
3640 /*
3641 ========================
3642 VM_bufstr_get
3643 get a string from buffer, returns direct pointer, dont str_unzone it!
3644 string bufstr_get(float bufhandle, float string_index) = #465;
3645 ========================
3646 */
3647 void VM_bufstr_get (void)
3648 {
3649         qcstrbuffer_t   *b;
3650         int                             strindex;
3651         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
3652
3653         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3654         if(!b)
3655         {
3656                 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3657                 return;
3658         }
3659         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3660         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3661         {
3662                 VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3663                 return;
3664         }
3665         PRVM_G_INT(OFS_RETURN) = 0;
3666         if(b->num_strings <= strindex)
3667                 return;
3668         if(b->strings[strindex])
3669                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(b->strings[strindex]);
3670 }
3671
3672 /*
3673 ========================
3674 VM_bufstr_set
3675 copies a string into selected slot of buffer
3676 void bufstr_set(float bufhandle, float string_index, string str) = #466;
3677 ========================
3678 */
3679 void VM_bufstr_set (void)
3680 {
3681         int                             bufindex, strindex;
3682         qcstrbuffer_t   *b;
3683         const char              *news;
3684         size_t                  alloclen;
3685
3686         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
3687
3688         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3689         b = BUFSTR_BUFFER(bufindex);
3690         if(!b)
3691         {
3692                 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3693                 return;
3694         }
3695         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3696         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3697         {
3698                 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3699                 return;
3700         }
3701         news = PRVM_G_STRING(OFS_PARM2);
3702         if(!news)
3703         {
3704                 VM_Warning("VM_bufstr_set: null string used in %s\n", PRVM_NAME);
3705                 return;
3706         }
3707         if(b->strings[strindex])
3708                 Z_Free(b->strings[strindex]);
3709         alloclen = strlen(news) + 1;
3710         b->strings[strindex] = (char *)Z_Malloc(alloclen);
3711         memcpy(b->strings[strindex], news, alloclen);
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         size_t                  alloclen;
3728
3729         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
3730
3731         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3732         b = BUFSTR_BUFFER(bufindex);
3733         PRVM_G_FLOAT(OFS_RETURN) = -1;
3734         if(!b)
3735         {
3736                 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3737                 return;
3738         }
3739         string = PRVM_G_STRING(OFS_PARM1);
3740         if(!string)
3741         {
3742                 VM_Warning("VM_bufstr_add: null string used in %s\n", PRVM_NAME);
3743                 return;
3744         }
3745
3746         order = (int)PRVM_G_FLOAT(OFS_PARM2);
3747         if(order)
3748                 strindex = b->num_strings;
3749         else
3750         {
3751                 strindex = BufStr_FindFreeString(b);
3752                 if(strindex < 0)
3753                 {
3754                         VM_Warning("VM_bufstr_add: buffer %i has no free string slots in %s\n", bufindex, PRVM_NAME);
3755                         return;
3756                 }
3757         }
3758
3759         while(b->num_strings <= strindex)
3760         {
3761                 if(b->num_strings == MAX_QCSTR_STRINGS)
3762                 {
3763                         VM_Warning("VM_bufstr_add: buffer %i has no free string slots in %s\n", bufindex, PRVM_NAME);
3764                         return;
3765                 }
3766                 b->strings[b->num_strings] = NULL;
3767                 b->num_strings++;
3768         }
3769         if(b->strings[strindex])
3770                 Z_Free(b->strings[strindex]);
3771         alloclen = strlen(string) + 1;
3772         b->strings[strindex] = (char *)Z_Malloc(alloclen);
3773         memcpy(b->strings[strindex], string, alloclen);
3774         PRVM_G_FLOAT(OFS_RETURN) = strindex;
3775 }
3776
3777 /*
3778 ========================
3779 VM_bufstr_free
3780 delete string from buffer
3781 void bufstr_free(float bufhandle, float string_index) = #468;
3782 ========================
3783 */
3784 void VM_bufstr_free (void)
3785 {
3786         int                             i;
3787         qcstrbuffer_t   *b;
3788         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
3789
3790         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3791         if(!b)
3792         {
3793                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3794                 return;
3795         }
3796         i = (int)PRVM_G_FLOAT(OFS_PARM1);
3797         if(i < 0 || i > MAX_QCSTR_STRINGS)
3798         {
3799                 VM_Warning("VM_bufstr_free: invalid string index %i used in %s\n", i, PRVM_NAME);
3800                 return;
3801         }
3802         if(b->strings[i])
3803                 Z_Free(b->strings[i]);
3804         b->strings[i] = NULL;
3805         if(i+1 == b->num_strings)
3806                 --b->num_strings;
3807 }
3808
3809 //=============
3810
3811 void VM_Cmd_Init(void)
3812 {
3813         // only init the stuff for the current prog
3814         VM_Files_Init();
3815         VM_Search_Init();
3816 //      VM_BufStr_Init();
3817         if(vm_polygons_initialized)
3818         {
3819                 Mem_FreePool(&vm_polygons_pool);
3820                 vm_polygons_initialized = false;
3821         }
3822 }
3823
3824 void VM_Cmd_Reset(void)
3825 {
3826         CL_PurgeOwner( MENUOWNER );
3827         VM_Search_Reset();
3828         VM_Files_CloseAll();
3829 //      VM_BufStr_ShutDown();
3830         if(vm_polygons_initialized)
3831         {
3832                 Mem_FreePool(&vm_polygons_pool);
3833                 vm_polygons_initialized = false;
3834         }
3835 }
3836