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