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