From eceeddeff0fa17325bf0a0c8d8d3bfb59eb97518 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 5 Mar 2024 07:45:02 +0100 Subject: [PATCH] saveg stuff and some other things ugh --- src/d_clisrv.c | 10 +- src/p_saveg.c | 1036 +++++++++++++++++++++++++++++++++++++++++++++++- src/p_saveg.h | 12 +- 3 files changed, 1044 insertions(+), 14 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 24bf4522a..b9fb1264c 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -6223,7 +6223,8 @@ boolean TryRunTics(tic_t realtics) boolean canSimulate = (gamestate == GS_LEVEL) && leveltime >= TICRATE*4 && gametic >= TICRATE - && !countdown2 //SRB2Kart: No simulating after everyone has finished ... it breaks stuff + //&& !countdown2 //SRB2Kart: No simulating after everyone has finished ... it breaks stuff + && !exitcountdown //SRB2Kart: No simulating after everyone has finished ... it breaks stuff //countdown 2? the sequel? idk && (cv_simulate.value && !server) //SRB2Kart: make it impossible to sim before the start of the race && !resynch_local_inprogress && gametic >= lastSavestateClearedTic + TICRATE; boolean recordingStates = canSimulate; @@ -6385,7 +6386,7 @@ static void RunSimulations() } } - // and cull distant thinkers if enabled + // and cull distant thinkers if enabled //// FIXME i have no idea how this shit works without the split thinker lists lmao if (cv_simulateculldistance.value > 0) { thinker_t* current; @@ -6402,7 +6403,8 @@ static void RunSimulations() } } - for (current = thlist[THINK_MOBJ].next; current != &thlist[THINK_MOBJ]; current = current->next) + for (thinker = thlist[i].next; thinker != &thlist[i]; thinker = thinker->next) + //for (current = thlist[THINK_MOBJ].next; current != &thlist[THINK_MOBJ]; current = current->next) { for (i = 0; i < numPlayers; i++) { @@ -7209,7 +7211,7 @@ rewind_t *CL_RewindToTime(tic_t time) return NULL; save_p = rewindhead->savebuffer; - P_LoadNetGame(); + P_LoadNetGame(false); // i guess should be false??? wipegamestate = gamestate; // No fading back in! timeinmap = leveltime; diff --git a/src/p_saveg.c b/src/p_saveg.c index 3658734ba..d2faf3c46 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -45,6 +45,11 @@ UINT8 *save_p; #define ARCHIVEBLOCK_THINKERS 0x7F37037C #define ARCHIVEBLOCK_SPECIALS 0x7F228378 +boolean memleak = false; + +UINT32 saveTimes[12]; +UINT32 loadTimes[12]; + // Note: This cannot be bigger // than an UINT16 typedef enum @@ -454,6 +459,56 @@ static void P_NetUnArchivePlayers(void) } } +static void P_LocalArchivePlayers(void) +{ + int i; + + WRITEUINT32(save_p, ARCHIVEBLOCK_PLAYERS); + + for (i = 0; i < MAXPLAYERS; i++) + { + if (!playeringame[i]) + continue; + + WRITEMEM(save_p, &players[i], sizeof(player_t)); + + player_t* player = &((player_t*)save_p)[-1]; + +#define RELINK(var) if (var != NULL) var = (mobj_t*)var->mobjnum + RELINK(player->capsule); + RELINK(player->axis1); + RELINK(player->axis2); + RELINK(player->awayviewmobj); + //RELINK(player->followmobj); + //RELINK(player->drone); +#undef RELINK + } +} + +static void P_LocalUnArchivePlayers(void) +{ + int i; + + if (READUINT32(save_p) != ARCHIVEBLOCK_PLAYERS) + I_Error("Bad savestate at archive block Players"); + + for (i = 0; i < MAXPLAYERS; i++) + { + if (!playeringame[i]) + continue; + + READMEM(save_p, &players[i], sizeof(player_t)); + } +} + +/// +/// Colormaps +/// + +static extracolormap_t *net_colormaps = NULL; +static UINT32 num_net_colormaps = 0; +static UINT32 num_ffloors = 0; // for loading + #define SD_FLOORHT 0x01 #define SD_CEILHT 0x02 #define SD_FLOORPIC 0x04 @@ -488,6 +543,166 @@ static void P_NetUnArchivePlayers(void) #define LD_S2BOTTEX 0x04 #define LD_S2MIDTEX 0x08 +// ResetSectors +// Resets the sectors in the level to their original state +// +static void ResetSectors(void) +{ + UINT8* wadData = NULL; + const mapsector_t *ms; + const mapsidedef_t *msd; + const maplinedef_t *mld; + sector_t *ss; + line_t* li; + side_t* si; + + if (W_IsLumpWad(lastloadedmaplumpnum)) // welp it's a map wad in a pk3 + { // HACK: Open wad file rather quickly so we can get the data from the relevant lumps + wadData = W_CacheLumpNum(lastloadedmaplumpnum, PU_STATIC); + filelump_t *fileinfo = (filelump_t *)(wadData + ((wadinfo_t *)wadData)->infotableofs); +#define retrieve_mapdata(d, f)\ + d = (void*)(wadData + (f)->filepos); + + retrieve_mapdata(ms, fileinfo + ML_SECTORS); + retrieve_mapdata(mld, fileinfo + ML_LINEDEFS); + retrieve_mapdata(msd, fileinfo + ML_SIDEDEFS); +#undef retrieve_mapdata + } + else // phew it's just a WAD + { + ms = W_CacheLumpNum(lastloadedmaplumpnum + ML_SECTORS, PU_CACHE); + mld = W_CacheLumpNum(lastloadedmaplumpnum + ML_LINEDEFS, PU_CACHE); + msd = W_CacheLumpNum(lastloadedmaplumpnum + ML_SIDEDEFS, PU_CACHE); + } + + // reset every sector + // commented out lines are eh lines + // we really should do them properly, but they take effort and only have a visual effect + for (ss = sectors; ss < §ors[numsectors]; ss++, ms++) { + ss->floorheight = ms->floorheight<ceilingheight = ms->ceilingheight<floorpic = P_AddLevelFlatRuntime((char *)get); + //ss->ceilingpic = P_AddLevelFlatRuntime((char *)get); + ss->lightlevel = ms->lightlevel; + ss->special = ms->special; + + ss->floor_xoffs = ss->spawn_flr_xoffs; + ss->floor_yoffs = ss->spawn_flr_yoffs; + ss->ceiling_xoffs = ss->spawn_ceil_xoffs; + ss->ceiling_yoffs = ss->spawn_ceil_yoffs; + ss->floorpic_angle = ss->spawn_flrpic_angle; + ss->ceilingpic_angle = ss->spawn_ceilpic_angle; + ss->tag = ms->tag; // DON'T use P_ChangeSectorTag + ss->firsttag = ss->spawn_firsttag; + ss->nexttag = ss->spawn_nexttag; + //ss->extra_colormap = GetNetColormapFromList(READUINT32(get)); + + ffloor_t* floor = ss->ffloors; + + while (floor != NULL) + { + floor->flags = floor->spawnflags; + floor->alpha = floor->spawnalpha; + + floor = floor->next; + } + } + + for (li = lines; li < &lines[numlines]; li++, mld++) + { + li->special = mld->special; + if (SHORT(li->special) == 321 || SHORT(li->special) == 322) { + li->callcount = 0; + } + + si = &sides[li->sidenum[0]]; + //si->textureoffset = si->; + //si->toptexture = READINT32(get); + //si->bottomtexture = READINT32(get); + //si->midtexture = READINT32(get); + + si = &sides[li->sidenum[1]]; + //si->textureoffset = READFIXED(get); + //si->toptexture = READINT32(get); + //si->bottomtexture = READINT32(get); + //si->midtexture = READINT32(get); + } + + if (wadData) + { + Z_Free(wadData); + } +} + +// +// P_LocalArchiveWorld +// Archives the world's state locally, regardless of differences from original state +// Faster than NetArchiveWorld +// +static void P_LocalArchiveWorld(void) +{ + UINT8* put; + + // paranoia something something + //ClearNetColormaps(); + + WRITEUINT32(save_p, ARCHIVEBLOCK_WORLD); + put = save_p; + + WRITEUINT32(put, numsectors * sizeof(sectors[0])); + WRITEUINT32(put, numlines * sizeof(lines[0])); + + // dump all sector memory into the data + WRITEMEM(put, sectors, numsectors * sizeof(sectors[0])); + WRITEMEM(put, lines, numlines * sizeof(lines[0])); + + save_p = put; +} + +static void P_LocalUnArchiveWorld(void) +{ + UINT8* get = save_p; + + if (READUINT32(get) != ARCHIVEBLOCK_WORLD) + { + I_Error("Bad SaveState at archive block World"); + } + + // preserve certain local variables + sector_t* preservedSectors = Z_Malloc(numsectors * sizeof(sector_t), PU_CACHE, NULL); + + memcpy(preservedSectors, sectors, numsectors * sizeof(sector_t)); + + UINT32 sectorSize = READUINT32(get); + UINT32 lineSize = READUINT32(get); + READMEM(get, sectors, numsectors * sizeof(sectors[0])); + READMEM(get, lines, numlines * sizeof(lines[0])); + + for (size_t i = 0; i < numsectors; i++) + { + sectors[i].thinglist = preservedSectors[i].thinglist; + sectors[i].touching_thinglist = preservedSectors[i].touching_thinglist; + sectors[i].preciplist = preservedSectors[i].preciplist; + sectors[i].touching_preciplist = preservedSectors[i].touching_preciplist; + + if (sectors[i].thinglist == (mobj_t*)0xDDDDDDDD) + { + continue; + } + + // restore preserved local stuff (tbh I don't really know what this is lol) + sectors[i].lightlist = preservedSectors[i].lightlist; + sectors[i].numlights = preservedSectors[i].numlights; + sectors[i].attached = preservedSectors[i].attached; + sectors[i].attachedsolid = preservedSectors[i].attachedsolid; + } + + Z_Free(preservedSectors); + + save_p = get; +} + // // P_NetArchiveWorld // @@ -743,16 +958,34 @@ static void P_NetArchiveWorld(void) // // P_NetUnArchiveWorld // -static void P_NetUnArchiveWorld(void) +static void P_NetUnArchiveWorld(boolean preserveLevel) { UINT16 i; line_t *li; side_t *si; UINT8 *get; UINT8 diff, diff2; + UINT32 num_ffloors; if (READUINT32(save_p) != ARCHIVEBLOCK_WORLD) I_Error("Bad $$$.sav at archive block World"); + + // initialize colormap vars because paranoia + R_ClearColormaps(); + + if (preserveLevel) { + // when we save, we only save sectors that differ from their initial state + // so if we don't reset our sectors before loading, some sector changes might not be reverted becuase they were identical to their original state when saved and thus omitted + ResetSectors(); + } + + // count the level's ffloors so that colormap loading can have an upper limit + for (i = 0; i < numsectors; i++) + { + ffloor_t *rover; + for (rover = sectors[i].ffloors; rover; rover = rover->next) + num_ffloors++; + } get = save_p; @@ -996,6 +1229,69 @@ typedef enum tc_end } specials_e; + +typedef enum +{ + ST_FLOORDATA = 1, + ST_CEILDATA = 2, + ST_LIGHTDATA = 4, + ST_FADEMAPDATA = 8 +} sectortarget_e; + +typedef struct +{ + actionf_p1 action; + UINT16 size; + UINT32 sectorPointer; + UINT8 sectorTargets; +} specialdef_t; + +// special function/data size associations +#define NOSECTOR(func, type) (actionf_p1)func, sizeof(type), 0, 0 +#define WITHSECTOR(func, type, targets) (actionf_p1)func, sizeof(type), (UINT32)&((type*)NULL)->sector, targets +static const specialdef_t specialDefs[] = +{ + NOSECTOR(P_MobjThinker, mobj_t), // tc_mobj + WITHSECTOR(T_MoveCeiling, ceiling_t, ST_CEILDATA), // tc_ceiling + WITHSECTOR(T_MoveFloor, floormove_t, ST_FLOORDATA), // tc_floor + WITHSECTOR(T_LightningFlash, lightflash_t, ST_LIGHTDATA), // tc_flash + WITHSECTOR(T_StrobeFlash, strobe_t, ST_LIGHTDATA), // tc_strobe + WITHSECTOR(T_Glow, glow_t, ST_LIGHTDATA), // tc_glow + WITHSECTOR(T_FireFlicker, fireflicker_t, ST_LIGHTDATA), // tc_fireflicker + WITHSECTOR(T_ThwompSector, levelspecthink_t, ST_FLOORDATA | ST_CEILDATA), // tc_thwomp + NOSECTOR(T_CameraScanner, elevator_t), // tc_camerascanner + WITHSECTOR(T_MoveElevator, elevator_t, ST_CEILDATA | ST_FLOORDATA), // tc_elevator + WITHSECTOR(T_ContinuousFalling, levelspecthink_t, ST_CEILDATA | ST_FLOORDATA), // tc_contunousfalling + WITHSECTOR(T_BounceCheese, levelspecthink_t, ST_CEILDATA), // tc_bouncecheese + WITHSECTOR(T_StartCrumble, elevator_t, ST_FLOORDATA), // tc_startcrumble + WITHSECTOR(T_MarioBlock, levelspecthink_t, ST_FLOORDATA | ST_CEILDATA), // tc_marioblock + NOSECTOR(T_MarioBlockChecker, levelspecthink_t), // tc_marioblockchecker + NOSECTOR(T_SpikeSector, levelspecthink_t), // tc_spikesector + NOSECTOR(T_FloatSector, levelspecthink_t), // tc_floatsector + WITHSECTOR(T_BridgeThinker, levelspecthink_t, ST_CEILDATA | ST_FLOORDATA), // tc_bridgethinker + WITHSECTOR(T_CrushCeiling, ceiling_t, ST_CEILDATA), // tc_crushceiling + NOSECTOR(T_Scroll, scroll_t), // tc_scroll + NOSECTOR(T_Friction, friction_t), // tc_friction + NOSECTOR(T_Pusher, pusher_t), // tc_pusher + NOSECTOR(T_LaserFlash, laserthink_t), // tc_laserflash + WITHSECTOR(T_LightFade, lightlevel_t, ST_LIGHTDATA), // tc_lightfade + NOSECTOR(T_ExecutorDelay, executor_t), // tc_executor + NOSECTOR(T_RaiseSector, levelspecthink_t), // tc_raisesector + NOSECTOR(T_NoEnemiesSector, levelspecthink_t), // tc_noenemies + NOSECTOR(T_EachTimeThinker, levelspecthink_t), // tc_eachtime + NOSECTOR(T_Disappear, disappear_t), // tc_disappear +#ifdef POLYOBJECTS + NOSECTOR(T_PolyObjRotate, polyrotate_t), // tc_polyrotate + NOSECTOR(T_PolyObjMove, polymove_t), // tc_polymove + NOSECTOR(T_PolyObjWaypoint, polywaypoint_t), // tc_polywaypoint + NOSECTOR(T_PolyDoorSlide, polyslidedoor_t), // tc_polyslidedoor + NOSECTOR(T_PolyDoorSwing, polyswingdoor_t), // tc_polyswingdoor + NOSECTOR(T_PolyObjFlag, polymove_t), // tc_polyflag + NOSECTOR(T_PolyObjDisplace, polydisplace_t), // tc_polydisplace +#endif +}; +#undef A + static inline UINT32 SaveMobjnum(const mobj_t *mobj) { if (mobj) return mobj->mobjnum; @@ -2688,10 +2984,549 @@ static inline void LoadWhatThinker(actionf_p1 thinker) } */ +// debug lists for the confused programmer +thinker_t* debugThinkerLists[NUM_THINKERLISTS][4096]; +mobj_t* debugMobjLists[NUM_THINKERLISTS][4096]; +int numDebugThinkers[NUM_THINKERLISTS]; + +static void CollectDebugObjectList(void) { + int i; + for (i = 0; i < NUM_THINKERLISTS; i++) { + int count = 0; + thinker_t* test; + thinker_t* testNext; + for (test = thlist[i].next; test != &thlist[i]; test = testNext) { + testNext = test->next; + debugThinkerLists[i][count] = test; + debugMobjLists[i][count] = (mobj_t*)test; + count++; + } + numDebugThinkers[i] = count; + } +} + +void S_DetachChannelsFromOrigin(void* origin); + +typedef struct +{ + mobj_t* mobj; + int thinkerListIndex; +} mobjloclink_t; + +#define HASHLOC(x, y, z) (((x>>4)-(y>>8)+(z>>12)-(x>>16)+(y>>20)-(z>>24)+(x>>28)-(y>>24)+(z>>20)-(x>>16)+(y>>8)-(z>>4)) & 0x7FFF) +#define MAXNUMMOBJSBYLOC 15 + + + +// +// P_LocalArchiveThinkers +// Archives the world's thinkers locally. Used for within-level savestates +// +static void P_LocalArchiveThinkers(void) +{ + int i, j; + size_t s; + const thinker_t* thinker; + mobj_t* savedMobj; + executor_t* savedExecutor; + UINT8* original = save_p; + WRITEUINT32(save_p, ARCHIVEBLOCK_THINKERS); + + for (i = 0; i < NUM_THINKERLISTS; i++) + { +#define RELINK(var) if (var != NULL) var = (mobj_t*)(var->mobjnum) + for (thinker = thlist[i].next; thinker != &thlist[i]; thinker = thinker->next) + { + actionf_p1 acp1 = thinker->function.acp1; + + // find the associated special def + for (j = 0; j < sizeof(specialDefs) / sizeof(specialDefs[0]); j++) + { + if (acp1 == specialDefs[j].action) + break; + } + + if (j == sizeof(specialDefs) / sizeof(specialDefs[0])) + continue; + + WRITEUINT8(save_p, j); + WRITEMEM(save_p, thinker, specialDefs[j].size); + + // relink saved pointers with saved mobjnums + if (j == tc_mobj) + { + savedMobj = &((mobj_t*)save_p)[-1]; + RELINK(savedMobj->tracer); + RELINK(savedMobj->target); + RELINK(savedMobj->hnext); + RELINK(savedMobj->hprev); + } + + if (j == tc_executor) + { + savedExecutor = &((executor_t*)save_p)[-1]; + RELINK(savedExecutor->caller); + } + } + + WRITEUINT8(save_p, 0xFF); // next list (or end) + } + + //RELINK(waypointcap); + // now write the nothinkers... + // turns out that MF_NOTHINKs aren't in thinker lists lol.... + // makes sense, but doesn't make life easier. I just wanted an object list. Ah well. + for (s = 0; s < numsectors; s++) + { + mobj_t* thing = sectors[s].thinglist; + + while (thing) + { + if (thing->flags & MF_NOTHINK) + { + // archive this thing + WRITEUINT8(save_p, tc_mobj); + WRITEMEM(save_p, thing, specialDefs[tc_mobj].size); + + savedMobj = &((mobj_t*)save_p)[-1]; + RELINK(savedMobj->tracer); + RELINK(savedMobj->target); + RELINK(savedMobj->hnext); + RELINK(savedMobj->hprev); + + } + thing = thing->snext; + } + } +#undef RELINK + + WRITEUINT8(save_p, 0xFF); +} + +static void P_LocalUnArchiveThinkers() +{ + thinker_t *thinker; + mobj_t* mobj; + UINT8 tclass; + UINT8 restoreExecutors = false; + INT32 i, j, list; + int skyviewid = 0; + int skycenterid = 0; + thinker_t newthinkers[NUM_THINKERLISTS] = { 0 }; + static thinker_t* thinkersbytype[tc_end][16384]; + static int numthinkersbytype[tc_end]; + static mobjloclink_t mobjByLoc[32768][MAXNUMMOBJSBYLOC]; + static int numMobjsByLoc[32768]; + static mobj_t* mobjByNum[16384]; + + memset(mobjByNum, 0, sizeof(mobjByNum)); + memset(mobjByLoc, 0, sizeof(mobjByLoc)); + memset(numMobjsByLoc, 0, sizeof(numMobjsByLoc)); + memset(numthinkersbytype, 0, sizeof(numthinkersbytype)); + + int hashHits = 0; + int hashMisses = 0; + + if (READUINT32(save_p) != ARCHIVEBLOCK_THINKERS) + I_Error("Bad SaveState at archive block Thinkers"); + + // preserve sky box indexes + /* Probably unused + for (i = 0; i < 16; i++) + { + if (skyboxmo[0] == skyboxviewpnts[i]) + skyviewid = i; // save id just in case + if (skyboxmo[1] == skyboxcenterpnts[i]) + skycenterid = i; // save id just in case + skyboxviewpnts[i] = NULL; + skyboxcenterpnts[i] = NULL; + } + */ + skyboxmo[0] = skyboxmo[1] = NULL; + + // sort thinkers into maps to speed up replacement searches + for (i = 0; i < NUM_THINKERLISTS; i++) + { + newthinkers[i].next = &newthinkers[i]; + newthinkers[i].prev = &newthinkers[i]; + + for (thinker = thlist[i].next; thinker != &thlist[i]; thinker = thinker->next) + { + if (thinker->function.acp1 == P_RemoveThinkerDelayed) + continue; + for (j = 0; j < tc_end; j++) + { + if (thinker->function.acp1 == specialDefs[j].action) + break; + } + + // insert the thinker into the appropriate maps + thinkersbytype[j][numthinkersbytype[j]] = thinker; + numthinkersbytype[j]++; + + if (thinker->function.acp1 == P_MobjThinker) + { + UINT16 locHash = HASHLOC(((mobj_t*)thinker)->x, ((mobj_t*)thinker)->y, ((mobj_t*)thinker)->z); + + if (numMobjsByLoc[locHash] < MAXNUMMOBJSBYLOC) + { + mobjByLoc[locHash][numMobjsByLoc[locHash]].mobj = (mobj_t*)thinker; + mobjByLoc[locHash][numMobjsByLoc[locHash]].thinkerListIndex = numthinkersbytype[j] - 1; + numMobjsByLoc[locHash]++; + } + } + } + } + + // remove from item respawn queues + iquetail = iquehead = 0; + waypointcap = NULL; + + // clear sector thinker pointers so they don't point to non-existant thinkers for all of eternity + for (i = 0; i < (int)numsectors; i++) + { + mobj_t* thing = sectors[i].thinglist, *next; + sectors[i].floordata = sectors[i].ceilingdata = sectors[i].lightingdata; + + // clear nothinkers too + while (thing) + { + next = thing->snext; + if (thing->flags & MF_NOTHINK) + { + thing->thinker.references = 0; // hope this is ok... + P_RemoveMobj(thing); + } + + thing = next; + } + } + + // read in saved thinkers + for (list = 0; list < NUM_THINKERLISTS; list++) + { + for (;;) + { + msecnode_t* preserveTouchingSectorlist = NULL; + sector_t* preserveSubsector = NULL; + + tclass = READUINT8(save_p); + + if (tclass == 0xFF) + break; // next list + + thinker_t* newthinker = NULL; + boolean preservePositions = false; + + // find the existing thinker(s) at the same position, if possible + if (tclass == tc_mobj) + { + mobj_t* savedMobj = (mobj_t*)save_p; + UINT16 locHash = HASHLOC(savedMobj->x, savedMobj->y, savedMobj->z); + + for (i = 0; i < numMobjsByLoc[locHash]; i++) + { + if (mobjByLoc[locHash][i].mobj->x == savedMobj->x && mobjByLoc[locHash][i].mobj->y == savedMobj->y && mobjByLoc[locHash][i].mobj->z == savedMobj->z && + (mobjByLoc[locHash][i].mobj->flags & (MF_NOSECTOR | MF_NOBLOCKMAP)) == (savedMobj->flags & (MF_NOSECTOR | MF_NOBLOCKMAP))) + { + newthinker = (thinker_t*)mobjByLoc[locHash][i].mobj; + thinkersbytype[tc_mobj][mobjByLoc[locHash][i].thinkerListIndex] = NULL; + mobjByLoc[locHash][i] = mobjByLoc[locHash][numMobjsByLoc[locHash] - 1]; + numMobjsByLoc[locHash]--; + preservePositions = true; + hashHits++; + break; + } + } + + if (newthinker == NULL) + hashMisses++; + } + + // if that didn't work, find an existing thinker of the same type + if (newthinker == NULL && numthinkersbytype[tclass] > 0) + { + for (j = numthinkersbytype[tclass] - 1; j >= 0; j--) + { + if (thinkersbytype[tclass][j] == NULL) + { + numthinkersbytype[tclass]--; + continue; + } + + // we found an object to replace! + newthinker = thinkersbytype[tclass][j]; + numthinkersbytype[tclass]--; + break; + } + } + + if (newthinker != NULL) + { + // we found a thinker! we just need to set it up to be replaced + if (tclass == tc_mobj && !preservePositions) + { + // remove it from its old position + P_UnsetThingPosition((mobj_t*)newthinker); + if (sector_list != NULL) + { + P_DelSeclist(sector_list); + sector_list = NULL; + } + } + + // detach any playing sounds from this object if we can (still need to work on doing this properly!) + S_DetachChannelsFromOrigin((mobj_t*)newthinker); + + // unlink it from the old list (if it's not a nothinker) + if (!(tclass == tc_mobj && (((mobj_t*)newthinker)->flags & MF_NOTHINK))) + { + newthinker->prev->next = newthinker->next; + newthinker->next->prev = newthinker->prev; + } + } + else + { + // we couldn't find an object to replace so we gotta create it + if (tclass == tc_mobj) + newthinker = Z_Calloc(specialDefs[tclass].size, PU_LEVEL, NULL); + else + newthinker = Z_Malloc(specialDefs[tclass].size, PU_LEVSPEC, NULL); + } + + // preserve vital positioning stuff (cleanup...) + mobj_t preservedMobj; + if (tclass == tc_mobj) + preservedMobj = *(mobj_t*)newthinker; + + // read in the data + READMEM(save_p, newthinker, specialDefs[tclass].size); + + newthinker->references = 0; // we'll sort this later + + // set special-specific info + switch (tclass) + { + case tc_mobj: + { + mobj_t* mobj = (mobj_t*)newthinker; + + // link global and player pointers + if (mobj->type == MT_REDFLAG) + { + redflag = mobj; + rflagpoint = mobj->spawnpoint; + } + + if (mobj->type == MT_BLUEFLAG) + { + blueflag = mobj; + bflagpoint = mobj->spawnpoint; + } + if (mobj->type == MT_BOSS3WAYPOINT) + { + //P_SetTarget(&mobj->tracer, waypointcap); + P_SetTarget(&waypointcap, mobj); + } + /* + if (mobj->type == MT_SKYBOX) + { + if ((mobj->extravalue2 >> 16) == 1) + skyboxcenterpnts[mobj->extravalue2 & 0xFFFF] = mobj; + else + skyboxviewpnts[mobj->extravalue2 & 0xFFFF] = mobj; + } + */ + + if (mobj->player && mobj->type == MT_PLAYER) + mobj->player->mo = mobj; + + // clear sector links etc + mobj->bnext = NULL; + mobj->bprev = NULL; + mobj->snext = preservedMobj.snext; + mobj->sprev = preservedMobj.sprev; + mobj->subsector = preservedMobj.subsector; + mobj->touching_sectorlist = preservedMobj.touching_sectorlist; + mobjByNum[mobj->mobjnum] = mobj; + break; // i dream of a programming language where breaking is the default and fallthrough is the optional (and so much more rarely used) specifier + } + case tc_executor: + restoreExecutors = true; + break; + } + + // make special-specific sector connections + if (specialDefs[tclass].sectorTargets) + { + sector_t* target = *(sector_t**)((UINT8*)newthinker + specialDefs[tclass].sectorPointer); + + if (specialDefs[tclass].sectorTargets & ST_CEILDATA) + target->ceilingdata = newthinker; + if (specialDefs[tclass].sectorTargets & ST_FLOORDATA) + target->floordata = newthinker; + /* + if (specialDefs[tclass].sectorTargets & ST_LIGHTDATA) + target->lightingdata = newthinker; + if (specialDefs[tclass].sectorTargets & ST_FADEMAPDATA) + target->fadecolormapdata = newthinker; + */ + } + + // relink into the new thinker list + if (!(tclass == tc_mobj && (((mobj_t*)newthinker)->flags & MF_NOTHINK))) + { + newthinker->prev = newthinkers[list].prev; + newthinker->next = &newthinkers[list]; + newthinker->prev->next = newthinker; + newthinker->next->prev = newthinker; + } + + if (tclass == tc_mobj) + { + if (!preservePositions) + P_SetThingPosition((mobj_t*)newthinker); + else + { + ((mobj_t*)newthinker)->bnext = preservedMobj.bnext; + ((mobj_t*)newthinker)->bprev = preservedMobj.bprev; + } + } + } + } + + // collect nothinkers as well + for (;;) + { + tclass = READUINT8(save_p); + + if (tclass == 0xFF) + break; // next list + + mobj = Z_Calloc(sizeof(mobj_t), PU_LEVEL, NULL); + READMEM(save_p, mobj, specialDefs[tclass].size); + + mobjByNum[mobj->mobjnum] = mobj; + mobj->bnext = NULL; + mobj->bprev = NULL; + mobj->snext = NULL; + mobj->sprev = NULL; + mobj->subsector = NULL; + mobj->touching_sectorlist = NULL; + P_SetThingPosition(mobj); + + // we just spawner a nothinker so it doesn't go in a thinker list, let it run wild?? + } + + // delete everything remaining in the list that hasn't been linked + for (i = 0; i < NUM_THINKERLISTS; i++) + { + thinker_t* next; + + for (thinker = thlist[i].next; thinker != &thlist[i]; thinker = next) + { + next = thinker->next; + + thinker->references = 0; + + if (thinker->function.acp1 == (actionf_p1)P_MobjThinker) + P_RemoveSavegameMobj((mobj_t *)thinker, true); + else if (thinker->function.acp1 == (actionf_p1)P_NullPrecipThinker) + P_RemovePrecipMobj((precipmobj_t*)thinker); // i bet this is gonna break :D + else + { + // we can remove this thinker manually, bye! + thinker->prev->next = thinker->next; + thinker->next->prev = thinker->prev; + Z_Free(thinker); + } + } + + // connect the new linker list to the old linker list + newthinkers[i].prev->next = thlist[i].next; + thlist[i].next->prev = newthinkers[i].prev; + + thlist[i].next = newthinkers[i].next; + newthinkers[i].next->prev = &thlist[i]; + } + + // restore execution stuff I guess lol + if (restoreExecutors) + { + executor_t *delay = NULL; + UINT32 mobjnum; + for (thinker = thlist[THINK_MAIN].next; thinker != &thlist[THINK_MAIN]; thinker = thinker->next) + { + if (thinker->function.acp1 != (actionf_p1)T_ExecutorDelay) + continue; + delay = (void *)thinker; + if (!(mobjnum = (UINT32)(size_t)delay->caller)) + continue; + delay->caller = mobjByNum[mobjnum]; + } + } + + // restore pointers +#define RELINK(var) if (var) { UINT32 index = (UINT32)var; var = NULL; P_SetTarget(&var, mobjByNum[index]); } + + //RELINK(waypointcap); + + for (thinker = thlist[THINK_MOBJ].next; thinker != &thlist[THINK_MOBJ]; thinker = thinker->next) + { + if (thinker->function.acp1 == (actionf_p1)P_RemoveThinkerDelayed) + continue; + + mobj = (mobj_t*)thinker; + + RELINK(mobj->tracer); + RELINK(mobj->target); + RELINK(mobj->hnext); + RELINK(mobj->hprev); + } + + // and for nothinkers + for (i = 0; i < (int)numsectors; i++) + { + mobj_t* thing = sectors[i].thinglist; + + while (thing) + { + if (thing->flags & MF_NOTHINK) + { + RELINK(thing->tracer); + RELINK(thing->target); + RELINK(thing->hnext); + RELINK(thing->hprev); + } + + thing = thing->snext; + } + } + + // restore player pointers (the above doesn't always seem to work perhaps because playeringame is false? + for (int i = 0; i < MAXPLAYERS; i++) + { + if (playeringame[i]) + { + RELINK(players[i].capsule); + RELINK(players[i].axis1); + RELINK(players[i].axis2); + RELINK(players[i].awayviewmobj); + //RELINK(players[i].followmobj); + //RELINK(players[i].drone); + } + } +#undef RELINK + + // restore skyboxes + //skyboxmo[0] = skyboxviewpnts[(skyviewid >= 0) ? skyviewid : 0]; + //skyboxmo[1] = skyboxcenterpnts[(skycenterid >= 0) ? skycenterid : 0]; +} + // // P_NetUnArchiveThinkers // -static void P_NetUnArchiveThinkers(void) +static void P_NetUnArchiveThinkers(boolean preserveLevel) { thinker_t *currentthinker; thinker_t *next; @@ -2700,9 +3535,24 @@ static void P_NetUnArchiveThinkers(void) UINT32 i; UINT32 numloaded = 0; + mobj_t* currentmobj; + int skyviewid = -1; + int skycenterid = -1; + if (READUINT32(save_p) != ARCHIVEBLOCK_THINKERS) I_Error("Bad $$$.sav at archive block Thinkers"); + /* + // preserve sky box index + for (i = 0; i < 16; i++) + { + if (skyboxmo[0] && skyboxmo[0] == skyboxviewpnts[i]) + skyviewid = i; // save id just in case + if (skyboxmo[1] && skyboxmo[1] == skyboxcenterpnts[i]) + skycenterid = i; // save id just in case + } + */ + // remove all the current thinkers currentthinker = thinkercap.next; for (currentthinker = thinkercap.next; currentthinker != &thinkercap; currentthinker = next) @@ -2722,12 +3572,18 @@ static void P_NetUnArchiveThinkers(void) // we don't want the removed mobjs to come back iquetail = iquehead = 0; P_InitThinkers(); + + waypointcap = NULL; //Hack transplant, was being called in P_InitThinkers, which was removed from here for memory leak reasons? Se we moved the hack here for netgames // clear sector thinker pointers so they don't point to non-existant thinkers for all of eternity for (i = 0; i < numsectors; i++) { sectors[i].floordata = sectors[i].ceilingdata = sectors[i].lightingdata = NULL; } + + // clear flags (necessary for level-preserving loads) + redflag = NULL; + blueflag = NULL; // read in saved thinkers for (;;) @@ -2907,6 +3763,12 @@ static void P_NetUnArchiveThinkers(void) } } } + + + + // restore skyboxes, if applicable + for (i = 0; i < sizeof(skyboxmo) / sizeof(skyboxmo[0]); i++) + skyboxmo[i] = NULL; } /////////////////////////////////////////////////////////////////////////////// @@ -3001,6 +3863,31 @@ static inline void P_UnArchivePolyObjects(void) for (i = 0; i < numSavedPolys; ++i) P_UnArchivePolyObj(&PolyObjects[i]); } + +static void P_LocalArchivePolyObjects(void) +{ + P_ArchivePolyObjects(); + /*WRITEUINT32(save_p, ARCHIVEBLOCK_POBJS); + WRITEINT32(save_p, numPolyObjects); + WRITEMEM(save_p, PolyObjects, numPolyObjects * sizeof(PolyObjects[0]));*/ +} + +static void P_LocalUnArchivePolyObjects(void) +{ + P_UnArchivePolyObjects(); + /*if (READUINT32(save_p) != ARCHIVEBLOCK_POBJS) + I_Error("Bad savestate at archive block polyobjects"); + numPolyObjects = READINT32(save_p); + READMEM(save_p, PolyObjects, numPolyObjects * sizeof(PolyObjects[0])); + bmap_freelist = NULL; + for (int i = 0; i < numPolyObjects; i++) + { + PolyObjects[i].thinker = NULL; + PolyObjects[i].linked = false; + Polyobj_linkToBlockmap(&PolyObjects[i]); + }*/ +} + // // P_FinishMobjs // @@ -3337,11 +4224,13 @@ static void P_NetArchiveMisc(void) WRITEUINT8(save_p, 0x2e); } -static inline boolean P_NetUnArchiveMisc(void) +static inline boolean P_NetUnArchiveMisc(boolean preserveLevel) { UINT32 pig; INT32 i; + INT16 oldMap = gamemap; + if (READUINT32(save_p) != ARCHIVEBLOCK_MISC) I_Error("Bad $$$.sav at archive block Misc"); @@ -3371,7 +4260,7 @@ static inline boolean P_NetUnArchiveMisc(void) encoremode = (boolean)READUINT8(save_p); - if (!P_SetupLevel(true)) + if ((!preserveLevel || (gamemap != oldMap)) && !P_SetupLevel(true)) return false; // get the time @@ -3447,6 +4336,28 @@ static inline boolean P_NetUnArchiveMisc(void) return true; } +//made kart splitscreen compat +static inline void P_LocalArchiveCameras() +{ + WRITEMEM(save_p, &camera, sizeof(camera)); +} + +//made kart splitscreen compat +static inline void P_LocalUnArchiveCameras() +{ + UINT32 i; + boolean chase[4]; + for (i = 0; i < 4; i++) + chase[i] = camera[i].chase; + + // this makes things easy! + READMEM(save_p, &camera, sizeof(camera)); + + // chase is changed outside of tics, so preserve this + for (i = 0; i < 4; i++) + camera[i].chase = chase[i]; +} + void P_SaveGame(void) { P_ArchiveMisc(); @@ -3514,17 +4425,17 @@ boolean P_LoadGame(INT16 mapoverride) return true; } -boolean P_LoadNetGame(void) +boolean P_LoadNetGame(boolean preserveLevel) { - CV_LoadNetVars(&save_p); - if (!P_NetUnArchiveMisc()) + CV_LoadNetVars(&save_p, false); + if (!P_NetUnArchiveMisc(preserveLevel)) return false; P_NetUnArchivePlayers(); if (gamestate == GS_LEVEL) { - P_NetUnArchiveWorld(); + P_NetUnArchiveWorld(preserveLevel); P_UnArchivePolyObjects(); - P_NetUnArchiveThinkers(); + P_NetUnArchiveThinkers(preserveLevel); P_NetUnArchiveSpecials(); P_RelinkPointers(); P_FinishMobjs(); @@ -3543,3 +4454,110 @@ boolean P_LoadNetGame(void) return READUINT8(save_p) == 0x1d; } + +extern UINT64 saveStateBenchmark; +extern UINT64 loadStateBenchmark; + +// P_SaveGameState is a within-level-only mechanism for saving the game state. It must not be used cross level. Used for simulation backtracking. +// It uses a mixture of existing NetArchive functions and faster LocalArchive functions to do the job +void P_SaveGameState(savestate_t* savestate) +{ + mobj_t* mobj; + thinker_t* th; + size_t s = 0; + int mobjnum = 1; + + UINT64 time = I_GetTimeUs(); + + save_p = savestate->buffer; + + WRITEINT16(save_p, gamemap); + WRITEUINT32(save_p, globalmobjnum); + + CV_SaveNetVars(&save_p, false); + + // assign mobj nums for pointer relinking + for (th = thlist[THINK_MOBJ].next; th != &thlist[THINK_MOBJ]; th = th->next) + { + if (th->function.acp1 == (actionf_p1)P_RemoveThinkerDelayed) + continue; + + mobj = (mobj_t *)th; + if (mobj->type == MT_HOOP || mobj->type == MT_HOOPCOLLIDE || mobj->type == MT_HOOPCENTER) + continue; + mobj->mobjnum = mobjnum++; + } + // including nothinkers... + for (s = 0; s < numsectors; s++) + { + mobj_t* thing = sectors[s].thinglist; + + while (thing) + { + if (thing->flags & MF_NOTHINK) + { + thing->mobjnum = mobjnum++; + } + thing = thing->snext; + } + } + + P_NetArchiveMisc(); + P_LocalArchivePlayers(); + P_LocalArchiveWorld(); +#ifdef POLYOBJECTS + P_LocalArchivePolyObjects(); +#endif + P_LocalArchiveThinkers(); + P_NetArchiveSpecials(); + P_LocalArchiveCameras(); + +#ifdef HAVE_BLUA + LUA_Archive(); +#endif + + //P_ArchiveLuabanksAndConsistency(); + + saveStateBenchmark = I_GetTimeUs() - time; +} + +// P_LoadGameState is a within-level-only mechanism for loading the game state. It must not be used cross level. Used for simulation backtracking. +// It uses a mixture of existing NetUnArchive functions and faster LocalUnArchive functions to do the job +boolean P_LoadGameState(const savestate_t* savestate) +{ + UINT64 time = I_GetTimeUs(); + angle_t preserveAngle = localangle; + INT32 preserveAiming = localaiming; + INT16 savedGameMap; + + save_p = ((unsigned char*)savestate->buffer); + + savedGameMap = READINT16(save_p); + globalmobjnum = READUINT32(save_p); + + if (savedGameMap != gamemap) + { + // savestates do not work cross-level + return false; + } + + CV_LoadNetVars(&save_p, true); + + P_NetUnArchiveMisc(true); + P_LocalUnArchivePlayers(); + P_LocalUnArchiveWorld(); + P_LocalUnArchivePolyObjects(); + P_LocalUnArchiveThinkers(); + P_NetUnArchiveSpecials(); + P_LocalUnArchiveCameras(); + + LUA_UnArchive(); + + // This is stupid and hacky _squared_, but it's in the net load code and it says it might work, so I guess it might work! + //P_SetRandSeed(P_GetInitSeed()); + + //P_UnArchiveLuabanksAndConsistency(); + loadStateBenchmark = I_GetTimeUs() - time; + + return true; +} diff --git a/src/p_saveg.h b/src/p_saveg.h index 0992f1185..e425a9ff1 100644 --- a/src/p_saveg.h +++ b/src/p_saveg.h @@ -21,10 +21,20 @@ // Persistent storage/archiving. // These are the load / save game routines. +typedef struct +{ + UINT8 buffer[16 * 1024 * 1024]; // 16 megs per frame should do +} savestate_t; + +// Persistent storage/archiving. +// These are the load / save game routines. + void P_SaveGame(void); void P_SaveNetGame(void); +void P_SaveGameState(savestate_t* savestate); boolean P_LoadGame(INT16 mapoverride); -boolean P_LoadNetGame(void); +boolean P_LoadNetGame(boolean preserveLevel); +boolean P_LoadGameState(const savestate_t* savestate); mobj_t *P_FindNewPosition(UINT32 oldposition);