]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - csprogs.c
fix broken demos with csqc code
[xonotic/darkplaces.git] / csprogs.c
index 152b747fb3b5cf99b6ba58235a06135635e90e35..203e107056862d9f5c0d712431874f543a85d34d 100644 (file)
--- a/csprogs.c
+++ b/csprogs.c
@@ -2,6 +2,9 @@
 #include "progsvm.h"
 #include "clprogdefs.h"
 #include "csprogs.h"
+#include "cl_collision.h"
+#include "snd_main.h"
+#include "clvm_cmds.h"
 
 //============================================================================
 // Client prog handling
 static prvm_prog_t *csqc_tmpprog;
 
 //[515]: these are required funcs
-#define CL_F_INIT                              "CSQC_Init"
-#define CL_F_INPUTEVENT                        "CSQC_InputEvent"
-#define CL_F_UPDATEVIEW                        "CSQC_UpdateView"
-#define CL_F_CONSOLECOMMAND            "CSQC_ConsoleCommand"
-#define CL_F_SHUTDOWN                  "CSQC_Shutdown"
-
-//[515]: these are optional
-#define CL_F_PARSE_TEMPENTITY  "CSQC_Parse_TempEntity" //[515]: very helpfull when you want to create your own particles/decals/etc for effects that allready exist
-#define CL_F_PARSE_STUFFCMD            "CSQC_Parse_StuffCmd"
-#define CL_F_PARSE_PRINT               "CSQC_Parse_Print"
-#define CL_F_PARSE_CENTERPRINT "CSQC_Parse_CenterPrint"
-#define CL_F_ENT_UPDATE                        "CSQC_Ent_Update"
-#define CL_F_ENT_REMOVE                        "CSQC_Ent_Remove"
-#define CL_F_EVENT                             "CSQC_Event"    //[515]: engine call this for its own needs
-                                                                                               //so csqc can do some things according to what engine it's running on
-                                                                                               //example: to say about edicts increase, whatever...
-
-#define CSQC_PRINTBUFFERLEN            8192    //[515]: enough ?
-
 static char *cl_required_func[] =
 {
-       CL_F_INIT,
-       CL_F_INPUTEVENT,
-       CL_F_UPDATEVIEW,
-       CL_F_CONSOLECOMMAND,
-       CL_F_SHUTDOWN
+       "CSQC_Init",
+       "CSQC_InputEvent",
+       "CSQC_UpdateView",
+       "CSQC_ConsoleCommand",
 };
 
 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
 
-unsigned int                   csqc_drawmask = 0;
-static char                            *csqc_printtextbuf = NULL;
-static unsigned short  *csqc_sv2csqcents;      //[515]: server entities numbers on client side. FIXME : make pointers instead of numbers ?
-
-static mfunction_t     *CSQC_Parse_TempEntity;
-static mfunction_t     *CSQC_Parse_StuffCmd;
-static mfunction_t     *CSQC_Parse_Print;
-static mfunction_t     *CSQC_Parse_CenterPrint;
-static mfunction_t     *CSQC_Ent_Update;
-static mfunction_t     *CSQC_Ent_Remove;
-static mfunction_t     *CSQC_Event;
-
-static int csqc_fieldoff_alpha;
-static int csqc_fieldoff_colormod;
-static int csqc_fieldoff_effects;
-int csqc_fieldoff_scale;
-int csqc_fieldoff_renderflags;
-int csqc_fieldoff_tag_entity;
-int csqc_fieldoff_tag_index;
-int csqc_fieldoff_dphitcontentsmask;
-
-qboolean csqc_loaded = false;
-
-vec3_t csqc_origin, csqc_angles;
-static double csqc_frametime = 0;
-int csqc_buttons;
-
-static mempool_t *csqc_mempool;
-
-static void CL_VM_FindEdictFieldOffsets (void)
-{
-       csqc_fieldoff_alpha                     = PRVM_ED_FindFieldOffset("alpha");
-       csqc_fieldoff_scale                     = PRVM_ED_FindFieldOffset("scale");
-       csqc_fieldoff_colormod          = PRVM_ED_FindFieldOffset("colormod");
-       csqc_fieldoff_renderflags       = PRVM_ED_FindFieldOffset("renderflags");
-       csqc_fieldoff_effects           = PRVM_ED_FindFieldOffset("effects");
-       csqc_fieldoff_tag_entity        = PRVM_ED_FindFieldOffset("tag_entity");
-       csqc_fieldoff_tag_index         = PRVM_ED_FindFieldOffset("tag_index");
-
-       CSQC_Parse_TempEntity           = PRVM_ED_FindFunction (CL_F_PARSE_TEMPENTITY);
-       CSQC_Parse_StuffCmd                     = PRVM_ED_FindFunction (CL_F_PARSE_STUFFCMD);
-       CSQC_Parse_Print                        = PRVM_ED_FindFunction (CL_F_PARSE_PRINT);
-       CSQC_Parse_CenterPrint          = PRVM_ED_FindFunction (CL_F_PARSE_CENTERPRINT);
-       CSQC_Ent_Update                         = PRVM_ED_FindFunction (CL_F_ENT_UPDATE);
-       CSQC_Ent_Remove                         = PRVM_ED_FindFunction (CL_F_ENT_REMOVE);
-       CSQC_Event                                      = PRVM_ED_FindFunction (CL_F_EVENT);
-
-       if(CSQC_Parse_Print)
-       {
-               csqc_printtextbuf = (char *)Mem_Alloc(csqc_mempool, CSQC_PRINTBUFFERLEN);
-               csqc_printtextbuf[0] = 0;
-       }
-}
-
+void CL_VM_Error (const char *format, ...) DP_FUNC_PRINTF(1);
 void CL_VM_Error (const char *format, ...)     //[515]: hope it will be never executed =)
 {
        char errorstring[4096];
@@ -108,40 +38,66 @@ void CL_VM_Error (const char *format, ...) //[515]: hope it will be never execut
 //     Con_Printf( "CL_VM_Error: %s\n", errorstring );
 
        PRVM_Crash();
-       csqc_loaded = false;
-       Mem_FreePool(&csqc_mempool);
+       cl.csqc_loaded = false;
 
-       Cvar_SetValueQuick(&csqc_progcrc, 0);
+       Cvar_SetValueQuick(&csqc_progcrc, -1);
+       Cvar_SetValueQuick(&csqc_progsize, -1);
 
 //     Host_AbortCurrentFrame();       //[515]: hmmm... if server says it needs csqc then client MUST disconnect
        Host_Error(va("CL_VM_Error: %s", errorstring));
 }
-
+void CL_VM_UpdateDmgGlobals (int dmg_take, int dmg_save, vec3_t dmg_origin)
+{
+       prvm_eval_t *val;
+       if(cl.csqc_loaded)
+       {
+               CSQC_BEGIN
+               val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_take);
+               if(val)
+                       val->_float = dmg_take;
+               val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_save);
+               if(val)
+                       val->_float = dmg_save;
+               val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_origin);
+               if(val)
+               {
+                       val->vector[0] = dmg_origin[0];
+                       val->vector[1] = dmg_origin[1];
+                       val->vector[2] = dmg_origin[2];
+               }
+               CSQC_END
+       }
+}
 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
 static void CSQC_SetGlobals (void)
 {
-       //extern cvar_t sv_accelerate, sv_friction, sv_gravity, sv_stopspeed, sv_maxspeed;
-
+       prvm_eval_t *val;
        CSQC_BEGIN
-               *prog->time = cl.time;
-               prog->globals.client->frametime = cl.time - csqc_frametime;
-               csqc_frametime = cl.time;
-               prog->globals.client->servercommandframe = cl.servermovesequence;
-               prog->globals.client->clientcommandframe = cl.movemessages;
+               prog->globals.client->time = cl.time;
+               prog->globals.client->frametime = max(0, cl.time - cl.oldtime);
+               prog->globals.client->servercommandframe = cls.servermovesequence;
+               prog->globals.client->clientcommandframe = cl.movecmd[0].sequence;
                VectorCopy(cl.viewangles, prog->globals.client->input_angles);
-               VectorCopy(cl.viewangles, csqc_angles);
-               prog->globals.client->input_buttons = csqc_buttons;
-               VectorSet(prog->globals.client->input_movevalues, cl.cmd.forwardmove, cl.cmd.sidemove, cl.cmd.upmove);
-               //VectorCopy(cl.movement_origin, csqc_origin);
-               VectorCopy(cl.entities[cl.viewentity].render.origin, csqc_origin);
-               VectorCopy(csqc_origin, prog->globals.client->pmove_org);
-               prog->globals.client->maxclients = cl.maxclients;
-               //VectorCopy(cl.movement_velocity, prog->globals.client->pmove_vel);
+               VectorCopy(cl.viewangles, cl.csqc_angles);
+               // // FIXME: this actually belongs into getinputstate().. [12/17/2007 Black]
+               prog->globals.client->input_buttons = cl.movecmd[0].buttons;
+               VectorSet(prog->globals.client->input_movevalues, cl.movecmd[0].forwardmove, cl.movecmd[0].sidemove, cl.movecmd[0].upmove);
+               //VectorCopy(cl.movement_origin, cl.csqc_origin);
+               Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, cl.csqc_origin);
+
+               // LordHavoc: Spike says not to do this, but without pmove_org the
+               // CSQC is useless as it can't alter the view origin without
+               // completely replacing it
+               VectorCopy(cl.csqc_origin, prog->globals.client->pmove_org);
                VectorCopy(cl.velocity, prog->globals.client->pmove_vel);
+
+               if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.view_angles)))
+                       VectorCopy(cl.viewangles, val->vector);
+               prog->globals.client->maxclients = cl.maxclients;
        CSQC_END
 }
 
-static void CSQC_Predraw (prvm_edict_t *ed)
+void CSQC_Predraw (prvm_edict_t *ed)
 {
        int b;
        if(!ed->fields.client->predraw)
@@ -152,11 +108,11 @@ static void CSQC_Predraw (prvm_edict_t *ed)
        prog->globals.client->self = b;
 }
 
-static void CSQC_Think (prvm_edict_t *ed)
+void CSQC_Think (prvm_edict_t *ed)
 {
        int b;
        if(ed->fields.client->think)
-       if(ed->fields.client->nextthink && ed->fields.client->nextthink <= *prog->time)
+       if(ed->fields.client->nextthink && ed->fields.client->nextthink <= prog->globals.client->time)
        {
                ed->fields.client->nextthink = 0;
                b = prog->globals.client->self;
@@ -166,177 +122,185 @@ static void CSQC_Think (prvm_edict_t *ed)
        }
 }
 
-//[515]: weird too
-static qboolean CSQC_EdictToEntity (prvm_edict_t *ed, entity_t *e)
+extern cvar_t cl_noplayershadow;
+qboolean CSQC_AddRenderEdict(prvm_edict_t *ed)
 {
-       int i;
+       int renderflags;
+       int c;
+       float scale;
        prvm_eval_t *val;
+       entity_render_t *entrender;
+       dp_model_t *model;
+       matrix4x4_t tagmatrix, matrix2;
 
-       i = (int)ed->fields.client->modelindex;
-       e->state_current.modelindex = 0;
-       if(i >= MAX_MODELS || i <= -MAX_MODELS) //[515]: make work as error ?
-       {
-               Con_Print("CSQC_EdictToEntity: modelindex >= MAX_MODELS\n");
-               ed->fields.client->modelindex = 0;
-       }
-       else
-               e->state_current.modelindex = i;
-       if(!e->state_current.modelindex)
+       model = CL_GetModelFromEdict(ed);
+       if (!model)
                return false;
 
-       e->state_current.time = cl.time;
+       entrender = CL_NewTempEntity();
+       if (!entrender)
+               return false;
 
-       i = 0;
-       if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_renderflags)) && val->_float)
+       entrender->model = model;
+       entrender->skinnum = (int)ed->fields.client->skin;
+       entrender->effects |= entrender->model->effects;
+       scale = 1;
+       renderflags = 0;
+       if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.renderflags)) && val->_float)     renderflags = (int)val->_float;
+       if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.alpha)) && val->_float)           entrender->alpha = val->_float;
+       if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.scale)) && val->_float)           entrender->scale = scale = val->_float;
+       if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.colormod)) && VectorLength2(val->vector)) VectorCopy(val->vector, entrender->colormod);
+       if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.effects)) && val->_float) entrender->effects |= (int)val->_float;
+       if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_entity)) && val->edict)
        {
-               i = (int)val->_float;
-               if(i & RF_VIEWMODEL)    e->state_current.flags |= RENDER_VIEWMODEL;
-               if(i & RF_EXTERNALMODEL)e->state_current.flags |= RENDER_EXTERIORMODEL;
-               if(i & RF_DEPTHHACK)    e->state_current.effects |= EF_NODEPTHTEST;
-               if(i & RF_ADDITIVE)             e->state_current.effects |= EF_ADDITIVE;
+               int tagentity;
+               int tagindex = 0;
+               tagentity = val->edict;
+               if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_index)) && val->_float)
+                       tagindex = (int)val->_float;
+               CL_GetTagMatrix (&tagmatrix, PRVM_PROG_TO_EDICT(tagentity), tagindex);
        }
+       else
+               Matrix4x4_CreateIdentity(&tagmatrix);
 
-       if(i & RF_USEAXIS)      //FIXME!!!
-               VectorCopy(ed->fields.client->angles, e->persistent.newangles);
+       if (renderflags & RF_USEAXIS)
+       {
+               vec3_t left;
+               VectorNegate(prog->globals.client->v_right, left);
+               Matrix4x4_FromVectors(&matrix2, prog->globals.client->v_forward, left, prog->globals.client->v_up, ed->fields.client->origin);
+               Matrix4x4_Scale(&matrix2, scale, 1);
+       }
        else
-               VectorCopy(ed->fields.client->angles, e->persistent.newangles);
-
-       VectorCopy(ed->fields.client->origin, e->persistent.neworigin);
-       VectorCopy(ed->fields.client->origin, e->state_current.origin);
-       e->state_current.colormap = (int)ed->fields.client->colormap;
-       e->state_current.effects = (int)ed->fields.client->effects;
-       e->state_current.frame = (int)ed->fields.client->frame;
-       e->state_current.skin = (int)ed->fields.client->skin;
-
-       if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_alpha)) && val->_float)             e->state_current.alpha = (int)(val->_float*255);
-       if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_scale)) && val->_float)             e->state_current.scale = (int)(val->_float*16);
-       if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_colormod)) && VectorLength2(val->vector))   {int j;for (j = 0;j < 3;j++) e->state_current.colormod[j] = (unsigned char)bound(0, val->vector[j] * 32.0f, 255);}
-       if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_effects)) && val->_float)   e->state_current.effects = (int)val->_float;
-       if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_tag_entity)) && val->edict)
        {
-               e->state_current.tagentity = val->edict;
-               if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_tag_index)) && val->_float)
-                       e->state_current.tagindex = (int)val->_float;
+               vec3_t angles;
+               VectorCopy(ed->fields.client->angles, angles);
+               // if model is alias, reverse pitch direction
+               if (entrender->model->type == mod_alias)
+                       angles[0] = -angles[0];
+
+               // set up the render matrix
+               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);
        }
 
-       return true;
-}
-
-void CSQC_ClearCSQCEntities (void)
-{
-       memset(cl.csqcentities_active, 0, sizeof(cl.csqcentities_active));
-       cl.num_csqcentities = 0;
-       csqc_drawmask = 0;
-}
-
-void CL_ExpandCSQCEntities (int num);
-
-void CSQC_RelinkCSQCEntities (void)
-{
-       int                     i;
-       entity_t        *e;
-       prvm_edict_t *ed;
-
-       *prog->time = cl.time;
-       for(i=1;i<prog->num_edicts;i++)
+       // set up the animation data
+       // self.frame is the interpolation target (new frame)
+       // self.frame1time is the animation base time for the interpolation target
+       // self.frame2 is the interpolation start (previous frame)
+       // self.frame2time is the animation base time for the interpolation start
+       entrender->frame1 = entrender->frame2 = ed->fields.client->frame;
+       if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2))) entrender->frame2 = val->_float;
+       if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame1time))) entrender->frame2time = val->_float;
+       if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2time))) entrender->frame1time = val->_float;
+       if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac))) entrender->framelerp = val->_float;
+
+       // concat the matrices to make the entity relative to its tag
+       Matrix4x4_Concat(&entrender->matrix, &tagmatrix, &matrix2);
+
+       if(renderflags)
        {
-               if(i >= cl.max_csqcentities)
-                       CL_ExpandCSQCEntities(i);
-
-               e = &cl.csqcentities[i];
-               ed = &prog->edicts[i];
-               if(ed->priv.required->free)
-               {
-                       e->state_current.active = false;
-                       cl.csqcentities_active[i] = false;
-                       continue;
-               }
-               VectorAdd(ed->fields.client->origin, ed->fields.client->mins, ed->fields.client->absmin);
-               VectorAdd(ed->fields.client->origin, ed->fields.client->maxs, ed->fields.client->absmax);
-               CSQC_Think(ed);
-               if(ed->priv.required->free)
-               {
-                       e->state_current.active = false;
-                       cl.csqcentities_active[i] = false;
-                       continue;
-               }
-               CSQC_Predraw(ed);
-               if(ed->priv.required->free)
-               {
-                       e->state_current.active = false;
-                       cl.csqcentities_active[i] = false;
-                       continue;
-               }
-               if(!cl.csqcentities_active[i])
-               if(!((int)ed->fields.client->drawmask & csqc_drawmask))
-                       continue;
-
-               e->state_previous       = e->state_current;
-               e->state_current        = defaultstate;
-               if((cl.csqcentities_active[i] = CSQC_EdictToEntity(ed, e)))
-               {
-                       if(!e->state_current.active)
-                       {
-                               if(!e->state_previous.active)
-                                       VectorCopy(ed->fields.client->origin, e->persistent.trail_origin);//[515]: hack to make good gibs =/
-                               e->state_previous = e->state_current;
-                               e->state_current.active = true;
-                       }
-                       e->persistent.lerpdeltatime = 0;//prog->globals.client->frametime;
-                       cl.num_csqcentities++;
-               }
+               if(renderflags & RF_VIEWMODEL)  entrender->flags |= RENDER_VIEWMODEL;
+               if(renderflags & RF_EXTERNALMODEL)entrender->flags |= RENDER_EXTERIORMODEL;
+               if(renderflags & RF_DEPTHHACK)  entrender->effects |= EF_NODEPTHTEST;
+               if(renderflags & RF_ADDITIVE)           entrender->effects |= EF_ADDITIVE;
        }
-}
 
-//[515]: omfg... it's all weird =/
-void CSQC_AddEntity (int n)
-{
-       cl.csqcentities_active[n] = true;
+       c = (int)ed->fields.client->colormap;
+       if (c <= 0)
+               CL_SetEntityColormapColors(entrender, -1);
+       else if (c <= cl.maxclients && cl.scores != NULL)
+               CL_SetEntityColormapColors(entrender, cl.scores[c-1].colors);
+       else
+               CL_SetEntityColormapColors(entrender, c);
+
+       // either fullbright or lit
+       if (!(entrender->effects & EF_FULLBRIGHT) && !r_fullbright.integer)
+               entrender->flags |= RENDER_LIGHT;
+       // hide player shadow during intermission or nehahra movie
+       if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
+        &&  (entrender->alpha >= 1)
+        && !(entrender->flags & RENDER_VIEWMODEL)
+        && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
+               entrender->flags |= RENDER_SHADOW;
+       if (entrender->flags & RENDER_VIEWMODEL)
+               entrender->flags |= RENDER_NOSELFSHADOW;
+
+       // make the other useful stuff
+       CL_UpdateRenderEntity(entrender);
+
+       return true;
 }
 
-qboolean CL_VM_InputEvent (qboolean pressed, int key)
+qboolean CL_VM_InputEvent (qboolean down, int key, int ascii)
 {
        qboolean r;
-       if(!csqc_loaded)
+
+       if(!cl.csqc_loaded)
                return false;
+
        CSQC_BEGIN
-               *prog->time = cl.time;
-               PRVM_G_FLOAT(OFS_PARM0) = pressed;
-               PRVM_G_FLOAT(OFS_PARM1) = key;
-               PRVM_ExecuteProgram (prog->globals.client->CSQC_InputEvent, CL_F_INPUTEVENT);
-               r = CSQC_RETURNVAL;
+               if (!prog->funcoffsets.CSQC_InputEvent)
+                       r = false;
+               else
+               {
+                       prog->globals.client->time = cl.time;
+                       prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
+                       PRVM_G_FLOAT(OFS_PARM0) = !down; // 0 is down, 1 is up
+                       PRVM_G_FLOAT(OFS_PARM1) = key;
+                       PRVM_G_FLOAT(OFS_PARM2) = ascii;
+                       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_InputEvent, "QC function CSQC_InputEvent is missing");
+                       r = CSQC_RETURNVAL;
+               }
        CSQC_END
        return r;
 }
 
 qboolean CL_VM_UpdateView (void)
 {
+       vec3_t emptyvector;
+       emptyvector[0] = 0;
+       emptyvector[1] = 0;
+       emptyvector[2] = 0;
 //     vec3_t oldangles;
-       if(!csqc_loaded)
+       if(!cl.csqc_loaded)
                return false;
        CSQC_BEGIN
                //VectorCopy(cl.viewangles, oldangles);
-               *prog->time = cl.time;
+               prog->globals.client->time = cl.time;
+               prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
                CSQC_SetGlobals();
-               csqc_drawmask = 0;
-               cl.num_csqcentities = 0;
-               PRVM_ExecuteProgram (prog->globals.client->CSQC_UpdateView, CL_F_UPDATEVIEW);
+               // clear renderable entity and light lists to prevent crashes if the
+               // CSQC_UpdateView function does not call R_ClearScene as it should
+               r_refdef.scene.numentities = 0;
+               r_refdef.scene.numlights = 0;
+               // pass in width and height as parameters (EXT_CSQC_1)
+               PRVM_G_FLOAT(OFS_PARM0) = vid.width;
+               PRVM_G_FLOAT(OFS_PARM1) = vid.height;
+               PRVM_ExecuteProgram(prog->funcoffsets.CSQC_UpdateView, "QC function CSQC_UpdateView is missing");
                //VectorCopy(oldangles, cl.viewangles);
+               // Dresk : Reset Dmg Globals Here
+               CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
        CSQC_END
-       csqc_frame = false;
        return true;
 }
 
+extern sizebuf_t vm_tempstringsbuf;
 qboolean CL_VM_ConsoleCommand (const char *cmd)
 {
-       qboolean r;
-       if(!csqc_loaded)
+       int restorevm_tempstringsbuf_cursize;
+       qboolean r = false;
+       if(!cl.csqc_loaded)
                return false;
        CSQC_BEGIN
-               *prog->time = cl.time;
-               PRVM_G_INT(OFS_PARM0) = PRVM_SetEngineString(cmd);
-               PRVM_ExecuteProgram (prog->globals.client->CSQC_ConsoleCommand, CL_F_CONSOLECOMMAND);
+       if (prog->funcoffsets.CSQC_ConsoleCommand)
+       {
+               prog->globals.client->time = cl.time;
+               prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
+               restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
+               PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
+               PRVM_ExecuteProgram(prog->funcoffsets.CSQC_ConsoleCommand, "QC function CSQC_ConsoleCommand is missing");
+               vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
                r = CSQC_RETURNVAL;
+       }
        CSQC_END
        return r;
 }
@@ -344,108 +308,233 @@ qboolean CL_VM_ConsoleCommand (const char *cmd)
 qboolean CL_VM_Parse_TempEntity (void)
 {
        int                     t;
-       qboolean        r;
-       if(!csqc_loaded || !CSQC_Parse_TempEntity)
+       qboolean        r = false;
+       if(!cl.csqc_loaded)
                return false;
-       t = msg_readcount;
        CSQC_BEGIN
-               *prog->time = cl.time;
-               PRVM_ExecuteProgram ((func_t)(CSQC_Parse_TempEntity - prog->functions), CL_F_PARSE_TEMPENTITY);
-               r = CSQC_RETURNVAL;
-       CSQC_END
-       if(!r)
+       if(prog->funcoffsets.CSQC_Parse_TempEntity)
        {
-               msg_readcount = t;
-               msg_badread = false;
+               t = msg_readcount;
+               prog->globals.client->time = cl.time;
+               prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
+               PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_TempEntity, "QC function CSQC_Parse_TempEntity is missing");
+               r = CSQC_RETURNVAL;
+               if(!r)
+               {
+                       msg_readcount = t;
+                       msg_badread = false;
+               }
        }
+       CSQC_END
        return r;
 }
 
 void CL_VM_Parse_StuffCmd (const char *msg)
 {
-       if(!csqc_loaded)        //[515]: add more here
+       int restorevm_tempstringsbuf_cursize;
        if(msg[0] == 'c')
        if(msg[1] == 's')
        if(msg[2] == 'q')
        if(msg[3] == 'c')
        {
-               Cvar_SetQuick(&csqc_progcrc, "0");
-               csqc_progcrc.flags = 0;
+               // if this is setting a csqc variable, deprotect csqc_progcrc
+               // temporarily so that it can be set by the cvar command,
+               // and then reprotect it afterwards
+               int crcflags = csqc_progcrc.flags;
+               int sizeflags = csqc_progcrc.flags;
+               csqc_progcrc.flags &= ~CVAR_READONLY;
+               csqc_progsize.flags &= ~CVAR_READONLY;
                Cmd_ExecuteString (msg, src_command);
-               csqc_progcrc.flags = CVAR_READONLY;
+               csqc_progcrc.flags = crcflags;
+               csqc_progsize.flags = sizeflags;
                return;
        }
-       if(!csqc_loaded || !CSQC_Parse_StuffCmd)
+       if(!cl.csqc_loaded)
        {
                Cbuf_AddText(msg);
                return;
        }
        CSQC_BEGIN
-               *prog->time = cl.time;
-               PRVM_G_INT(OFS_PARM0) = PRVM_SetEngineString(msg);
-               PRVM_ExecuteProgram ((func_t)(CSQC_Parse_StuffCmd - prog->functions), CL_F_PARSE_STUFFCMD);
+       if(prog->funcoffsets.CSQC_Parse_StuffCmd)
+       {
+               prog->globals.client->time = cl.time;
+               prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
+               restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
+               PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
+               PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_StuffCmd, "QC function CSQC_Parse_StuffCmd is missing");
+               vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
+       }
+       else
+               Cbuf_AddText(msg);
        CSQC_END
 }
 
 static void CL_VM_Parse_Print (const char *msg)
 {
-       CSQC_BEGIN
-               *prog->time = cl.time;
-               PRVM_G_INT(OFS_PARM0) = PRVM_SetEngineString(msg);
-               PRVM_ExecuteProgram ((func_t)(CSQC_Parse_Print - prog->functions), CL_F_PARSE_PRINT);
-       CSQC_END
+       int restorevm_tempstringsbuf_cursize;
+       prog->globals.client->time = cl.time;
+       prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
+       restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
+       PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
+       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_Print, "QC function CSQC_Parse_Print is missing");
+       vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
 }
 
 void CSQC_AddPrintText (const char *msg)
 {
        size_t i;
-       if(!csqc_loaded || !CSQC_Parse_Print)
+       if(!cl.csqc_loaded)
        {
                Con_Print(msg);
                return;
        }
-       // FIXME: is this bugged?
-       i = strlen(msg)-1;
-       if(msg[i] != '\n' && msg[i] != '\r')
+       CSQC_BEGIN
+       if(prog->funcoffsets.CSQC_Parse_Print)
        {
-               if(strlen(csqc_printtextbuf)+i >= CSQC_PRINTBUFFERLEN)
+               // FIXME: is this bugged?
+               i = strlen(msg)-1;
+               if(msg[i] != '\n' && msg[i] != '\r')
                {
-                       CL_VM_Parse_Print(csqc_printtextbuf);
-                       csqc_printtextbuf[0] = 0;
+                       if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
+                       {
+                               CL_VM_Parse_Print(cl.csqc_printtextbuf);
+                               cl.csqc_printtextbuf[0] = 0;
+                       }
+                       else
+                               strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
+                       return;
                }
-               else
-                       strcat(csqc_printtextbuf, msg);
-               return;
+               strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
+               CL_VM_Parse_Print(cl.csqc_printtextbuf);
+               cl.csqc_printtextbuf[0] = 0;
        }
-       strcat(csqc_printtextbuf, msg);
-       CL_VM_Parse_Print(csqc_printtextbuf);
-       csqc_printtextbuf[0] = 0;
+       else
+               Con_Print(msg);
+       CSQC_END
 }
 
 void CL_VM_Parse_CenterPrint (const char *msg)
 {
-       if(!csqc_loaded || !CSQC_Parse_CenterPrint)
+       int restorevm_tempstringsbuf_cursize;
+       if(!cl.csqc_loaded)
        {
-               SCR_CenterPrint((char*)msg);
+               SCR_CenterPrint(msg);
                return;
        }
        CSQC_BEGIN
-               *prog->time = cl.time;
-               PRVM_G_INT(OFS_PARM0) = PRVM_SetEngineString(msg);
-               PRVM_ExecuteProgram ((func_t)(CSQC_Parse_CenterPrint - prog->functions), CL_F_PARSE_CENTERPRINT);
+       if(prog->funcoffsets.CSQC_Parse_CenterPrint)
+       {
+               prog->globals.client->time = cl.time;
+               prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
+               restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
+               PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
+               PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_CenterPrint, "QC function CSQC_Parse_CenterPrint is missing");
+               vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
+       }
+       else
+               SCR_CenterPrint(msg);
        CSQC_END
 }
 
+void CL_VM_UpdateIntermissionState (int intermission)
+{
+       prvm_eval_t *val;
+       if(cl.csqc_loaded)
+       {
+               CSQC_BEGIN
+               val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.intermission);
+               if(val)
+                       val->_float = intermission;
+               CSQC_END
+       }
+}
+void CL_VM_UpdateShowingScoresState (int showingscores)
+{
+       prvm_eval_t *val;
+       if(cl.csqc_loaded)
+       {
+               CSQC_BEGIN
+               val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.sb_showscores);
+               if(val)
+                       val->_float = showingscores;
+               CSQC_END
+       }
+}
+qboolean CL_VM_Event_Sound(int sound_num, int volume, int channel, float attenuation, int ent, vec3_t pos)
+{
+       qboolean r = false;
+       if(cl.csqc_loaded)
+       {
+               CSQC_BEGIN
+               if(prog->funcoffsets.CSQC_Event_Sound)
+               {
+                       prog->globals.client->time = cl.time;
+                       prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
+                       PRVM_G_FLOAT(OFS_PARM0) = ent;
+                       PRVM_G_FLOAT(OFS_PARM1) = channel;
+                       PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(cl.sound_name[sound_num] );
+                       PRVM_G_FLOAT(OFS_PARM3) = volume;
+                       PRVM_G_FLOAT(OFS_PARM4) = attenuation;
+                       VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
+                       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event_Sound, "QC function CSQC_Event_Sound is missing");
+                       r = CSQC_RETURNVAL;
+               }
+               CSQC_END
+       }
+
+       return r;
+}
+void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
+{
+       // Avoid global names for clean(er) coding
+       int localcoop;
+       int localdeathmatch;
+
+       prvm_eval_t *val;
+       if(cl.csqc_loaded)
+       {
+               if(gametype == GAME_COOP)
+               {
+                       localcoop = 1;
+                       localdeathmatch = 0;
+               }
+               else
+               if(gametype == GAME_DEATHMATCH)
+               {
+                       localcoop = 0;
+                       localdeathmatch = 1;
+               }
+               else
+               {
+                       // How did the ServerInfo send an unknown gametype?
+                       // Better just assign the globals as 0...
+                       localcoop = 0;
+                       localdeathmatch = 0;
+               }
+               CSQC_BEGIN
+               val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.coop);
+               if(val)
+                       val->_float = localcoop;
+               val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.deathmatch);
+               if(val)
+                       val->_float = localdeathmatch;
+               CSQC_END
+       }
+}
 float CL_VM_Event (float event)                //[515]: needed ? I'd say "YES", but don't know for what :D
 {
-       float r;
-       if(!csqc_loaded || !CSQC_Event)
+       float r = 0;
+       if(!cl.csqc_loaded)
                return 0;
        CSQC_BEGIN
-               *prog->time = cl.time;
+       if(prog->funcoffsets.CSQC_Event)
+       {
+               prog->globals.client->time = cl.time;
+               prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
                PRVM_G_FLOAT(OFS_PARM0) = event;
-               PRVM_ExecuteProgram ((func_t)(CSQC_Event - prog->functions), CL_F_EVENT);
+               PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event, "QC function CSQC_Event is missing");
                r = CSQC_RETURNVAL;
+       }
        CSQC_END
        return r;
 }
@@ -453,76 +542,233 @@ float CL_VM_Event (float event)          //[515]: needed ? I'd say "YES", but don't know
 void CSQC_ReadEntities (void)
 {
        unsigned short entnum, oldself, realentnum;
+       if(!cl.csqc_loaded)
+       {
+               Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
+               return;
+       }
+
        CSQC_BEGIN
-               *prog->time = cl.time;
+               prog->globals.client->time = cl.time;
                oldself = prog->globals.client->self;
                while(1)
                {
                        entnum = MSG_ReadShort();
-                       if(!entnum)
+                       if(!entnum || msg_badread)
                                return;
                        realentnum = entnum & 0x7FFF;
-                       prog->globals.client->self = csqc_sv2csqcents[realentnum];
+                       prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum];
                        if(entnum & 0x8000)
                        {
                                if(prog->globals.client->self)
                                {
-                                       PRVM_ExecuteProgram((func_t)(CSQC_Ent_Remove - prog->functions), CL_F_ENT_REMOVE);
-                                       csqc_sv2csqcents[realentnum] = 0;
+                                       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Remove, "QC function CSQC_Ent_Remove is missing");
+                                       cl.csqc_server2csqcentitynumber[realentnum] = 0;
                                }
                                else
-                                       Con_Printf("Smth bad happens in csqc...\n");    //[515]: never happens ?
+                               {
+                                       // LordHavoc: removing an entity that is already gone on
+                                       // the csqc side is possible for legitimate reasons (such
+                                       // as a repeat of the remove message), so no warning is
+                                       // needed
+                                       //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
+                               }
                        }
                        else
                        {
                                if(!prog->globals.client->self)
                                {
-                                       prvm_edict_t    *ed;
-                                       ed = PRVM_ED_Alloc();
-                                       ed->fields.client->entnum = realentnum;
-                                       prog->globals.client->self = csqc_sv2csqcents[realentnum] = PRVM_EDICT_TO_PROG(ed);
+                                       if(!prog->funcoffsets.CSQC_Ent_Spawn)
+                                       {
+                                               prvm_edict_t    *ed;
+                                               ed = PRVM_ED_Alloc();
+                                               ed->fields.client->entnum = realentnum;
+                                               prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
+                                       }
+                                       else
+                                       {
+                                               // entity( float entnum ) CSQC_Ent_Spawn;
+                                               // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
+                                               PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
+                                               // make sure no one gets wrong ideas
+                                               prog->globals.client->self = 0;
+                                               PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Spawn, "QC function CSQC_Ent_Spawn is missing");
+                                               prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
+                                       }
                                        PRVM_G_FLOAT(OFS_PARM0) = 1;
+                                       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
                                }
-                               else
+                               else {
                                        PRVM_G_FLOAT(OFS_PARM0) = 0;
-                               PRVM_ExecuteProgram((func_t)(CSQC_Ent_Update - prog->functions), CL_F_ENT_UPDATE);
+                                       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
+                               }
                        }
                }
                prog->globals.client->self = oldself;
        CSQC_END
 }
 
+void CL_VM_CB_BeginIncreaseEdicts(void)
+{
+       // links don't survive the transition, so unlink everything
+       World_UnlinkAll(&cl.world);
+}
+
+void CL_VM_CB_EndIncreaseEdicts(void)
+{
+       int i;
+       prvm_edict_t *ent;
+
+       // link every entity except world
+       for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
+               if (!ent->priv.server->free)
+                       CL_LinkEdict(ent);
+}
+
+void CL_VM_CB_InitEdict(prvm_edict_t *e)
+{
+       e->priv.server->move = false; // don't move on first frame
+}
+
+void CL_VM_CB_FreeEdict(prvm_edict_t *ed)
+{
+       World_UnlinkEdict(ed);
+       memset(ed->fields.client, 0, sizeof(*ed->fields.client));
+}
+
+void CL_VM_CB_CountEdicts(void)
+{
+       int             i;
+       prvm_edict_t    *ent;
+       int             active = 0, models = 0, solid = 0;
+
+       for (i=0 ; i<prog->num_edicts ; i++)
+       {
+               ent = PRVM_EDICT_NUM(i);
+               if (ent->priv.server->free)
+                       continue;
+               active++;
+               if (ent->fields.client->solid)
+                       solid++;
+               if (ent->fields.client->model)
+                       models++;
+       }
+
+       Con_Printf("num_edicts:%3i\n", prog->num_edicts);
+       Con_Printf("active    :%3i\n", active);
+       Con_Printf("view      :%3i\n", models);
+       Con_Printf("touch     :%3i\n", solid);
+}
+
+qboolean CL_VM_CB_LoadEdict(prvm_edict_t *ent)
+{
+       return true;
+}
+
 void Cmd_ClearCsqcFuncs (void);
 
+// returns true if the packet is valid, false if end of file is reached
+// used for dumping the CSQC download into demo files
+qboolean MakeDownloadPacket(const char *filename, unsigned char *data, unsigned long len, int crc, int cnt, sizebuf_t *buf, int protocol)
+{
+       int packetsize = buf->maxsize - 7; // byte short long
+       int npackets = (len + packetsize - 1) / (packetsize);
+
+       if(protocol == PROTOCOL_QUAKEWORLD)
+               return false; // CSQC can't run in QW anyway
+
+       SZ_Clear(buf);
+       if(cnt == 0)
+       {
+               MSG_WriteByte(buf, svc_stufftext);
+               MSG_WriteString(buf, va("\ncl_downloadbegin %lu %s\n", len, filename));
+               return true;
+       }
+       else if(cnt >= 1 && cnt <= npackets)
+       {
+               unsigned long thispacketoffset = (cnt - 1) * packetsize;
+               int thispacketsize = len - thispacketoffset;
+               if(thispacketsize > packetsize)
+                       thispacketsize = packetsize;
+
+               MSG_WriteByte(buf, svc_downloaddata);
+               MSG_WriteLong(buf, thispacketoffset);
+               MSG_WriteShort(buf, thispacketsize);
+               SZ_Write(buf, data + thispacketoffset, thispacketsize);
+
+               return true;
+       }
+       else if(cnt == npackets + 1)
+       {
+               MSG_WriteByte(buf, svc_stufftext);
+               MSG_WriteString(buf, va("\ncl_downloadfinished %lu %d\n", len, crc));
+               return true;
+       }
+       return false;
+}
+
 void CL_VM_Init (void)
 {
-       entity_t *ent;
+       const char* csprogsfn;
+       unsigned char *csprogsdata;
+       fs_offset_t csprogsdatasize;
+       int csprogsdatacrc, requiredcrc;
+       int requiredsize;
+       prvm_eval_t *val;
+
+       // reset csqc_progcrc after reading it, so that changing servers doesn't
+       // expect csqc on the next server
+       requiredcrc = csqc_progcrc.integer;
+       requiredsize = csqc_progsize.integer;
+       Cvar_SetValueQuick(&csqc_progcrc, -1);
+       Cvar_SetValueQuick(&csqc_progsize, -1);
 
-       csqc_loaded = false;
-       memset(cl.csqc_model_precache, 0, sizeof(cl.csqc_model_precache));
-       memset(&cl.csqc_vidvars, true, sizeof(csqc_vidvars_t));
+       // if the server is not requesting a csprogs, then we're done here
+       if (requiredcrc < 0)
+               return;
 
-       if(!FS_FileExists(csqc_progname.string))
+       // see if the requested csprogs.dat file matches the requested crc
+       csprogsdatacrc = -1;
+       csprogsfn = va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
+       csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
+       if (!csprogsdata)
        {
-               if(!sv.active && csqc_progcrc.integer)
+               csprogsfn = csqc_progname.string;
+               csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
+       }
+       if (csprogsdata)
+       {
+               csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
+               if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
                {
-                       Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
-                       CL_Disconnect();
+                       if (cls.demoplayback)
+                       {
+                               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);
+                               // Mem_Free(csprogsdata);
+                               // return;
+                               // We WANT to continue here, and play the demo with different csprogs!
+                               // After all, this is just a warning. Sure things may go wrong from here.
+                       }
+                       else
+                       {
+                               Mem_Free(csprogsdata);
+                               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);
+                               CL_Disconnect();
+                               return;
+                       }
                }
-               return;
        }
        else
        {
-               if (developer.integer < 100)
-               {
-                       Con_DPrintf("CL_VM_Init: CSQC is broken, and is not being loaded because developer is less than 100.\n");
-                       return;
-               }
-               if(!sv.active && !csqc_progcrc.integer) //[515]: because cheaters may use csqc while server didn't allowed it !
+               if (requiredcrc >= 0)
                {
-                       Con_Printf("CL_VM_Init: server didn't sent CSQC crc, so CSQC is disabled\n");
-                       return;
+                       if (cls.demoplayback)
+                               Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
+                       else
+                               Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
+                       CL_Disconnect();
                }
+               return;
        }
 
        PRVM_Begin;
@@ -532,88 +778,108 @@ void CL_VM_Init (void)
        prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
        prog->headercrc = CL_PROGHEADER_CRC;
        prog->edictprivate_size = 0; // no private struct used
-       prog->name = csqc_progname.string;
+       prog->name = CL_NAME;
        prog->num_edicts = 1;
+       prog->max_edicts = 512;
        prog->limit_edicts = CL_MAX_EDICTS;
-       prog->extensionstring = vm_cl_extensions;
+       prog->reserved_edicts = 0;
+       prog->edictprivate_size = sizeof(edict_engineprivate_t);
+       // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
+       prog->extensionstring = vm_sv_extensions;
        prog->builtins = vm_cl_builtins;
        prog->numbuiltins = vm_cl_numbuiltins;
+       prog->begin_increase_edicts = CL_VM_CB_BeginIncreaseEdicts;
+       prog->end_increase_edicts = CL_VM_CB_EndIncreaseEdicts;
+       prog->init_edict = CL_VM_CB_InitEdict;
+       prog->free_edict = CL_VM_CB_FreeEdict;
+       prog->count_edicts = CL_VM_CB_CountEdicts;
+       prog->load_edict = CL_VM_CB_LoadEdict;
        prog->init_cmd = VM_CL_Cmd_Init;
        prog->reset_cmd = VM_CL_Cmd_Reset;
        prog->error_cmd = CL_VM_Error;
 
-       PRVM_LoadProgs(csqc_progname.string, cl_numrequiredfunc, cl_required_func, 0, NULL);
-
-       if(!sv.active && !cls.demoplayback && prog->filecrc != (unsigned short)csqc_progcrc.integer)
-       {
-               Con_Printf("^1Your CSQC version differs from server's one (%i!=%i)\n", prog->filecrc, csqc_progcrc.integer);
-               PRVM_ResetProg();
-               CL_Disconnect();
-               return;
-       }
+       PRVM_LoadProgs(csprogsfn, cl_numrequiredfunc, cl_required_func, 0, NULL, 0, NULL);
 
-       if(prog->loaded)
+       if (!prog->loaded)
        {
-               Cvar_SetValueQuick(&csqc_progcrc, prog->filecrc);
-               Con_Printf("CSQC ^5loaded (crc=%i)\n", csqc_progcrc.integer);
-       }
-       else
-       {
-               CL_VM_Error("CSQC ^2failed to load\n");
+               CL_VM_Error("CSQC %s ^2failed to load\n", csprogsfn);
                if(!sv.active)
                        CL_Disconnect();
+               Mem_Free(csprogsdata);
                return;
        }
 
-       csqc_mempool = Mem_AllocPool("CSQC", 0, NULL);
+       Con_Printf("CSQC %s ^5loaded (crc=%i, size=%i)\n", csprogsfn, csprogsdatacrc, (int)csprogsdatasize);
 
-       //[515]: optional fields & funcs
-       CL_VM_FindEdictFieldOffsets();
+       if(cls.demorecording)
+       {
+               if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
+               {
+                       int i;
+                       char buf[NET_MAXMESSAGE];
+                       sizebuf_t sb;
+                       unsigned char *demobuf; fs_offset_t demofilesize;
+
+                       sb.data = (void *) buf;
+                       sb.maxsize = sizeof(buf);
+                       i = 0;
+
+                       CL_CutDemo(&demobuf, &demofilesize);
+                       while(MakeDownloadPacket(csqc_progname.string, csprogsdata, csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
+                               CL_WriteDemoMessage(&sb);
+                       CL_PasteDemo(&demobuf, &demofilesize);
+
+                       cls.demo_lastcsprogssize = csprogsdatasize;
+                       cls.demo_lastcsprogscrc = csprogsdatacrc;
+               }
+       }
+       Mem_Free(csprogsdata);
+
+       // check if OP_STATE animation is possible in this dat file
+       if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
+               prog->flag |= PRVM_OP_STATE;
 
        // set time
-       *prog->time = cl.time;
-       csqc_frametime = 0;
+       prog->globals.client->time = cl.time;
+       prog->globals.client->self = 0;
 
-       prog->globals.client->mapname = PRVM_SetEngineString(cl.worldmodel->name);
+       prog->globals.client->mapname = cl.worldmodel ? PRVM_SetEngineString(cl.worldmodel->name) : PRVM_SetEngineString("");
        prog->globals.client->player_localentnum = cl.playerentity;
 
+       // set map description (use world entity 0)
+       val = PRVM_EDICTFIELDVALUE(prog->edicts, prog->fieldoffsets.message);
+       if(val)
+               val->string = PRVM_SetEngineString(cl.levelname);
+       VectorCopy(cl.world.mins, prog->edicts->fields.client->mins);
+       VectorCopy(cl.world.maxs, prog->edicts->fields.client->maxs);
+
        // call the prog init
-       PRVM_ExecuteProgram((func_t) (PRVM_ED_FindFunction(CL_F_INIT) - prog->functions), CL_F_INIT);
+       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Init, "QC function CSQC_Init is missing");
 
        PRVM_End;
-       csqc_loaded = true;
-
-       csqc_sv2csqcents = (unsigned short *)Mem_Alloc(csqc_mempool, MAX_EDICTS*sizeof(unsigned short));
-       memset(csqc_sv2csqcents, 0, MAX_EDICTS*sizeof(unsigned short));
+       cl.csqc_loaded = true;
 
        cl.csqc_vidvars.drawcrosshair = false;
        cl.csqc_vidvars.drawenginesbar = false;
 
-       // local state
-       ent = &cl.csqcentities[0];
-       // entire entity array was cleared, so just fill in a few fields
-       ent->state_current.active = true;
-       ent->render.model = cl.worldmodel = cl.model_precache[1];
-       ent->render.scale = 1; // some of the renderer still relies on scale
-       ent->render.alpha = 1;
-       ent->render.flags = RENDER_SHADOW | RENDER_LIGHT;
-       Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, 0, 0, 0, 0, 0, 0, 1);
-       Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
-       CL_BoundingBoxForEntity(&ent->render);
+       // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
+       CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
 }
 
 void CL_VM_ShutDown (void)
 {
        Cmd_ClearCsqcFuncs();
-       Cvar_SetValueQuick(&csqc_progcrc, 0);
-       if(!csqc_loaded)
+       //Cvar_SetValueQuick(&csqc_progcrc, -1);
+       //Cvar_SetValueQuick(&csqc_progsize, -1);
+       if(!cl.csqc_loaded)
                return;
        CSQC_BEGIN
-               *prog->time = cl.time;
-               PRVM_ExecuteProgram((func_t) (PRVM_ED_FindFunction(CL_F_SHUTDOWN) - prog->functions), CL_F_SHUTDOWN);
+               prog->globals.client->time = cl.time;
+               prog->globals.client->self = 0;
+               if (prog->funcoffsets.CSQC_Shutdown)
+                       PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Shutdown, "QC function CSQC_Shutdown is missing");
                PRVM_ResetProg();
        CSQC_END
        Con_Print("CSQC ^1unloaded\n");
-       csqc_loaded = false;
-       Mem_FreePool(&csqc_mempool);
+       cl.csqc_loaded = false;
 }