redesigned input networking code (still same protocol) and did a lot of cleaning...
[xonotic/darkplaces.git] / csprogs.c
1 #include "quakedef.h"
2 #include "progsvm.h"
3 #include "clprogdefs.h"
4 #include "csprogs.h"
5
6 //============================================================================
7 // Client prog handling
8 //[515]: omg !!! optimize it ! a lot of hacks here and there also :P
9
10 #define CSQC_RETURNVAL  prog->globals.generic[OFS_RETURN]
11 #define CSQC_BEGIN              csqc_tmpprog=prog;prog=0;PRVM_SetProg(PRVM_CLIENTPROG);
12 #define CSQC_END                prog=csqc_tmpprog;
13 static prvm_prog_t *csqc_tmpprog;
14
15 //[515]: these are required funcs
16 #define CL_F_INIT                               "CSQC_Init"
17 #define CL_F_INPUTEVENT                 "CSQC_InputEvent"
18 #define CL_F_UPDATEVIEW                 "CSQC_UpdateView"
19 #define CL_F_CONSOLECOMMAND             "CSQC_ConsoleCommand"
20 #define CL_F_SHUTDOWN                   "CSQC_Shutdown"
21
22 //[515]: these are optional
23 #define CL_F_PARSE_TEMPENTITY   "CSQC_Parse_TempEntity" //[515]: very helpfull when you want to create your own particles/decals/etc for effects that already exist
24 #define CL_F_PARSE_STUFFCMD             "CSQC_Parse_StuffCmd"
25 #define CL_F_PARSE_PRINT                "CSQC_Parse_Print"
26 #define CL_F_PARSE_CENTERPRINT  "CSQC_Parse_CenterPrint"
27 #define CL_F_ENT_UPDATE                 "CSQC_Ent_Update"
28 #define CL_F_ENT_REMOVE                 "CSQC_Ent_Remove"
29 #define CL_F_EVENT                              "CSQC_Event"    //[515]: engine call this for its own needs
30                                                                                                 //so csqc can do some things according to what engine it's running on
31                                                                                                 //example: to say about edicts increase, whatever...
32
33 #define CSQC_PRINTBUFFERLEN             8192    //[515]: enough ?
34
35 static char *cl_required_func[] =
36 {
37         CL_F_INIT,
38         CL_F_INPUTEVENT,
39         CL_F_UPDATEVIEW,
40         CL_F_CONSOLECOMMAND,
41         CL_F_SHUTDOWN
42 };
43
44 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
45
46 static char                             *csqc_printtextbuf = NULL;
47 static unsigned short   *csqc_sv2csqcents;      //[515]: server entities numbers on client side. FIXME : make pointers instead of numbers ?
48
49 static mfunction_t      *CSQC_Parse_TempEntity;
50 static mfunction_t      *CSQC_Parse_StuffCmd;
51 static mfunction_t      *CSQC_Parse_Print;
52 static mfunction_t      *CSQC_Parse_CenterPrint;
53 static mfunction_t      *CSQC_Ent_Update;
54 static mfunction_t      *CSQC_Ent_Remove;
55 static mfunction_t      *CSQC_Event;
56
57 static int csqc_fieldoff_alpha;
58 static int csqc_fieldoff_colormod;
59 static int csqc_fieldoff_effects;
60 int csqc_fieldoff_scale;
61 int csqc_fieldoff_renderflags;
62 int csqc_fieldoff_tag_entity;
63 int csqc_fieldoff_tag_index;
64 int csqc_fieldoff_dphitcontentsmask;
65
66 qboolean csqc_loaded = false;
67
68 vec3_t csqc_origin, csqc_angles;
69 static double csqc_frametime = 0;
70
71 static mempool_t *csqc_mempool;
72
73 static void CL_VM_FindEdictFieldOffsets (void)
74 {
75         csqc_fieldoff_alpha                     = PRVM_ED_FindFieldOffset("alpha");
76         csqc_fieldoff_scale                     = PRVM_ED_FindFieldOffset("scale");
77         csqc_fieldoff_colormod          = PRVM_ED_FindFieldOffset("colormod");
78         csqc_fieldoff_renderflags       = PRVM_ED_FindFieldOffset("renderflags");
79         csqc_fieldoff_effects           = PRVM_ED_FindFieldOffset("effects");
80         csqc_fieldoff_tag_entity        = PRVM_ED_FindFieldOffset("tag_entity");
81         csqc_fieldoff_tag_index         = PRVM_ED_FindFieldOffset("tag_index");
82
83         CSQC_Parse_TempEntity           = PRVM_ED_FindFunction (CL_F_PARSE_TEMPENTITY);
84         CSQC_Parse_StuffCmd                     = PRVM_ED_FindFunction (CL_F_PARSE_STUFFCMD);
85         CSQC_Parse_Print                        = PRVM_ED_FindFunction (CL_F_PARSE_PRINT);
86         CSQC_Parse_CenterPrint          = PRVM_ED_FindFunction (CL_F_PARSE_CENTERPRINT);
87         CSQC_Ent_Update                         = PRVM_ED_FindFunction (CL_F_ENT_UPDATE);
88         CSQC_Ent_Remove                         = PRVM_ED_FindFunction (CL_F_ENT_REMOVE);
89         CSQC_Event                                      = PRVM_ED_FindFunction (CL_F_EVENT);
90
91         if(CSQC_Parse_Print)
92         {
93                 csqc_printtextbuf = (char *)Mem_Alloc(csqc_mempool, CSQC_PRINTBUFFERLEN);
94                 csqc_printtextbuf[0] = 0;
95         }
96 }
97
98 void CL_VM_Error (const char *format, ...) DP_FUNC_PRINTF(1);
99 void CL_VM_Error (const char *format, ...)      //[515]: hope it will be never executed =)
100 {
101         char errorstring[4096];
102         va_list argptr;
103
104         va_start (argptr, format);
105         dpvsnprintf (errorstring, sizeof(errorstring), format, argptr);
106         va_end (argptr);
107 //      Con_Printf( "CL_VM_Error: %s\n", errorstring );
108
109         PRVM_Crash();
110         csqc_loaded = false;
111         Mem_FreePool(&csqc_mempool);
112
113         Cvar_SetValueQuick(&csqc_progcrc, -1);
114         Cvar_SetValueQuick(&csqc_progsize, -1);
115
116 //      Host_AbortCurrentFrame();       //[515]: hmmm... if server says it needs csqc then client MUST disconnect
117         Host_Error(va("CL_VM_Error: %s", errorstring));
118 }
119
120 model_t *CSQC_GetModelByIndex(int modelindex)
121 {
122         if(!modelindex)
123                 return NULL;
124         if (modelindex < 0)
125         {
126                 modelindex = -(modelindex+1);
127                 if (modelindex < MAX_MODELS)
128                         return cl.csqc_model_precache[modelindex];
129         }
130         else
131         {
132                 if(modelindex < MAX_MODELS)
133                         return cl.model_precache[modelindex];
134         }
135         return NULL;
136 }
137
138 model_t *CSQC_GetModelFromEntity(prvm_edict_t *ed)
139 {
140         if (!ed || ed->priv.server->free)
141                 return NULL;
142         return CSQC_GetModelByIndex((int)ed->fields.client->modelindex);
143 }
144
145 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
146 static void CSQC_SetGlobals (void)
147 {
148         //extern cvar_t sv_accelerate, sv_friction, sv_gravity, sv_stopspeed, sv_maxspeed;
149
150         CSQC_BEGIN
151                 *prog->time = cl.time;
152                 prog->globals.client->frametime = cl.time - csqc_frametime;
153                 csqc_frametime = cl.time;
154                 prog->globals.client->servercommandframe = cl.servermovesequence;
155                 prog->globals.client->clientcommandframe = cl.movesequence;
156                 VectorCopy(cl.viewangles, prog->globals.client->input_angles);
157                 VectorCopy(cl.viewangles, csqc_angles);
158                 prog->globals.client->input_buttons = cl.cmd.buttons;
159                 VectorSet(prog->globals.client->input_movevalues, cl.cmd.forwardmove, cl.cmd.sidemove, cl.cmd.upmove);
160                 //VectorCopy(cl.movement_origin, csqc_origin);
161                 Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, csqc_origin);
162                 VectorCopy(csqc_origin, prog->globals.client->pmove_org);
163                 prog->globals.client->maxclients = cl.maxclients;
164                 //VectorCopy(cl.movement_velocity, prog->globals.client->pmove_vel);
165                 VectorCopy(cl.velocity, prog->globals.client->pmove_vel);
166         CSQC_END
167 }
168
169 void CSQC_Predraw (prvm_edict_t *ed)
170 {
171         int b;
172         if(!ed->fields.client->predraw)
173                 return;
174         b = prog->globals.client->self;
175         prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
176         PRVM_ExecuteProgram(ed->fields.client->predraw, "CSQC_Predraw: NULL function\n");
177         prog->globals.client->self = b;
178 }
179
180 void CSQC_Think (prvm_edict_t *ed)
181 {
182         int b;
183         if(ed->fields.client->think)
184         if(ed->fields.client->nextthink && ed->fields.client->nextthink <= *prog->time)
185         {
186                 ed->fields.client->nextthink = 0;
187                 b = prog->globals.client->self;
188                 prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
189                 PRVM_ExecuteProgram(ed->fields.client->think, "CSQC_Think: NULL function\n");
190                 prog->globals.client->self = b;
191         }
192 }
193
194 extern cvar_t cl_noplayershadow;
195 qboolean CSQC_AddRenderEdict(prvm_edict_t *ed)
196 {
197         int i, renderflags;
198         float scale;
199         prvm_eval_t *val;
200         entity_t *e;
201         model_t *model;
202         matrix4x4_t tagmatrix, matrix2;
203
204         model = CSQC_GetModelFromEntity(ed);
205         if (!model)
206                 return false;
207
208         e = CL_NewTempEntity();
209         if (!e)
210                 return false;
211
212         e->render.model = model;
213         e->render.colormap = (int)ed->fields.client->colormap;
214         e->render.frame = (int)ed->fields.client->frame;
215         e->render.skinnum = (int)ed->fields.client->skin;
216         e->render.effects |= e->render.model->flags2 & (EF_FULLBRIGHT | EF_ADDITIVE);
217         scale = 1;
218         // FIXME: renderflags should be in the cl_entvars_t
219 #if 1
220         renderflags = 0;
221         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_renderflags)) && val->_float)       renderflags = (int)val->_float;
222 #else
223         renderflags = (int)ed->fields.client->renderflags;
224 #endif
225
226         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_alpha)) && val->_float)             e->render.alpha = val->_float;
227         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_scale)) && val->_float)             e->render.scale = scale = val->_float;
228         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_colormod)) && VectorLength2(val->vector))   VectorCopy(val->vector, e->render.colormod);
229         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_effects)) && val->_float)   e->render.effects = (int)val->_float;
230         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_tag_entity)) && val->edict)
231         {
232                 int tagentity;
233                 int tagindex = 0;
234                 tagentity = val->edict;
235                 if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_tag_index)) && val->_float)
236                         tagindex = (int)val->_float;
237                 // FIXME: calculate tag matrix
238                 Matrix4x4_CreateIdentity(&tagmatrix);
239         }
240         else
241                 Matrix4x4_CreateIdentity(&tagmatrix);
242
243         if (renderflags & RF_USEAXIS)
244         {
245                 vec3_t left;
246                 VectorNegate(prog->globals.client->v_right, left);
247                 Matrix4x4_FromVectors(&matrix2, prog->globals.client->v_forward, left, prog->globals.client->v_up, ed->fields.client->origin);
248         }
249         else
250         {
251                 vec3_t angles;
252                 VectorCopy(ed->fields.client->angles, angles);
253                 // if model is alias, reverse pitch direction
254                 if (e->render.model->type == mod_alias)
255                         angles[0] = -angles[0];
256
257                 // set up the render matrix
258                 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);
259         }
260
261         // FIXME: csqc has frame1/frame2/frame1time/frame2time/lerpfrac but this implementation's cl_entvars_t lacks those fields
262         e->render.frame1 = e->render.frame = ed->fields.client->frame;
263         e->render.frame1time = e->render.frame2time = 0;
264         e->render.framelerp = 0;
265
266         // concat the matrices to make the entity relative to its tag
267         Matrix4x4_Concat(&e->render.matrix, &tagmatrix, &matrix2);
268         // make the other useful stuff
269         CL_UpdateRenderEntity(&e->render);
270
271         i = 0;
272         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_renderflags)) && val->_float)
273         {
274                 i = (int)val->_float;
275                 if(i & RF_VIEWMODEL)    e->render.flags |= RENDER_VIEWMODEL;
276                 if(i & RF_EXTERNALMODEL)e->render.flags |= RENDER_EXTERIORMODEL;
277                 if(i & RF_DEPTHHACK)    e->render.effects |= EF_NODEPTHTEST;
278                 if(i & RF_ADDITIVE)             e->render.effects |= EF_ADDITIVE;
279         }
280
281         // transparent stuff can't be lit during the opaque stage
282         if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
283                 e->render.flags |= RENDER_TRANSPARENT;
284         // double sided rendering mode causes backfaces to be visible
285         // (mostly useful on transparent stuff)
286         if (e->render.effects & EF_DOUBLESIDED)
287                 e->render.flags |= RENDER_NOCULLFACE;
288         // either fullbright or lit
289         if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
290                 e->render.flags |= RENDER_LIGHT;
291         // hide player shadow during intermission or nehahra movie
292         if (!(e->render.effects & EF_NOSHADOW)
293          && !(e->render.flags & (RENDER_VIEWMODEL | RENDER_TRANSPARENT))
294          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
295                 e->render.flags |= RENDER_SHADOW;
296
297         return true;
298 }
299
300 qboolean CL_VM_InputEvent (qboolean pressed, int key)
301 {
302         qboolean r;
303         if(!csqc_loaded)
304                 return false;
305         CSQC_BEGIN
306                 *prog->time = cl.time;
307                 PRVM_G_FLOAT(OFS_PARM0) = pressed;
308                 PRVM_G_FLOAT(OFS_PARM1) = key;
309                 PRVM_ExecuteProgram (prog->globals.client->CSQC_InputEvent, CL_F_INPUTEVENT);
310                 r = CSQC_RETURNVAL;
311         CSQC_END
312         return r;
313 }
314
315 qboolean CL_VM_UpdateView (void)
316 {
317 //      vec3_t oldangles;
318         if(!csqc_loaded)
319                 return false;
320         CSQC_BEGIN
321                 //VectorCopy(cl.viewangles, oldangles);
322                 *prog->time = cl.time;
323                 CSQC_SetGlobals();
324                 r_refdef.numentities = 0;
325                 PRVM_ExecuteProgram (prog->globals.client->CSQC_UpdateView, CL_F_UPDATEVIEW);
326                 //VectorCopy(oldangles, cl.viewangles);
327         CSQC_END
328         return true;
329 }
330
331 extern sizebuf_t vm_tempstringsbuf;
332 qboolean CL_VM_ConsoleCommand (const char *cmd)
333 {
334         int restorevm_tempstringsbuf_cursize;
335         qboolean r;
336         if(!csqc_loaded)
337                 return false;
338         CSQC_BEGIN
339                 *prog->time = cl.time;
340                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
341                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
342                 PRVM_ExecuteProgram (prog->globals.client->CSQC_ConsoleCommand, CL_F_CONSOLECOMMAND);
343                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
344                 r = CSQC_RETURNVAL;
345         CSQC_END
346         return r;
347 }
348
349 qboolean CL_VM_Parse_TempEntity (void)
350 {
351         int                     t;
352         qboolean        r;
353         if(!csqc_loaded || !CSQC_Parse_TempEntity)
354                 return false;
355         t = msg_readcount;
356         CSQC_BEGIN
357                 *prog->time = cl.time;
358                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_TempEntity - prog->functions), CL_F_PARSE_TEMPENTITY);
359                 r = CSQC_RETURNVAL;
360         CSQC_END
361         if(!r)
362         {
363                 msg_readcount = t;
364                 msg_badread = false;
365         }
366         return r;
367 }
368
369 void CL_VM_Parse_StuffCmd (const char *msg)
370 {
371         int restorevm_tempstringsbuf_cursize;
372         if(msg[0] == 'c')
373         if(msg[1] == 's')
374         if(msg[2] == 'q')
375         if(msg[3] == 'c')
376         {
377                 // if this is setting a csqc variable, deprotect csqc_progcrc
378                 // temporarily so that it can be set by the cvar command,
379                 // and then reprotect it afterwards
380                 int crcflags = csqc_progcrc.flags;
381                 int sizeflags = csqc_progcrc.flags;
382                 csqc_progcrc.flags &= ~CVAR_READONLY;
383                 csqc_progsize.flags &= ~CVAR_READONLY;
384                 Cmd_ExecuteString (msg, src_command);
385                 csqc_progcrc.flags = crcflags;
386                 csqc_progsize.flags = sizeflags;
387                 return;
388         }
389         if(!csqc_loaded || !CSQC_Parse_StuffCmd)
390         {
391                 Cbuf_AddText(msg);
392                 return;
393         }
394         CSQC_BEGIN
395                 *prog->time = cl.time;
396                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
397                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
398                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_StuffCmd - prog->functions), CL_F_PARSE_STUFFCMD);
399                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
400         CSQC_END
401 }
402
403 static void CL_VM_Parse_Print (const char *msg)
404 {
405         int restorevm_tempstringsbuf_cursize;
406         CSQC_BEGIN
407                 *prog->time = cl.time;
408                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
409                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
410                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_Print - prog->functions), CL_F_PARSE_PRINT);
411                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
412         CSQC_END
413 }
414
415 void CSQC_AddPrintText (const char *msg)
416 {
417         size_t i;
418         if(!csqc_loaded || !CSQC_Parse_Print)
419         {
420                 Con_Print(msg);
421                 return;
422         }
423         // FIXME: is this bugged?
424         i = strlen(msg)-1;
425         if(msg[i] != '\n' && msg[i] != '\r')
426         {
427                 if(strlen(csqc_printtextbuf)+i >= CSQC_PRINTBUFFERLEN)
428                 {
429                         CL_VM_Parse_Print(csqc_printtextbuf);
430                         csqc_printtextbuf[0] = 0;
431                 }
432                 else
433                         strlcat(csqc_printtextbuf, msg, CSQC_PRINTBUFFERLEN);
434                 return;
435         }
436         strlcat(csqc_printtextbuf, msg, CSQC_PRINTBUFFERLEN);
437         CL_VM_Parse_Print(csqc_printtextbuf);
438         csqc_printtextbuf[0] = 0;
439 }
440
441 void CL_VM_Parse_CenterPrint (const char *msg)
442 {
443         int restorevm_tempstringsbuf_cursize;
444         if(!csqc_loaded || !CSQC_Parse_CenterPrint)
445         {
446                 SCR_CenterPrint((char*)msg);
447                 return;
448         }
449         CSQC_BEGIN
450                 *prog->time = cl.time;
451                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
452                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
453                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_CenterPrint - prog->functions), CL_F_PARSE_CENTERPRINT);
454                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
455         CSQC_END
456 }
457
458 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
459 {
460         float r;
461         if(!csqc_loaded || !CSQC_Event)
462                 return 0;
463         CSQC_BEGIN
464                 *prog->time = cl.time;
465                 PRVM_G_FLOAT(OFS_PARM0) = event;
466                 PRVM_ExecuteProgram ((func_t)(CSQC_Event - prog->functions), CL_F_EVENT);
467                 r = CSQC_RETURNVAL;
468         CSQC_END
469         return r;
470 }
471
472 void CSQC_ReadEntities (void)
473 {
474         unsigned short entnum, oldself, realentnum;
475         CSQC_BEGIN
476                 *prog->time = cl.time;
477                 oldself = prog->globals.client->self;
478                 while(1)
479                 {
480                         entnum = MSG_ReadShort();
481                         if(!entnum)
482                                 return;
483                         realentnum = entnum & 0x7FFF;
484                         prog->globals.client->self = csqc_sv2csqcents[realentnum];
485                         if(entnum & 0x8000)
486                         {
487                                 if(prog->globals.client->self)
488                                 {
489                                         PRVM_ExecuteProgram((func_t)(CSQC_Ent_Remove - prog->functions), CL_F_ENT_REMOVE);
490                                         csqc_sv2csqcents[realentnum] = 0;
491                                 }
492                                 else
493                                         Con_Printf("Smth bad happens in csqc...\n");    //[515]: never happens ?
494                         }
495                         else
496                         {
497                                 if(!prog->globals.client->self)
498                                 {
499                                         prvm_edict_t    *ed;
500                                         ed = PRVM_ED_Alloc();
501                                         ed->fields.client->entnum = realentnum;
502                                         prog->globals.client->self = csqc_sv2csqcents[realentnum] = PRVM_EDICT_TO_PROG(ed);
503                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
504                                 }
505                                 else
506                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
507                                 PRVM_ExecuteProgram((func_t)(CSQC_Ent_Update - prog->functions), CL_F_ENT_UPDATE);
508                         }
509                 }
510                 prog->globals.client->self = oldself;
511         CSQC_END
512 }
513
514 void Cmd_ClearCsqcFuncs (void);
515
516 void CL_VM_Init (void)
517 {
518         unsigned char *csprogsdata;
519         fs_offset_t csprogsdatasize;
520         int csprogsdatacrc, requiredcrc;
521         int requiredsize;
522
523         // reset csqc_progcrc after reading it, so that changing servers doesn't
524         // expect csqc on the next server
525         requiredcrc = csqc_progcrc.integer;
526         requiredsize = csqc_progsize.integer;
527         Cvar_SetValueQuick(&csqc_progcrc, -1);
528         Cvar_SetValueQuick(&csqc_progsize, -1);
529
530         csqc_loaded = false;
531         memset(cl.csqc_model_precache, 0, sizeof(cl.csqc_model_precache));
532         memset(&cl.csqc_vidvars, true, sizeof(csqc_vidvars_t));
533
534         // if the server is not requesting a csprogs, then we're done here
535         if (requiredcrc < 0)
536                 return;
537
538         // see if the requested csprogs.dat file matches the requested crc
539         csprogsdatacrc = -1;
540         csprogsdata = FS_LoadFile(va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc), tempmempool, true, &csprogsdatasize);
541         if (!csprogsdata)
542                 csprogsdata = FS_LoadFile(csqc_progname.string, tempmempool, true, &csprogsdatasize);
543         if (csprogsdata)
544         {
545                 csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
546                 Mem_Free(csprogsdata);
547                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
548                 {
549                         if (cls.demoplayback)
550                         {
551                                 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);
552                                 return;
553                         }
554                         else
555                         {
556                                 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);
557                                 CL_Disconnect();
558                                 return;
559                         }
560                 }
561         }
562         else
563         {
564                 if (requiredcrc >= 0)
565                 {
566                         if (cls.demoplayback)
567                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
568                         else
569                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
570                         CL_Disconnect();
571                 }
572                 return;
573         }
574
575         PRVM_Begin;
576         PRVM_InitProg(PRVM_CLIENTPROG);
577
578         csqc_mempool = Mem_AllocPool("CSQC", 0, NULL);
579
580         // allocate the mempools
581         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
582         prog->headercrc = CL_PROGHEADER_CRC;
583         prog->edictprivate_size = 0; // no private struct used
584         prog->name = CL_NAME;
585         prog->num_edicts = 1;
586         prog->limit_edicts = CL_MAX_EDICTS;
587         prog->extensionstring = vm_cl_extensions;
588         prog->builtins = vm_cl_builtins;
589         prog->numbuiltins = vm_cl_numbuiltins;
590         prog->init_cmd = VM_CL_Cmd_Init;
591         prog->reset_cmd = VM_CL_Cmd_Reset;
592         prog->error_cmd = CL_VM_Error;
593
594         PRVM_LoadProgs(csqc_progname.string, cl_numrequiredfunc, cl_required_func, 0, NULL);
595
596         if(prog->loaded)
597                 Con_Printf("CSQC ^5loaded (crc=%i, size=%i)\n", csprogsdatacrc, (int)csprogsdatasize);
598         else
599         {
600                 CL_VM_Error("CSQC ^2failed to load\n");
601                 if(!sv.active)
602                         CL_Disconnect();
603                 return;
604         }
605
606         //[515]: optional fields & funcs
607         CL_VM_FindEdictFieldOffsets();
608
609         // set time
610         *prog->time = cl.time;
611         csqc_frametime = 0;
612
613         prog->globals.client->mapname = PRVM_SetEngineString(cl.worldmodel->name);
614         prog->globals.client->player_localentnum = cl.playerentity;
615
616         // call the prog init
617         PRVM_ExecuteProgram((func_t) (PRVM_ED_FindFunction(CL_F_INIT) - prog->functions), CL_F_INIT);
618
619         PRVM_End;
620         csqc_loaded = true;
621
622         csqc_sv2csqcents = (unsigned short *)Mem_Alloc(csqc_mempool, MAX_EDICTS*sizeof(unsigned short));
623         memset(csqc_sv2csqcents, 0, MAX_EDICTS*sizeof(unsigned short));
624
625         cl.csqc_vidvars.drawcrosshair = false;
626         cl.csqc_vidvars.drawenginesbar = false;
627 }
628
629 void CL_VM_ShutDown (void)
630 {
631         Cmd_ClearCsqcFuncs();
632         Cvar_SetValueQuick(&csqc_progcrc, -1);
633         Cvar_SetValueQuick(&csqc_progsize, -1);
634         if(!csqc_loaded)
635                 return;
636         CSQC_BEGIN
637                 *prog->time = cl.time;
638                 PRVM_ExecuteProgram((func_t) (PRVM_ED_FindFunction(CL_F_SHUTDOWN) - prog->functions), CL_F_SHUTDOWN);
639                 PRVM_ResetProg();
640         CSQC_END
641         Con_Print("CSQC ^1unloaded\n");
642         csqc_loaded = false;
643         Mem_FreePool(&csqc_mempool);
644 }