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