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