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