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