003eab4cd4061e3dc2d918d1cf93de9ff248c2b5
[divverent/darkplaces.git] / csprogs.c
1 #include "quakedef.h"
2 #include "progsvm.h"
3 #include "clprogdefs.h"
4 #include "csprogs.h"
5 #include "cl_collision.h"
6 #include "snd_main.h"
7 #include "clvm_cmds.h"
8 #include "prvm_cmds.h"
9
10 //============================================================================
11 // Client prog handling
12 //[515]: omg !!! optimize it ! a lot of hacks here and there also :P
13
14 #define CSQC_RETURNVAL  prog->globals.generic[OFS_RETURN]
15 #define CSQC_BEGIN              csqc_tmpprog=prog;prog=0;PRVM_SetProg(PRVM_CLIENTPROG);
16 #define CSQC_END                prog=csqc_tmpprog;
17
18 static prvm_prog_t *csqc_tmpprog;
19
20 void CL_VM_PreventInformationLeaks(void)
21 {
22         prvm_eval_t *val;
23         if(!cl.csqc_loaded)
24                 return;
25         CSQC_BEGIN
26                 VM_ClearTraceGlobals();
27                 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_networkentity)))
28                         val->_float = 0;
29         CSQC_END
30 }
31
32 //[515]: these are required funcs
33 static char *cl_required_func[] =
34 {
35         "CSQC_Init",
36         "CSQC_InputEvent",
37         "CSQC_UpdateView",
38         "CSQC_ConsoleCommand",
39 };
40
41 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
42
43 void CL_VM_Error (const char *format, ...) DP_FUNC_PRINTF(1);
44 void CL_VM_Error (const char *format, ...)      //[515]: hope it will be never executed =)
45 {
46         char errorstring[4096];
47         va_list argptr;
48
49         va_start (argptr, format);
50         dpvsnprintf (errorstring, sizeof(errorstring), format, argptr);
51         va_end (argptr);
52 //      Con_Printf( "CL_VM_Error: %s\n", errorstring );
53
54         PRVM_Crash();
55         cl.csqc_loaded = false;
56
57         Cvar_SetValueQuick(&csqc_progcrc, -1);
58         Cvar_SetValueQuick(&csqc_progsize, -1);
59
60 //      Host_AbortCurrentFrame();       //[515]: hmmm... if server says it needs csqc then client MUST disconnect
61         Host_Error("CL_VM_Error: %s", errorstring);
62 }
63 void CL_VM_UpdateDmgGlobals (int dmg_take, int dmg_save, vec3_t dmg_origin)
64 {
65         prvm_eval_t *val;
66         if(cl.csqc_loaded)
67         {
68                 CSQC_BEGIN
69                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_take);
70                 if(val)
71                         val->_float = dmg_take;
72                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_save);
73                 if(val)
74                         val->_float = dmg_save;
75                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_origin);
76                 if(val)
77                 {
78                         val->vector[0] = dmg_origin[0];
79                         val->vector[1] = dmg_origin[1];
80                         val->vector[2] = dmg_origin[2];
81                 }
82                 CSQC_END
83         }
84 }
85
86 void CSQC_UpdateNetworkTimes(double newtime, double oldtime)
87 {
88         prvm_eval_t *val;
89         if(!cl.csqc_loaded)
90                 return;
91         CSQC_BEGIN
92         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.servertime)))
93                 val->_float = newtime;
94         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.serverprevtime)))
95                 val->_float = oldtime;
96         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.serverdeltatime)))
97                 val->_float = newtime - oldtime;
98         CSQC_END
99 }
100
101 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
102 static void CSQC_SetGlobals (void)
103 {
104         prvm_eval_t *val;
105         CSQC_BEGIN
106                 prog->globals.client->time = cl.time;
107                 prog->globals.client->frametime = max(0, cl.time - cl.oldtime);
108                 prog->globals.client->servercommandframe = cls.servermovesequence;
109                 prog->globals.client->clientcommandframe = cl.movecmd[0].sequence;
110                 VectorCopy(cl.viewangles, prog->globals.client->input_angles);
111                 VectorCopy(cl.viewangles, cl.csqc_angles);
112                 // // FIXME: this actually belongs into getinputstate().. [12/17/2007 Black]
113                 prog->globals.client->input_buttons = cl.movecmd[0].buttons;
114                 VectorSet(prog->globals.client->input_movevalues, cl.movecmd[0].forwardmove, cl.movecmd[0].sidemove, cl.movecmd[0].upmove);
115                 //VectorCopy(cl.movement_origin, cl.csqc_origin);
116                 Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, cl.csqc_origin);
117
118                 // LordHavoc: Spike says not to do this, but without pmove_org the
119                 // CSQC is useless as it can't alter the view origin without
120                 // completely replacing it
121                 VectorCopy(cl.csqc_origin, prog->globals.client->pmove_org);
122                 VectorCopy(cl.movement_velocity, prog->globals.client->pmove_vel);
123
124                 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.view_angles)))
125                         VectorCopy(cl.viewangles, val->vector);
126                 prog->globals.client->maxclients = cl.maxclients;
127         CSQC_END
128 }
129
130 void CSQC_Predraw (prvm_edict_t *ed)
131 {
132         int b;
133         if(!ed->fields.client->predraw)
134                 return;
135         b = prog->globals.client->self;
136         prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
137         PRVM_ExecuteProgram(ed->fields.client->predraw, "CSQC_Predraw: NULL function\n");
138         prog->globals.client->self = b;
139 }
140
141 void CSQC_Think (prvm_edict_t *ed)
142 {
143         int b;
144         if(ed->fields.client->think)
145         if(ed->fields.client->nextthink && ed->fields.client->nextthink <= prog->globals.client->time)
146         {
147                 ed->fields.client->nextthink = 0;
148                 b = prog->globals.client->self;
149                 prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
150                 PRVM_ExecuteProgram(ed->fields.client->think, "CSQC_Think: NULL function\n");
151                 prog->globals.client->self = b;
152         }
153 }
154
155 extern cvar_t cl_noplayershadow;
156 qboolean CSQC_AddRenderEdict(prvm_edict_t *ed)
157 {
158         int renderflags;
159         int c;
160         float scale;
161         prvm_eval_t *val;
162         entity_render_t *entrender;
163         dp_model_t *model;
164         matrix4x4_t tagmatrix, matrix2;
165
166         model = CL_GetModelFromEdict(ed);
167         if (!model)
168                 return false;
169
170         entrender = CL_NewTempEntity(0);
171         if (!entrender)
172                 return false;
173
174         entrender->model = model;
175         entrender->skinnum = (int)ed->fields.client->skin;
176         entrender->effects |= entrender->model->effects;
177         scale = 1;
178         renderflags = 0;
179         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.renderflags)) && val->_float)     renderflags = (int)val->_float;
180         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.alpha)) && val->_float)           entrender->alpha = val->_float;
181         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.scale)) && val->_float)           entrender->scale = scale = val->_float;
182         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.colormod)) && VectorLength2(val->vector)) VectorCopy(val->vector, entrender->colormod);
183         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.effects)) && val->_float) entrender->effects |= (int)val->_float;
184         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_entity)) && val->edict)
185         {
186                 int tagentity;
187                 int tagindex = 0;
188                 tagentity = val->edict;
189                 if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_index)) && val->_float)
190                         tagindex = (int)val->_float;
191                 CL_GetTagMatrix (&tagmatrix, PRVM_PROG_TO_EDICT(tagentity), tagindex);
192         }
193         else
194                 Matrix4x4_CreateIdentity(&tagmatrix);
195
196         if (renderflags & RF_USEAXIS)
197         {
198                 vec3_t left;
199                 VectorNegate(prog->globals.client->v_right, left);
200                 Matrix4x4_FromVectors(&matrix2, prog->globals.client->v_forward, left, prog->globals.client->v_up, ed->fields.client->origin);
201                 Matrix4x4_Scale(&matrix2, scale, 1);
202         }
203         else
204         {
205                 vec3_t angles;
206                 VectorCopy(ed->fields.client->angles, angles);
207                 // if model is alias, reverse pitch direction
208                 if (entrender->model->type == mod_alias)
209                         angles[0] = -angles[0];
210
211                 // set up the render matrix
212                 Matrix4x4_CreateFromQuakeEntity(&matrix2, ed->fields.client->origin[0], ed->fields.client->origin[1], ed->fields.client->origin[2], angles[0], angles[1], angles[2], scale);
213         }
214
215         // set up the animation data
216         // self.frame is the interpolation target (new frame)
217         // self.frame1time is the animation base time for the interpolation target
218         // self.frame2 is the interpolation start (previous frame)
219         // self.frame2time is the animation base time for the interpolation start
220         // self.lerpfrac is the interpolation strength for self.frame
221         // 3+ are for additional blends (the main use for this feature is lerping
222         // pitch angle on a player model where the animator set up 5 sets of
223         // animations and the csqc simply lerps between sets)
224         entrender->framegroupblend[0].frame = entrender->framegroupblend[1].frame = (int) ed->fields.client->frame;
225         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2))) entrender->framegroupblend[1].frame = (int) val->_float;
226         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame3))) entrender->framegroupblend[2].frame = (int) val->_float;
227         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame4))) entrender->framegroupblend[3].frame = (int) val->_float;
228         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame1time))) entrender->framegroupblend[0].start = val->_float;
229         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2time))) entrender->framegroupblend[1].start = val->_float;
230         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame3time))) entrender->framegroupblend[2].start = val->_float;
231         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame4time))) entrender->framegroupblend[3].start = val->_float;
232         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac))) entrender->framegroupblend[0].lerp = val->_float;
233         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac3))) entrender->framegroupblend[2].lerp = val->_float;
234         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac4))) entrender->framegroupblend[3].lerp = val->_float;
235         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.shadertime))) entrender->shadertime = val->_float;
236         // assume that the (missing) lerpfrac2 is whatever remains after lerpfrac+lerpfrac3+lerpfrac4 are summed
237         entrender->framegroupblend[1].lerp = 1 - entrender->framegroupblend[0].lerp - entrender->framegroupblend[2].lerp - entrender->framegroupblend[3].lerp;
238
239         // concat the matrices to make the entity relative to its tag
240         Matrix4x4_Concat(&entrender->matrix, &tagmatrix, &matrix2);
241
242         if(renderflags)
243         {
244                 if(renderflags & RF_VIEWMODEL)  entrender->flags |= RENDER_VIEWMODEL;
245                 if(renderflags & RF_EXTERNALMODEL)entrender->flags |= RENDER_EXTERIORMODEL;
246                 if(renderflags & RF_DEPTHHACK)  entrender->effects |= EF_NODEPTHTEST;
247                 if(renderflags & RF_ADDITIVE)           entrender->effects |= EF_ADDITIVE;
248         }
249
250         c = (int)ed->fields.client->colormap;
251         if (c <= 0)
252                 CL_SetEntityColormapColors(entrender, -1);
253         else if (c <= cl.maxclients && cl.scores != NULL)
254                 CL_SetEntityColormapColors(entrender, cl.scores[c-1].colors);
255         else
256                 CL_SetEntityColormapColors(entrender, c);
257
258         entrender->flags &= ~(RENDER_SHADOW | RENDER_LIGHT | RENDER_NOSELFSHADOW);
259         // either fullbright or lit
260         if (!(entrender->effects & EF_FULLBRIGHT) && !r_fullbright.integer)
261                 entrender->flags |= RENDER_LIGHT;
262         // hide player shadow during intermission or nehahra movie
263         if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
264          &&  (entrender->alpha >= 1)
265          && !(entrender->flags & RENDER_VIEWMODEL)
266          && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
267                 entrender->flags |= RENDER_SHADOW;
268         if (entrender->flags & RENDER_VIEWMODEL)
269                 entrender->flags |= RENDER_NOSELFSHADOW;
270         if (entrender->effects & EF_NOSELFSHADOW)
271                 entrender->flags |= RENDER_NOSELFSHADOW;
272
273         // make the other useful stuff
274         CL_UpdateRenderEntity(entrender);
275
276         return true;
277 }
278
279 qboolean CL_VM_InputEvent (qboolean down, int key, int ascii)
280 {
281         qboolean r;
282
283         if(!cl.csqc_loaded)
284                 return false;
285
286         CSQC_BEGIN
287                 if (!prog->funcoffsets.CSQC_InputEvent)
288                         r = false;
289                 else
290                 {
291                         prog->globals.client->time = cl.time;
292                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
293                         PRVM_G_FLOAT(OFS_PARM0) = !down; // 0 is down, 1 is up
294                         PRVM_G_FLOAT(OFS_PARM1) = key;
295                         PRVM_G_FLOAT(OFS_PARM2) = ascii;
296                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_InputEvent, "QC function CSQC_InputEvent is missing");
297                         r = CSQC_RETURNVAL != 0;
298                 }
299         CSQC_END
300         return r;
301 }
302
303 qboolean CL_VM_UpdateView (void)
304 {
305         vec3_t emptyvector;
306         emptyvector[0] = 0;
307         emptyvector[1] = 0;
308         emptyvector[2] = 0;
309 //      vec3_t oldangles;
310         if(!cl.csqc_loaded)
311                 return false;
312         CSQC_BEGIN
313                 //VectorCopy(cl.viewangles, oldangles);
314                 prog->globals.client->time = cl.time;
315                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
316                 CSQC_SetGlobals();
317                 // clear renderable entity and light lists to prevent crashes if the
318                 // CSQC_UpdateView function does not call R_ClearScene as it should
319                 r_refdef.scene.numentities = 0;
320                 r_refdef.scene.numlights = 0;
321                 // pass in width and height as parameters (EXT_CSQC_1)
322                 PRVM_G_FLOAT(OFS_PARM0) = vid.width;
323                 PRVM_G_FLOAT(OFS_PARM1) = vid.height;
324                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_UpdateView, "QC function CSQC_UpdateView is missing");
325                 //VectorCopy(oldangles, cl.viewangles);
326                 // Dresk : Reset Dmg Globals Here
327                 CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
328         CSQC_END
329         return true;
330 }
331
332 extern sizebuf_t vm_tempstringsbuf;
333 qboolean CL_VM_ConsoleCommand (const char *cmd)
334 {
335         int restorevm_tempstringsbuf_cursize;
336         qboolean r = false;
337         if(!cl.csqc_loaded)
338                 return false;
339         CSQC_BEGIN
340         if (prog->funcoffsets.CSQC_ConsoleCommand)
341         {
342                 prog->globals.client->time = cl.time;
343                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
344                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
345                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
346                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_ConsoleCommand, "QC function CSQC_ConsoleCommand is missing");
347                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
348                 r = CSQC_RETURNVAL != 0;
349         }
350         CSQC_END
351         return r;
352 }
353
354 qboolean CL_VM_Parse_TempEntity (void)
355 {
356         int                     t;
357         qboolean        r = false;
358         if(!cl.csqc_loaded)
359                 return false;
360         CSQC_BEGIN
361         if(prog->funcoffsets.CSQC_Parse_TempEntity)
362         {
363                 t = msg_readcount;
364                 prog->globals.client->time = cl.time;
365                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
366                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_TempEntity, "QC function CSQC_Parse_TempEntity is missing");
367                 r = CSQC_RETURNVAL != 0;
368                 if(!r)
369                 {
370                         msg_readcount = t;
371                         msg_badread = false;
372                 }
373         }
374         CSQC_END
375         return r;
376 }
377
378 void CL_VM_Parse_StuffCmd (const char *msg)
379 {
380         int restorevm_tempstringsbuf_cursize;
381         if(msg[0] == 'c')
382         if(msg[1] == 's')
383         if(msg[2] == 'q')
384         if(msg[3] == 'c')
385         {
386                 // if this is setting a csqc variable, deprotect csqc_progcrc
387                 // temporarily so that it can be set by the cvar command,
388                 // and then reprotect it afterwards
389                 int crcflags = csqc_progcrc.flags;
390                 int sizeflags = csqc_progcrc.flags;
391                 csqc_progcrc.flags &= ~CVAR_READONLY;
392                 csqc_progsize.flags &= ~CVAR_READONLY;
393                 Cmd_ExecuteString (msg, src_command);
394                 csqc_progcrc.flags = crcflags;
395                 csqc_progsize.flags = sizeflags;
396                 return;
397         }
398
399         if(cls.demoplayback)
400         if(!strncmp(msg, "curl --clear_autodownload\ncurl --pak --forthismap --as ", 55))
401         {
402                 // special handling for map download commands
403                 // run these commands IMMEDIATELY, instead of waiting for a client frame
404                 // that way, there is no black screen when playing back demos
405                 // I know this is a really ugly hack, but I can't think of any better way
406                 // FIXME find the actual CAUSE of this, and make demo playback WAIT
407                 // until all maps are loaded, then remove this hack
408
409                 char buf[MAX_INPUTLINE];
410                 const char *p, *q;
411                 size_t l;
412
413                 p = msg;
414
415                 for(;;)
416                 {
417                         q = strchr(p, '\n');
418                         if(q)
419                                 l = q - p;
420                         else
421                                 l = strlen(p);
422                         if(l > sizeof(buf) - 1)
423                                 l = sizeof(buf) - 1;
424                         strlcpy(buf, p, l + 1); // strlcpy needs a + 1 as it includes the newline!
425
426                         Cmd_ExecuteString(buf, src_command);
427
428                         p += l;
429                         if(*p == '\n')
430                                 ++p; // skip the newline and continue
431                         else
432                                 break; // end of string or overflow
433                 }
434                 Cmd_ExecuteString("curl --clear_autodownload", src_command); // don't inhibit CSQC loading
435                 return;
436         }
437
438         if(!cl.csqc_loaded)
439         {
440                 Cbuf_AddText(msg);
441                 return;
442         }
443         CSQC_BEGIN
444         if(prog->funcoffsets.CSQC_Parse_StuffCmd)
445         {
446                 prog->globals.client->time = cl.time;
447                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
448                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
449                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
450                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_StuffCmd, "QC function CSQC_Parse_StuffCmd is missing");
451                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
452         }
453         else
454                 Cbuf_AddText(msg);
455         CSQC_END
456 }
457
458 static void CL_VM_Parse_Print (const char *msg)
459 {
460         int restorevm_tempstringsbuf_cursize;
461         prog->globals.client->time = cl.time;
462         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
463         restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
464         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
465         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_Print, "QC function CSQC_Parse_Print is missing");
466         vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
467 }
468
469 void CSQC_AddPrintText (const char *msg)
470 {
471         size_t i;
472         if(!cl.csqc_loaded)
473         {
474                 Con_Print(msg);
475                 return;
476         }
477         CSQC_BEGIN
478         if(prog->funcoffsets.CSQC_Parse_Print)
479         {
480                 // FIXME: is this bugged?
481                 i = strlen(msg)-1;
482                 if(msg[i] != '\n' && msg[i] != '\r')
483                 {
484                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
485                         {
486                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
487                                 cl.csqc_printtextbuf[0] = 0;
488                         }
489                         else
490                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
491                         return;
492                 }
493                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
494                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
495                 cl.csqc_printtextbuf[0] = 0;
496         }
497         else
498                 Con_Print(msg);
499         CSQC_END
500 }
501
502 void CL_VM_Parse_CenterPrint (const char *msg)
503 {
504         int restorevm_tempstringsbuf_cursize;
505         if(!cl.csqc_loaded)
506         {
507                 SCR_CenterPrint(msg);
508                 return;
509         }
510         CSQC_BEGIN
511         if(prog->funcoffsets.CSQC_Parse_CenterPrint)
512         {
513                 prog->globals.client->time = cl.time;
514                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
515                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
516                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
517                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_CenterPrint, "QC function CSQC_Parse_CenterPrint is missing");
518                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
519         }
520         else
521                 SCR_CenterPrint(msg);
522         CSQC_END
523 }
524
525 void CL_VM_UpdateIntermissionState (int intermission)
526 {
527         prvm_eval_t *val;
528         if(cl.csqc_loaded)
529         {
530                 CSQC_BEGIN
531                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.intermission);
532                 if(val)
533                         val->_float = intermission;
534                 CSQC_END
535         }
536 }
537 void CL_VM_UpdateShowingScoresState (int showingscores)
538 {
539         prvm_eval_t *val;
540         if(cl.csqc_loaded)
541         {
542                 CSQC_BEGIN
543                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.sb_showscores);
544                 if(val)
545                         val->_float = showingscores;
546                 CSQC_END
547         }
548 }
549 qboolean CL_VM_Event_Sound(int sound_num, float volume, int channel, float attenuation, int ent, vec3_t pos)
550 {
551         qboolean r = false;
552         if(cl.csqc_loaded)
553         {
554                 CSQC_BEGIN
555                 if(prog->funcoffsets.CSQC_Event_Sound)
556                 {
557                         prog->globals.client->time = cl.time;
558                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
559                         PRVM_G_FLOAT(OFS_PARM0) = ent;
560                         PRVM_G_FLOAT(OFS_PARM1) = channel;
561                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(cl.sound_name[sound_num] );
562                         PRVM_G_FLOAT(OFS_PARM3) = volume;
563                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
564                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
565                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event_Sound, "QC function CSQC_Event_Sound is missing");
566                         r = CSQC_RETURNVAL != 0;
567                 }
568                 CSQC_END
569         }
570
571         return r;
572 }
573 void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
574 {
575         // Avoid global names for clean(er) coding
576         int localcoop;
577         int localdeathmatch;
578
579         prvm_eval_t *val;
580         if(cl.csqc_loaded)
581         {
582                 if(gametype == GAME_COOP)
583                 {
584                         localcoop = 1;
585                         localdeathmatch = 0;
586                 }
587                 else
588                 if(gametype == GAME_DEATHMATCH)
589                 {
590                         localcoop = 0;
591                         localdeathmatch = 1;
592                 }
593                 else
594                 {
595                         // How did the ServerInfo send an unknown gametype?
596                         // Better just assign the globals as 0...
597                         localcoop = 0;
598                         localdeathmatch = 0;
599                 }
600                 CSQC_BEGIN
601                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.coop);
602                 if(val)
603                         val->_float = localcoop;
604                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.deathmatch);
605                 if(val)
606                         val->_float = localdeathmatch;
607                 CSQC_END
608         }
609 }
610 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
611 {
612         float r = 0;
613         if(!cl.csqc_loaded)
614                 return 0;
615         CSQC_BEGIN
616         if(prog->funcoffsets.CSQC_Event)
617         {
618                 prog->globals.client->time = cl.time;
619                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
620                 PRVM_G_FLOAT(OFS_PARM0) = event;
621                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event, "QC function CSQC_Event is missing");
622                 r = CSQC_RETURNVAL;
623         }
624         CSQC_END
625         return r;
626 }
627
628 void CSQC_ReadEntities (void)
629 {
630         unsigned short entnum, oldself, realentnum;
631         if(!cl.csqc_loaded)
632         {
633                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
634                 return;
635         }
636
637         CSQC_BEGIN
638                 prog->globals.client->time = cl.time;
639                 oldself = prog->globals.client->self;
640                 while(1)
641                 {
642                         entnum = MSG_ReadShort();
643                         if(!entnum || msg_badread)
644                                 return;
645                         realentnum = entnum & 0x7FFF;
646                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum];
647                         if(entnum & 0x8000)
648                         {
649                                 if(prog->globals.client->self)
650                                 {
651                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Remove, "QC function CSQC_Ent_Remove is missing");
652                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
653                                 }
654                                 else
655                                 {
656                                         // LordHavoc: removing an entity that is already gone on
657                                         // the csqc side is possible for legitimate reasons (such
658                                         // as a repeat of the remove message), so no warning is
659                                         // needed
660                                         //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
661                                 }
662                         }
663                         else
664                         {
665                                 if(!prog->globals.client->self)
666                                 {
667                                         if(!prog->funcoffsets.CSQC_Ent_Spawn)
668                                         {
669                                                 prvm_edict_t    *ed;
670                                                 ed = PRVM_ED_Alloc();
671                                                 ed->fields.client->entnum = realentnum;
672                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
673                                         }
674                                         else
675                                         {
676                                                 // entity( float entnum ) CSQC_Ent_Spawn;
677                                                 // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
678                                                 PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
679                                                 // make sure no one gets wrong ideas
680                                                 prog->globals.client->self = 0;
681                                                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Spawn, "QC function CSQC_Ent_Spawn is missing");
682                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
683                                         }
684                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
685                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
686                                 }
687                                 else {
688                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
689                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
690                                 }
691                         }
692                 }
693                 prog->globals.client->self = oldself;
694         CSQC_END
695 }
696
697 void CL_VM_CB_BeginIncreaseEdicts(void)
698 {
699         // links don't survive the transition, so unlink everything
700         World_UnlinkAll(&cl.world);
701 }
702
703 void CL_VM_CB_EndIncreaseEdicts(void)
704 {
705         int i;
706         prvm_edict_t *ent;
707
708         // link every entity except world
709         for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
710                 if (!ent->priv.server->free)
711                         CL_LinkEdict(ent);
712 }
713
714 void CL_VM_CB_InitEdict(prvm_edict_t *e)
715 {
716         e->priv.server->move = false; // don't move on first frame
717 }
718
719 void CL_VM_CB_FreeEdict(prvm_edict_t *ed)
720 {
721         World_UnlinkEdict(ed);
722         memset(ed->fields.client, 0, sizeof(*ed->fields.client));
723 }
724
725 void CL_VM_CB_CountEdicts(void)
726 {
727         int             i;
728         prvm_edict_t    *ent;
729         int             active = 0, models = 0, solid = 0;
730
731         for (i=0 ; i<prog->num_edicts ; i++)
732         {
733                 ent = PRVM_EDICT_NUM(i);
734                 if (ent->priv.server->free)
735                         continue;
736                 active++;
737                 if (ent->fields.client->solid)
738                         solid++;
739                 if (ent->fields.client->model)
740                         models++;
741         }
742
743         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
744         Con_Printf("active    :%3i\n", active);
745         Con_Printf("view      :%3i\n", models);
746         Con_Printf("touch     :%3i\n", solid);
747 }
748
749 qboolean CL_VM_CB_LoadEdict(prvm_edict_t *ent)
750 {
751         return true;
752 }
753
754 void Cmd_ClearCsqcFuncs (void);
755
756 // returns true if the packet is valid, false if end of file is reached
757 // used for dumping the CSQC download into demo files
758 qboolean MakeDownloadPacket(const char *filename, unsigned char *data, unsigned long len, int crc, int cnt, sizebuf_t *buf, int protocol)
759 {
760         int packetsize = buf->maxsize - 7; // byte short long
761         int npackets = (len + packetsize - 1) / (packetsize);
762
763         if(protocol == PROTOCOL_QUAKEWORLD)
764                 return false; // CSQC can't run in QW anyway
765
766         SZ_Clear(buf);
767         if(cnt == 0)
768         {
769                 MSG_WriteByte(buf, svc_stufftext);
770                 MSG_WriteString(buf, va("\ncl_downloadbegin %lu %s\n", len, filename));
771                 return true;
772         }
773         else if(cnt >= 1 && cnt <= npackets)
774         {
775                 unsigned long thispacketoffset = (cnt - 1) * packetsize;
776                 int thispacketsize = len - thispacketoffset;
777                 if(thispacketsize > packetsize)
778                         thispacketsize = packetsize;
779
780                 MSG_WriteByte(buf, svc_downloaddata);
781                 MSG_WriteLong(buf, thispacketoffset);
782                 MSG_WriteShort(buf, thispacketsize);
783                 SZ_Write(buf, data + thispacketoffset, thispacketsize);
784
785                 return true;
786         }
787         else if(cnt == npackets + 1)
788         {
789                 MSG_WriteByte(buf, svc_stufftext);
790                 MSG_WriteString(buf, va("\ncl_downloadfinished %lu %d\n", len, crc));
791                 return true;
792         }
793         return false;
794 }
795
796 void CL_VM_Init (void)
797 {
798         const char* csprogsfn;
799         unsigned char *csprogsdata;
800         fs_offset_t csprogsdatasize;
801         int csprogsdatacrc, requiredcrc;
802         int requiredsize;
803         prvm_eval_t *val;
804
805         // reset csqc_progcrc after reading it, so that changing servers doesn't
806         // expect csqc on the next server
807         requiredcrc = csqc_progcrc.integer;
808         requiredsize = csqc_progsize.integer;
809         Cvar_SetValueQuick(&csqc_progcrc, -1);
810         Cvar_SetValueQuick(&csqc_progsize, -1);
811
812         // if the server is not requesting a csprogs, then we're done here
813         if (requiredcrc < 0)
814                 return;
815
816         // see if the requested csprogs.dat file matches the requested crc
817         csprogsdatacrc = -1;
818         csprogsfn = va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
819         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
820         if (!csprogsdata)
821         {
822                 csprogsfn = csqc_progname.string;
823                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
824         }
825         if (csprogsdata)
826         {
827                 csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
828                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
829                 {
830                         if (cls.demoplayback)
831                         {
832                                 Con_Printf("^1Warning: Your %s is not the same version as the demo was recorded with (CRC/size are %i/%i but should be %i/%i)\n", csqc_progname.string, csprogsdatacrc, (int)csprogsdatasize, requiredcrc, requiredsize);
833                                 // Mem_Free(csprogsdata);
834                                 // return;
835                                 // We WANT to continue here, and play the demo with different csprogs!
836                                 // After all, this is just a warning. Sure things may go wrong from here.
837                         }
838                         else
839                         {
840                                 Mem_Free(csprogsdata);
841                                 Con_Printf("^1Your %s is not the same version as the server (CRC is %i/%i but should be %i/%i)\n", csqc_progname.string, csprogsdatacrc, (int)csprogsdatasize, requiredcrc, requiredsize);
842                                 CL_Disconnect();
843                                 return;
844                         }
845                 }
846         }
847         else
848         {
849                 if (requiredcrc >= 0)
850                 {
851                         if (cls.demoplayback)
852                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
853                         else
854                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
855                         CL_Disconnect();
856                 }
857                 return;
858         }
859
860         PRVM_Begin;
861         PRVM_InitProg(PRVM_CLIENTPROG);
862
863         // allocate the mempools
864         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
865         prog->headercrc = CL_PROGHEADER_CRC;
866         prog->edictprivate_size = 0; // no private struct used
867         prog->name = CL_NAME;
868         prog->num_edicts = 1;
869         prog->max_edicts = 512;
870         prog->limit_edicts = CL_MAX_EDICTS;
871         prog->reserved_edicts = 0;
872         prog->edictprivate_size = sizeof(edict_engineprivate_t);
873         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
874         prog->extensionstring = vm_sv_extensions;
875         prog->builtins = vm_cl_builtins;
876         prog->numbuiltins = vm_cl_numbuiltins;
877         prog->begin_increase_edicts = CL_VM_CB_BeginIncreaseEdicts;
878         prog->end_increase_edicts = CL_VM_CB_EndIncreaseEdicts;
879         prog->init_edict = CL_VM_CB_InitEdict;
880         prog->free_edict = CL_VM_CB_FreeEdict;
881         prog->count_edicts = CL_VM_CB_CountEdicts;
882         prog->load_edict = CL_VM_CB_LoadEdict;
883         prog->init_cmd = VM_CL_Cmd_Init;
884         prog->reset_cmd = VM_CL_Cmd_Reset;
885         prog->error_cmd = CL_VM_Error;
886
887         PRVM_LoadProgs(csprogsfn, cl_numrequiredfunc, cl_required_func, 0, NULL, 0, NULL);
888
889         if (!prog->loaded)
890         {
891                 CL_VM_Error("CSQC %s ^2failed to load\n", csprogsfn);
892                 if(!sv.active)
893                         CL_Disconnect();
894                 Mem_Free(csprogsdata);
895                 return;
896         }
897
898         Con_Printf("CSQC %s ^5loaded (crc=%i, size=%i)\n", csprogsfn, csprogsdatacrc, (int)csprogsdatasize);
899
900         if(cls.demorecording)
901         {
902                 if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
903                 {
904                         int i;
905                         char buf[NET_MAXMESSAGE];
906                         sizebuf_t sb;
907                         unsigned char *demobuf; fs_offset_t demofilesize;
908
909                         sb.data = (unsigned char *) buf;
910                         sb.maxsize = sizeof(buf);
911                         i = 0;
912
913                         CL_CutDemo(&demobuf, &demofilesize);
914                         while(MakeDownloadPacket(csqc_progname.string, csprogsdata, csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
915                                 CL_WriteDemoMessage(&sb);
916                         CL_PasteDemo(&demobuf, &demofilesize);
917
918                         cls.demo_lastcsprogssize = csprogsdatasize;
919                         cls.demo_lastcsprogscrc = csprogsdatacrc;
920                 }
921         }
922         Mem_Free(csprogsdata);
923
924         // check if OP_STATE animation is possible in this dat file
925         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
926                 prog->flag |= PRVM_OP_STATE;
927
928         // set time
929         prog->globals.client->time = cl.time;
930         prog->globals.client->self = 0;
931
932         prog->globals.client->mapname = cl.worldmodel ? PRVM_SetEngineString(cl.worldmodel->name) : PRVM_SetEngineString("");
933         prog->globals.client->player_localentnum = cl.playerentity;
934
935         // set map description (use world entity 0)
936         val = PRVM_EDICTFIELDVALUE(prog->edicts, prog->fieldoffsets.message);
937         if(val)
938                 val->string = PRVM_SetEngineString(cl.levelname);
939         VectorCopy(cl.world.mins, prog->edicts->fields.client->mins);
940         VectorCopy(cl.world.maxs, prog->edicts->fields.client->maxs);
941
942         // call the prog init
943         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Init, "QC function CSQC_Init is missing");
944
945         PRVM_End;
946         cl.csqc_loaded = true;
947
948         cl.csqc_vidvars.drawcrosshair = false;
949         cl.csqc_vidvars.drawenginesbar = false;
950
951         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
952         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
953 }
954
955 void CL_VM_ShutDown (void)
956 {
957         Cmd_ClearCsqcFuncs();
958         //Cvar_SetValueQuick(&csqc_progcrc, -1);
959         //Cvar_SetValueQuick(&csqc_progsize, -1);
960         if(!cl.csqc_loaded)
961                 return;
962         CSQC_BEGIN
963                 prog->globals.client->time = cl.time;
964                 prog->globals.client->self = 0;
965                 if (prog->funcoffsets.CSQC_Shutdown)
966                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Shutdown, "QC function CSQC_Shutdown is missing");
967                 PRVM_ResetProg();
968         CSQC_END
969         Con_Print("CSQC ^1unloaded\n");
970         cl.csqc_loaded = false;
971 }
972
973 qboolean CL_VM_GetEntitySoundOrigin(int entnum, vec3_t out)
974 {
975         prvm_edict_t *ed;
976         dp_model_t *mod;
977         matrix4x4_t matrix;
978         qboolean r = 0;
979
980         CSQC_BEGIN;
981
982         // FIXME consider attachments here!
983
984         ed = PRVM_EDICT_NUM(entnum - 32768);
985
986         if(!ed->priv.required->free)
987         {
988                 mod = CL_GetModelFromEdict(ed);
989                 VectorCopy(ed->fields.client->origin, out);
990                 if(CL_GetTagMatrix (&matrix, ed, 0) == 0)
991                         Matrix4x4_OriginFromMatrix(&matrix, out);
992                 if (mod && mod->soundfromcenter)
993                         VectorMAMAM(1.0f, out, 0.5f, mod->normalmins, 0.5f, mod->normalmaxs, out);
994                 r = 1;
995         }
996
997         CSQC_END;
998
999         return r;
1000 }