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