diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index adce10023..f31a9bd26 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -134,6 +134,7 @@ set(SRB2_CORE_RENDER_SOURCES r_sky.c r_splats.c r_things.c + r_portal.c r_bsp.h r_data.h @@ -149,6 +150,7 @@ set(SRB2_CORE_RENDER_SOURCES r_splats.h r_state.h r_things.h + r_portal.h ) set(SRB2_CORE_GAME_SOURCES @@ -470,6 +472,7 @@ if(${SRB2_CONFIG_HWRENDER}) ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_clip.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_draw.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_main.c + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_portal.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md2.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md2load.c ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md3load.c @@ -484,9 +487,10 @@ if(${SRB2_CONFIG_HWRENDER}) ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_data.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_defs.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_dll.h - ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_drv.h + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_gl.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_glob.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_main.h + ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_portal.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md2.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md2load.h ${CMAKE_CURRENT_SOURCE_DIR}/hardware/hw_md3load.h diff --git a/src/Makefile b/src/Makefile index e3e764210..111e586b4 100644 --- a/src/Makefile +++ b/src/Makefile @@ -229,6 +229,7 @@ endif ifdef LINUX UNIXCOMMON=1 +NOOBJDUMP=1 ifndef NOGME HAVE_LIBGME=1 endif @@ -293,11 +294,11 @@ ifdef NOHW else OPTS+=-DHWRENDER OBJS+=$(OBJDIR)/hw_bsp.o $(OBJDIR)/hw_draw.o \ - $(OBJDIR)/hw_main.o $(OBJDIR)/hw_clip.o $(OBJDIR)/hw_md2.o $(OBJDIR)/hw_cache.o \ + $(OBJDIR)/hw_main.o $(OBJDIR)/hw_clip.o $(OBJDIR)/hw_md2.o $(OBJDIR)/hw_cache.o $(OBJDIR)/hw_portal.o\ $(OBJDIR)/hw_md2load.o $(OBJDIR)/hw_md3load.o $(OBJDIR)/hw_model.o $(OBJDIR)/u_list.o $(OBJDIR)/hw_batching.o $(OBJDIR)/hw_shaders.o endif -OPTS += -DCOMPVERSION -fwrapv +OPTS += -DCOMPVERSION ifndef NONX86 ifndef GCC29 @@ -563,6 +564,7 @@ OBJS:=$(i_main_o) \ $(OBJDIR)/r_splats.o \ $(OBJDIR)/r_patch.o \ $(OBJDIR)/r_things.o \ + $(OBJDIR)/r_portal.o \ $(OBJDIR)/screen.o \ $(OBJDIR)/v_video.o \ $(OBJDIR)/s_sound.o \ @@ -736,18 +738,18 @@ else ifdef SDL ifdef MINGW $(OBJDIR)/r_opengl.o: hardware/r_opengl/r_opengl.c hardware/r_opengl/r_opengl.h \ - doomdef.h doomtype.h g_state.h m_swap.h hardware/hw_drv.h screen.h \ + doomdef.h doomtype.h g_state.h m_swap.h hardware/hw_gl.h screen.h \ command.h hardware/hw_data.h hardware/hw_defs.h hardware/hw_md2.h \ - hardware/hw_glob.h hardware/hw_main.h hardware/hw_clip.h \ + hardware/hw_glob.h hardware/hw_main.h hardware/hw_clip.h hardware/hw_portal.h\ hardware/hw_md2load.h hardware/hw_md3load.h hardware/hw_model.h hardware/u_list.h \ am_map.h d_event.h d_player.h p_pspr.h m_fixed.h tables.h info.h d_think.h \ p_mobj.h doomdata.h d_ticcmd.h r_defs.h hardware/hw_dll.h $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@ else $(OBJDIR)/r_opengl.o: hardware/r_opengl/r_opengl.c hardware/r_opengl/r_opengl.h \ - doomdef.h doomtype.h g_state.h m_swap.h hardware/hw_drv.h screen.h \ + doomdef.h doomtype.h g_state.h m_swap.h hardware/hw_gl.h screen.h \ command.h hardware/hw_data.h hardware/hw_defs.h hardware/hw_md2.h \ - hardware/hw_glob.h hardware/hw_main.h hardware/hw_clip.h \ + hardware/hw_glob.h hardware/hw_main.h hardware/hw_clip.h hardware/hw_portal.h \ hardware/hw_md2load.h hardware/hw_md3load.h hardware/hw_model.h hardware/u_list.h \ am_map.h d_event.h d_player.h p_pspr.h m_fixed.h tables.h info.h d_think.h \ p_mobj.h doomdata.h d_ticcmd.h r_defs.h hardware/hw_dll.h diff --git a/src/am_map.c b/src/am_map.c index ac8236b41..3c10f710d 100644 --- a/src/am_map.c +++ b/src/am_map.c @@ -1,8 +1,10 @@ -// SONIC ROBO BLAST 2 +// SONIC ROBO BLAST 2 KART //----------------------------------------------------------------------------- // Copyright (C) 1993-1996 by id Software, Inc. -// Copyright (C) 1998-2000 by DooM Legacy Team. -// Copyright (C) 1999-2018 by Sonic Team Junior. +// Copyright (C) 2024 by Vivian "toastergrl" Grannell. +// Copyright (C) 2024 by Kart Krew. +// Copyright (C) 2020 by Sonic Team Junior. +// Copyright (C) 2000 by DooM Legacy Team. // // This program is free software distributed under the // terms of the GNU General Public License, version 2. @@ -26,43 +28,37 @@ #endif // For use if I do walls with outsides/insides -static const UINT8 REDS = (8*16); +static const UINT8 REDS = (2*16); static const UINT8 REDRANGE = 16; static const UINT8 GRAYS = (1*16); static const UINT8 GRAYSRANGE = 16; -static const UINT8 BROWNS = (3*16); -static const UINT8 YELLOWS = (7*16); -static const UINT8 GREENS = (10*16); +static const UINT8 BROWNS = (15*16); +static const UINT8 YELLOWS = (5*16)+8; +static const UINT8 GREENS = (6*16); +static const UINT8 BLUES = (9*16); static const UINT8 DBLACK = 31; static const UINT8 DWHITE = 0; -static const UINT8 NOCLIMBREDS = 248; -static const UINT8 NOCLIMBREDRANGE = 8; -static const UINT8 NOCLIMBGRAYS = 204; -static const UINT8 NOCLIMBBROWNS = (2*16); -static const UINT8 NOCLIMBYELLOWS = (11*16); - // Automap colors #define BACKGROUND DBLACK #define WALLCOLORS (REDS + REDRANGE/2) #define WALLRANGE (REDRANGE/2) -#define NOCLIMBWALLCOLORS (NOCLIMBREDS + NOCLIMBREDRANGE/2) -#define NOCLIMBWALLRANGE (NOCLIMBREDRANGE/2) #define THOKWALLCOLORS REDS #define THOKWALLRANGE REDRANGE -#define NOCLIMBTHOKWALLCOLORS NOCLIMBREDS -#define NOCLIMBTHOKWALLRANGE NOCLIMBREDRANGE -#define TSWALLCOLORS GRAYS -#define TSWALLRANGE GRAYSRANGE -#define NOCLIMBTSWALLCOLORS NOCLIMBGRAYS +#define TSWALLCOLORS DWHITE +#define TSFINISHLINE GRAYS +#define TSFOFINFO (BLUES + 4) #define FDWALLCOLORS BROWNS -#define NOCLIMBFDWALLCOLORS NOCLIMBBROWNS #define CDWALLCOLORS YELLOWS -#define NOCLIMBCDWALLCOLORS NOCLIMBYELLOWS #define THINGCOLORS GREENS #define GRIDCOLORS (GRAYS + GRAYSRANGE/2) #define XHAIRCOLORS GRAYS +// Automap passes +#define PASS_SOLID 1 +#define PASS_INTANGIBLE 2 +#define PASS_FOF 4 + // controls #define AM_PANUPKEY KEY_UPARROW #define AM_PANDOWNKEY KEY_DOWNARROW @@ -110,11 +106,6 @@ typedef struct mpoint_t a, b; } mline_t; -typedef struct -{ - fixed_t slp, islp; -} islope_t; - // // The vector graphics for the automap. // A line drawing of the player pointing right, @@ -136,16 +127,14 @@ static const mline_t player_arrow[] = { #undef R #define NUMPLYRLINES (sizeof (player_arrow)/sizeof (mline_t)) -#if 0 #define R (FRACUNIT) -static mline_t triangle_guy[] = { - { { (fixed_t)-.867f*R, (fixed_t)-.5f*R }, { (fixed_t) .867f*R, (fixed_t)-.5f*R } }, - { { (fixed_t) .867f*R, (fixed_t)-.5f*R }, { (fixed_t) 0, (fixed_t) R } }, - { { (fixed_t) 0, (fixed_t) R }, { (fixed_t)-.867f*R, (fixed_t)-.5f*R } } +static const mline_t cross_mark[] = +{ + { { -R, 0 }, { R, 0} }, + { { 0, -R }, { 0, R } }, }; #undef R -#define NUMTRIANGLEGUYLINES (sizeof (triangle_guy)/sizeof (mline_t)) -#endif +#define NUMCROSSMARKLINES (sizeof(cross_mark)/sizeof(mline_t)) #define R (FRACUNIT) static const mline_t thintriangle_guy[] = { @@ -162,10 +151,14 @@ static boolean draw_grid = false; boolean automapactive = false; boolean am_recalc = false; //added : 05-02-98 : true when screen size changes static boolean am_stopped = true; +static boolean am_minigen = false; + +static UINT8 *am_buf = NULL; static INT32 f_x, f_y; // location of window on screen (always zero for both) static INT32 f_w, f_h; // size of window on screen (always the screen width and height respectively) +static boolean m_keydown[4]; // which window panning keys are being pressed down? static mpoint_t m_paninc; // how far the window pans each tic (map coords) static fixed_t mtof_zoommul; // how far the window zooms in each tic (map coords) static fixed_t ftom_zoommul; // how far the window zooms in each tic (fb coords) @@ -205,12 +198,13 @@ static fixed_t scale_ftom; static player_t *plr; // the player represented by an arrow -static INT32 followplayer = true; // specifies whether to follow the player around +static boolean followplayer = true; // specifies whether to follow the player around // function for drawing lines, depends on rendermode typedef void (*AMDRAWFLINEFUNC) (const fline_t *fl, INT32 color); static AMDRAWFLINEFUNC AM_drawFline; +static void AM_drawPixel(INT32 xx, INT32 yy, INT32 cc); static void AM_drawFline_soft(const fline_t *fl, INT32 color); static void AM_activateNewScale(void) @@ -340,22 +334,23 @@ static void AM_initVariables(void) old_m_h = m_h; } +// +// Called when the screen size changes. +// +static void AM_FrameBufferInit(void) +{ + f_x = f_y = 0; + f_w = vid.width; + f_h = vid.height; + am_buf = screens[0]; +} + // // should be called at the start of every level // right now, i figure it out myself // static void AM_LevelInit(void) { - f_x = f_y = 0; - f_w = vid.width; - f_h = vid.height; - - AM_drawFline = AM_drawFline_soft; -#ifdef HWRENDER - if (rendermode == render_opengl) - AM_drawFline = HWR_drawAMline; -#endif - AM_findMinMaxBoundaries(); scale_mtof = FixedDiv(min_scale_mtof*10, 7*FRACUNIT); if (scale_mtof > max_scale_mtof) @@ -377,7 +372,7 @@ void AM_Stop(void) * * \sa AM_Stop */ -static inline void AM_Start(void) +void AM_Start(void) { static INT32 lastlevel = -1; @@ -386,8 +381,12 @@ static inline void AM_Start(void) am_stopped = false; if (lastlevel != gamemap || am_recalc) // screen size changed { - AM_LevelInit(); - lastlevel = gamemap; + AM_FrameBufferInit(); + if (lastlevel != gamemap) + { + AM_LevelInit(); + lastlevel = gamemap; + } am_recalc = false; } AM_initVariables(); @@ -413,6 +412,27 @@ static void AM_maxOutWindowScale(void) AM_activateNewScale(); } +// +// set window panning +// +static void AM_setWindowPanning(void) +{ + // up and down + if (m_keydown[2]) // pan up + m_paninc.y = FTOM(F_PANINC); + else if (m_keydown[3]) // pan down + m_paninc.y = -FTOM(F_PANINC); + else + m_paninc.y = 0; + // left and right + if (m_keydown[0]) // pan right + m_paninc.x = FTOM(F_PANINC); + else if (m_keydown[1]) // pan left + m_paninc.x = -FTOM(F_PANINC); + else + m_paninc.x = 0; +} + /** Responds to user inputs in automap mode. * * \param ev Event to possibly respond to. @@ -445,35 +465,49 @@ boolean AM_Responder(event_t *ev) { case AM_PANRIGHTKEY: // pan right if (!followplayer) - m_paninc.x = FTOM(F_PANINC); + { + m_keydown[0] = true; + AM_setWindowPanning(); + } else rc = false; break; case AM_PANLEFTKEY: // pan left if (!followplayer) - m_paninc.x = -FTOM(F_PANINC); + { + m_keydown[1] = true; + AM_setWindowPanning(); + } else rc = false; break; case AM_PANUPKEY: // pan up if (!followplayer) - m_paninc.y = FTOM(F_PANINC); + { + m_keydown[2] = true; + AM_setWindowPanning(); + } else rc = false; break; case AM_PANDOWNKEY: // pan down if (!followplayer) - m_paninc.y = -FTOM(F_PANINC); + { + m_keydown[3] = true; + AM_setWindowPanning(); + } else rc = false; break; case AM_ZOOMOUTKEY: // zoom out mtof_zoommul = M_ZOOMOUT; ftom_zoommul = M_ZOOMIN; + AM_setWindowPanning(); break; case AM_ZOOMINKEY: // zoom in mtof_zoommul = M_ZOOMIN; ftom_zoommul = M_ZOOMOUT; + AM_setWindowPanning(); break; case AM_TOGGLEKEY: AM_Stop(); @@ -487,6 +521,7 @@ boolean AM_Responder(event_t *ev) } else AM_restoreScaleAndLoc(); + AM_setWindowPanning(); break; case AM_FOLLOWKEY: followplayer = !followplayer; @@ -506,14 +541,32 @@ boolean AM_Responder(event_t *ev) switch (ev->data1) { case AM_PANRIGHTKEY: + if (!followplayer) + { + m_keydown[0] = false; + AM_setWindowPanning(); + } + break; case AM_PANLEFTKEY: if (!followplayer) - m_paninc.x = 0; + { + m_keydown[1] = false; + AM_setWindowPanning(); + } break; case AM_PANUPKEY: + if (!followplayer) + { + m_keydown[2] = false; + AM_setWindowPanning(); + } + break; case AM_PANDOWNKEY: if (!followplayer) - m_paninc.y = 0; + { + m_keydown[3] = false; + AM_setWindowPanning(); + } break; case AM_ZOOMOUTKEY: case AM_ZOOMINKEY: @@ -714,6 +767,16 @@ static boolean AM_clipMline(const mline_t *ml, fline_t *fl) } #undef DOOUTCODE +// +// Draws a pixel. +// +static void AM_drawPixel(INT32 xx, INT32 yy, INT32 cc) +{ + if (xx < 0 || yy < 0 || xx >= f_w || yy >= f_h) + return; // off the screen + am_buf[(yy*f_w) + xx] = cc; +} + // // Classic Bresenham w/ whatever optimizations needed for speed // @@ -735,8 +798,6 @@ static void AM_drawFline_soft(const fline_t *fl, INT32 color) } #endif - #define PUTDOT(xx,yy,cc) V_DrawFill(xx,yy,1,1,cc|V_NOSCALESTART); - dx = fl->b.x - fl->a.x; ax = 2 * (dx < 0 ? -dx : dx); sx = dx < 0 ? -1 : 1; @@ -753,7 +814,7 @@ static void AM_drawFline_soft(const fline_t *fl, INT32 color) d = ay - ax/2; for (;;) { - PUTDOT(x, y, color) + AM_drawPixel(x, y, color); if (x == fl->b.x) return; if (d >= 0) @@ -770,7 +831,7 @@ static void AM_drawFline_soft(const fline_t *fl, INT32 color) d = ax - ay/2; for (;;) { - PUTDOT(x, y, color) + AM_drawPixel(x, y, color); if (y == fl->b.y) return; if (d >= 0) @@ -782,8 +843,6 @@ static void AM_drawFline_soft(const fline_t *fl, INT32 color) d += ax; } } - - #undef PUTDOT } // @@ -805,17 +864,18 @@ static void AM_drawGrid(INT32 color) fixed_t x, y; fixed_t start, end; mline_t ml; + fixed_t gridsize = (MAPBLOCKUNITS<>FRACTOMAPBITS)) % gridsize) + start += gridsize - ((start - (bmaporgx>>FRACTOMAPBITS)) % gridsize); end = m_x + m_w; // draw vertical gridlines ml.a.y = m_y; ml.b.y = m_y + m_h; - for (x = start; x < end; x += (MAPBLOCKUNITS<>FRACTOMAPBITS)) % gridsize) + start += gridsize - ((start - (bmaporgy>>FRACTOMAPBITS)) % gridsize); end = m_y + m_h; // draw horizontal gridlines ml.a.x = m_x; ml.b.x = m_x + m_w; - for (y = start; y < end; y += (MAPBLOCKUNITS<x, lines[i].v1->y) + FRACUNIT/2) >> FRACBITS; \ + end2 = (P_GetZAt(slope, lines[i].v2->x, lines[i].v2->y) + FRACUNIT/2) >> FRACBITS; \ + } else \ + end1 = end2 = (normalheight + FRACUNIT/2) >> FRACBITS; + +static ffloor_t *AM_CompareFOFs(size_t i, ffloor_t *rover, ffloor_t *secondarystore) +{ + ffloor_t *secondaryrover = NULL; + for (; rover; rover = rover->next) + { + fixed_t rovt1, rovt2; + fixed_t rovb1, rovb2; + if (!(rover->flags & FF_EXISTS)) + continue; + if (!(rover->flags & FF_BLOCKPLAYER)) + continue; + SLOPEPARAMS(*rover->t_slope, rovt1, rovt2, *rover->topheight) + SLOPEPARAMS(*rover->b_slope, rovb1, rovb2, *rover->bottomheight) + for (secondaryrover = secondarystore; secondaryrover; secondaryrover = secondaryrover->next) + { + fixed_t sect1, sect2; + fixed_t secb1, secb2; + if (!(secondaryrover->flags & FF_EXISTS)) + continue; + if (!(secondaryrover->flags & FF_BLOCKPLAYER)) + continue; + if (secondaryrover->secnum == rover->secnum) + break; + SLOPEPARAMS(*secondaryrover->t_slope, sect1, sect2, *secondaryrover->topheight) + SLOPEPARAMS(*secondaryrover->b_slope, secb1, secb2, *secondaryrover->bottomheight) + if (rovt1 != sect1) + continue; + if (rovt2 != sect2) + continue; + if (rovb1 != secb1) + continue; + if (rovb2 != secb2) + continue; + break; + } + if (secondaryrover == NULL) + break; + } + return rover; +} + // // Determines visible lines, draws them. // This is LineDef based, not LineSeg based. // -static inline void AM_drawWalls(void) +static void AM_drawWalls(UINT8 pass) { size_t i; static mline_t l; + const fixed_t maxstep = FixedMul(MAXSTEPMOVE, mapobjectscale)>>FRACBITS; fixed_t frontf1,frontf2, frontc1, frontc2; // front floor/ceiling ends fixed_t backf1 = 0, backf2 = 0, backc1 = 0, backc2 = 0; // back floor ceiling ends @@ -856,74 +965,143 @@ static inline void AM_drawWalls(void) l.a.y = lines[i].v1->y >> FRACTOMAPBITS; l.b.x = lines[i].v2->x >> FRACTOMAPBITS; l.b.y = lines[i].v2->y >> FRACTOMAPBITS; -#define SLOPEPARAMS(slope, end1, end2, normalheight) \ - if (slope) { \ - end1 = P_GetZAt(slope, lines[i].v1->x, lines[i].v1->y); \ - end2 = P_GetZAt(slope, lines[i].v2->x, lines[i].v2->y); \ - } else \ - end1 = end2 = normalheight; SLOPEPARAMS(lines[i].frontsector->f_slope, frontf1, frontf2, lines[i].frontsector->floorheight) SLOPEPARAMS(lines[i].frontsector->c_slope, frontc1, frontc2, lines[i].frontsector->ceilingheight) - if (lines[i].backsector) { - SLOPEPARAMS(lines[i].backsector->f_slope, backf1, backf2, lines[i].backsector->floorheight) - SLOPEPARAMS(lines[i].backsector->c_slope, backc1, backc2, lines[i].backsector->ceilingheight) - } -#undef SLOPEPARAMS if (!lines[i].backsector) // 1-sided { - if (lines[i].flags & ML_NOCLIMB) - AM_drawMline(&l, NOCLIMBWALLCOLORS); - else + if (!(pass & PASS_SOLID)) + ; + else if (frontf1 != frontc1 || frontf2 != frontc2 || lines[i].frontsector->f_slope) + { + AM_drawMline(&l, TSWALLCOLORS); + } + else if (!am_minigen) + { AM_drawMline(&l, WALLCOLORS); + } + continue; } - else if ((backf1 == backc1 && backf2 == backc2) // Back is thok barrier + SLOPEPARAMS(lines[i].backsector->f_slope, backf1, backf2, lines[i].backsector->floorheight) + SLOPEPARAMS(lines[i].backsector->c_slope, backc1, backc2, lines[i].backsector->ceilingheight) + if ((backf1 == backc1 && backf2 == backc2) // Back is thok barrier || (frontf1 == frontc1 && frontf2 == frontc2)) // Front is thok barrier { if (backf1 == backc1 && backf2 == backc2 && frontf1 == frontc1 && frontf2 == frontc2) // BOTH are thok barriers { - if (lines[i].flags & ML_NOCLIMB) - AM_drawMline(&l, NOCLIMBTSWALLCOLORS); - else - AM_drawMline(&l, TSWALLCOLORS); + if (!am_minigen && (pass & PASS_INTANGIBLE)) + { + AM_drawMline(&l, GRIDCOLORS); + } } - else + else if (pass & PASS_SOLID) { - if (lines[i].flags & ML_NOCLIMB) - AM_drawMline(&l, NOCLIMBTHOKWALLCOLORS); - else - AM_drawMline(&l, THOKWALLCOLORS); + AM_drawMline(&l, TSWALLCOLORS); } } else { - if (lines[i].flags & ML_NOCLIMB) { - if (backf1 != frontf1 || backf2 != frontf2) { - AM_drawMline(&l, NOCLIMBFDWALLCOLORS); // floor level change - } - else if (backc1 != frontc1 || backc2 != frontc2) { - AM_drawMline(&l, NOCLIMBCDWALLCOLORS); // ceiling level change + //dont think kart even supports those idk? + /*if (lines[i].flags & (ML_IMPASSABLE|ML_BLOCKPLAYERS)) + { + if (pass & PASS_SOLID) + AM_drawMline(&l, TSWALLCOLORS); // Completely solid course boundary + } + else if ((lines[i].flags & ML_MIDSOLID) + && sides[lines->sidenum[0]].midtexture) + { + if (pass & PASS_SOLID) + AM_drawMline(&l, TSWALLCOLORS); // solid midtexture, likely a course boundary + }*/ + if ((backf1 != frontf1 && abs(backf1 - frontf1) > maxstep) + || (backf2 != frontf2 && abs(backf2 - frontf2) > maxstep)) + { + if (pass & PASS_SOLID) + AM_drawMline(&l, TSWALLCOLORS); // floor-wall, likely a course boundary + } + /*else if (lines[i].special == 2001) // guh its a sector effect in kart idk how to make it work tbh lol + { + if (pass & PASS_SOLID) + AM_drawMline(&l, TSFINISHLINE); // finish line + }*/ + else if (backf1 != frontf1 || backf2 != frontf2) + { + if (pass & PASS_INTANGIBLE) + AM_drawMline(&l, FDWALLCOLORS); // floorlevel change + } + else if (backc1 != frontc1 || backc2 != frontc2) + { + if (!(pass & PASS_INTANGIBLE)) + ; + else if (abs(backc1 - frontc1) < maxstep + || abs(backc2 - frontc2) < maxstep) + { + AM_drawMline(&l, CDWALLCOLORS); // ceilinglevel change } else - AM_drawMline(&l, NOCLIMBTSWALLCOLORS); + { + AM_drawMline(&l, GRIDCOLORS); // ceiling-wall, not likely to be a course boundary but flagged up just in case + } } else { - if (backf1 != frontf1 || backf2 != frontf2) { - AM_drawMline(&l, FDWALLCOLORS); // floor level change + { + ffloor_t *rover = NULL; + + if (lines[i].frontsector->ffloors || lines[i].backsector->ffloors) + { + if (lines[i].backsector->ffloors == NULL) + { + // Check frontside for one solid + for (rover = lines[i].frontsector->ffloors; rover; rover = rover->next) + { + if (!(rover->flags & FF_EXISTS)) + continue; + if (!(rover->flags & FF_BLOCKPLAYER)) + continue; + break; + } + } + else if (lines[i].frontsector->ffloors == NULL) + { + // Check backside for one solid + for (rover = lines[i].backsector->ffloors; rover; rover = rover->next) + { + if (!(rover->flags & FF_EXISTS)) + continue; + if (!(rover->flags & FF_BLOCKPLAYER)) + continue; + break; + } + } + else + { + // Check to see if any secnums exist in one but not the other. + rover = AM_CompareFOFs(i, lines[i].frontsector->ffloors, lines[i].backsector->ffloors); + if (rover == NULL) + rover = AM_CompareFOFs(i, lines[i].backsector->ffloors, lines[i].frontsector->ffloors); + } + } + if (rover != NULL) + { + if (pass & PASS_FOF) + AM_drawMline(&l, TSFOFINFO); // a FOF is here but we don't know how to distinguish them yet + } + else if (!am_minigen) + { + if (pass & PASS_INTANGIBLE) + AM_drawMline(&l, GRIDCOLORS); // likely low-relevance line + } } - else if (backc1 != frontc1 || backc2 != frontc2) { - AM_drawMline(&l, CDWALLCOLORS); // ceiling level change - } - else - AM_drawMline(&l, TSWALLCOLORS); } } } } +#undef SLOPEPARAMS + // // Rotation in 2D. // Used to rotate player arrow line character. @@ -996,7 +1174,7 @@ static inline void AM_drawPlayers(void) if (!multiplayer) { - AM_drawLineCharacter(player_arrow, NUMPLYRLINES, 0, plr->mo->angle, DWHITE, plr->mo->x, plr->mo->y); + AM_drawLineCharacter(player_arrow, NUMPLYRLINES, 16<mo->angle, DWHITE, plr->mo->x, plr->mo->y); return; } @@ -1013,7 +1191,7 @@ static inline void AM_drawPlayers(void) if (p->skincolor > 0) color = R_GetTranslationColormap(TC_DEFAULT, p->skincolor, GTC_CACHE)[GREENS + 8]; - AM_drawLineCharacter(player_arrow, NUMPLYRLINES, 0, p->mo->angle, color, p->mo->x, p->mo->y); + AM_drawLineCharacter(player_arrow, NUMPLYRLINES, 16<mo->angle, color, p->mo->x, p->mo->y); } } @@ -1033,13 +1211,27 @@ static inline void AM_drawThings(UINT8 colors) } } -/** Draws the crosshair, actually just a dot in software mode. +/** Draws the crosshair. * * \param color Color for the crosshair. */ static inline void AM_drawCrosshair(UINT8 color) { - V_DrawFill(f_w/2 + f_x, f_h/2 + f_y, 1, 1, color|V_NOSCALESTART); + const fixed_t scale = 4<> FRACBITS; + fl.a.y = FixedMul(cross_mark[i].a.y, scale) >> FRACBITS; + fl.b.x = FixedMul(cross_mark[i].b.x, scale) >> FRACBITS; + fl.b.y = FixedMul(cross_mark[i].b.y, scale) >> FRACBITS; + fl.a.x += f_x + (f_w / 2); + fl.a.y += f_y + (f_h / 2); + fl.b.x += f_x + (f_w / 2); + fl.b.y += f_y + (f_h / 2); + AM_drawFline(&fl, color); + } } /** Draws the automap. @@ -1049,11 +1241,80 @@ void AM_Drawer(void) if (!automapactive) return; + AM_drawFline = AM_drawFline_soft; +#ifdef HWRENDER + if (rendermode == render_opengl) + AM_drawFline = HWR_drawAMline; +#endif + AM_clearFB(BACKGROUND); if (draw_grid) AM_drawGrid(GRIDCOLORS); - AM_drawWalls(); + AM_drawWalls(PASS_FOF|PASS_INTANGIBLE|PASS_SOLID); AM_drawPlayers(); AM_drawThings(THINGCOLORS); - AM_drawCrosshair(XHAIRCOLORS); + if (!followplayer) AM_drawCrosshair(XHAIRCOLORS); +} + +minigen_t *AM_MinimapGenerate(INT32 mul) +{ + static minigen_t ret = {0}; + + if (automapactive) + return NULL; + + am_minigen = true; + + AM_drawFline = AM_drawFline_soft; // yes, even in GL + + //AM_FrameBufferInit(); + f_x = f_y = 0; + ret.w = f_w = minimapinfo.minimap_w * mul; + ret.h = f_h = minimapinfo.minimap_h * mul; + am_buf = ret.buf = NULL; + + //AM_LevelInit(); + AM_findMinMaxBoundaries(); + scale_mtof = min_scale_mtof - (min_scale_mtof/20); + scale_ftom = FixedDiv(FRACUNIT, scale_mtof); + + //AM_initVariables(); + f_oldloc.x = INT32_MAX; + + m_paninc.x = m_paninc.y = 0; + ftom_zoommul = FRACUNIT; + mtof_zoommul = FRACUNIT; + + m_w = FTOM(f_w); + m_h = FTOM(f_h); + + //AM_changeWindowLoc(); + m_x = min_x - FixedMul(m_w, FRACUNIT/40); + m_y = min_y - FixedMul(m_h, FRACUNIT/40); + m_x2 = m_x + m_w; + m_y2 = m_y + m_h; + + // for saving & restoring + old_m_x = m_x; + old_m_y = m_y; + old_m_w = m_w; + old_m_h = m_h; + + am_buf = ret.buf = malloc((f_w*f_h)); + + if (ret.buf == NULL) + return NULL; + + //AM_clearFB(BACKGROUND); + memset(am_buf, 0xff, (f_w*f_h)); + AM_drawWalls(PASS_FOF); + AM_drawWalls(PASS_INTANGIBLE); + AM_drawWalls(PASS_SOLID); + + am_buf = NULL; + am_recalc = true; + + am_minigen = false; + + return &ret; } diff --git a/src/am_map.h b/src/am_map.h index 4e8c782a9..112ba345f 100644 --- a/src/am_map.h +++ b/src/am_map.h @@ -1,8 +1,10 @@ -// SONIC ROBO BLAST 2 +// SONIC ROBO BLAST 2 KART //----------------------------------------------------------------------------- // Copyright (C) 1993-1996 by id Software, Inc. -// Copyright (C) 1998-2000 by DooM Legacy Team. -// Copyright (C) 1999-2018 by Sonic Team Junior. +// Copyright (C) 2024 by Vivian "toastergrl" Grannell. +// Copyright (C) 2024 by Kart Krew. +// Copyright (C) 2020 by Sonic Team Junior. +// Copyright (C) 2000 by DooM Legacy Team. // // This program is free software distributed under the // terms of the GNU General Public License, version 2. @@ -26,11 +28,6 @@ typedef struct fpoint_t a, b; } fline_t; -// Used by ST StatusBar stuff. -#define AM_MSGHEADER (('a'<<24)+('m'<<16)) -#define AM_MSGENTERED (AM_MSGHEADER | ('e'<<8)) -#define AM_MSGEXITED (AM_MSGHEADER | ('x'<<8)) - extern boolean am_recalc; // true if screen size changes extern boolean automapactive; // In AutoMap mode? @@ -43,7 +40,19 @@ void AM_Ticker(void); // Called by main loop, instead of view drawer if automap is active. void AM_Drawer(void); +// Enables the automap. +void AM_Start(void); + // Called to force the automap to quit if the level is completed while it is up. void AM_Stop(void); +typedef struct +{ + INT32 w, h; + UINT8 *buf; +} minigen_t; + +// Minimap generation +minigen_t *AM_MinimapGenerate(INT32 mul); + #endif diff --git a/src/b_bot.c b/src/b_bot.c index edaf477ad..8100fc414 100644 --- a/src/b_bot.c +++ b/src/b_bot.c @@ -36,7 +36,7 @@ static inline void B_BuildTailsTiccmd(mobj_t *sonic, mobj_t *tails, ticcmd_t *cm return; // Lua can handle it! - if (LUAh_BotAI(sonic, tails, cmd)) + if (LUA_HookBotAI(sonic, tails, cmd)) return; if (tails->player->pflags & (PF_MACESPIN|PF_ITEMHANG)) @@ -118,11 +118,8 @@ void B_BuildTiccmd(player_t *player, ticcmd_t *cmd) return; } - // Bot AI isn't programmed in analog. - //CV_SetValue(&cv_analog2, false); - // Let Lua scripts build ticcmds - if (LUAh_BotTiccmd(player, cmd)) + if (LUA_HookTiccmd(player, cmd, HOOK(BotTiccmd))) return; // We don't have any main character AI, sorry. D: diff --git a/src/byteptr.h b/src/byteptr.h index 9756e7d95..0345038b8 100644 --- a/src/byteptr.h +++ b/src/byteptr.h @@ -1,7 +1,7 @@ // SONIC ROBO BLAST 2 //----------------------------------------------------------------------------- // Copyright (C) 1998-2000 by DooM Legacy Team. -// Copyright (C) 1999-2018 by Sonic Team Junior. +// Copyright (C) 1999-2024 by Sonic Team Junior. // // This program is free software distributed under the // terms of the GNU General Public License, version 2. @@ -11,6 +11,9 @@ /// \brief Macros to read/write from/to a UINT8 *, /// used for packet creation and such +#ifndef __BYTEPTR_H__ +#define __BYTEPTR_H__ + #if defined (__alpha__) || defined (__arm__) || defined (__mips__) || defined (__ia64__) || defined (__clang__) #define DEALIGNED #endif @@ -150,7 +153,7 @@ FUNCINLINE static ATTRINLINE UINT32 readulong(void *ptr) #undef DEALIGNED -#define WRITESTRINGN(p, s, n) ({ \ +#define WRITESTRINGN(p, s, n) do { \ size_t tmp_i; \ \ for (tmp_i = 0; tmp_i < n && s[tmp_i] != '\0'; tmp_i++) \ @@ -158,70 +161,72 @@ FUNCINLINE static ATTRINLINE UINT32 readulong(void *ptr) \ if (tmp_i < n) \ WRITECHAR(p, '\0'); \ -}) +} while (0) -#define WRITESTRINGL(p, s, n) ({ \ +#define WRITESTRINGL(p, s, n) do { \ size_t tmp_i; \ \ for (tmp_i = 0; tmp_i < n - 1 && s[tmp_i] != '\0'; tmp_i++) \ WRITECHAR(p, s[tmp_i]); \ \ WRITECHAR(p, '\0'); \ -}) +} while (0) -#define WRITESTRING(p, s) ({ \ +#define WRITESTRING(p, s) do { \ size_t tmp_i; \ \ for (tmp_i = 0; s[tmp_i] != '\0'; tmp_i++) \ WRITECHAR(p, s[tmp_i]); \ \ WRITECHAR(p, '\0'); \ -}) +} while (0) -#define WRITEMEM(p, s, n) ({ \ - memcpy(p, s, n); \ - p += n; \ -}) +#define WRITEMEM(p, s, n) do { \ + memcpy(p, s, n); \ + p += n; \ +} while (0) #define SKIPSTRING(p) while (READCHAR(p) != '\0') -#define SKIPSTRINGN(p, n) ({ \ +#define SKIPSTRINGN(p, n) do { \ size_t tmp_i = 0; \ \ while (tmp_i < n && READCHAR(p) != '\0') \ tmp_i++; \ -}) +} while (0) #define SKIPSTRINGL(p, n) SKIPSTRINGN(p, n) -#define READSTRINGN(p, s, n) ({ \ +#define READSTRINGN(p, s, n) do { \ size_t tmp_i = 0; \ \ while (tmp_i < n && (s[tmp_i] = READCHAR(p)) != '\0') \ tmp_i++; \ \ s[tmp_i] = '\0'; \ -}) +} while (0) -#define READSTRINGL(p, s, n) ({ \ +#define READSTRINGL(p, s, n) do { \ size_t tmp_i = 0; \ \ while (tmp_i < n - 1 && (s[tmp_i] = READCHAR(p)) != '\0') \ tmp_i++; \ \ s[tmp_i] = '\0'; \ -}) +} while (0) -#define READSTRING(p, s) ({ \ +#define READSTRING(p, s) do { \ size_t tmp_i = 0; \ \ while ((s[tmp_i] = READCHAR(p)) != '\0') \ tmp_i++; \ \ s[tmp_i] = '\0'; \ -}) +} while (0) -#define READMEM(p, s, n) ({ \ - memcpy(s, p, n); \ - p += n; \ -}) +#define READMEM(p, s, n) do { \ + memcpy(s, p, n); \ + p += n; \ +} while (0) + +#endif // __BYTEPTR_H__ diff --git a/src/command.c b/src/command.c index b7e1e01de..fa84626fb 100644 --- a/src/command.c +++ b/src/command.c @@ -628,7 +628,7 @@ static void COM_ExecuteString(char *ptext) // check cvars // Hurdler: added at Ebola's request ;) - // (don't flood the console in software mode with bad gr_xxx command) + // (don't flood the console in software mode with bad gl_xxx command) if (!CV_Command() && con_destlines) CONS_Printf(M_GetText("Unknown command '%s'\n"), COM_Argv(0)); } diff --git a/src/console.c b/src/console.c index 9781078fa..f36b3b7cb 100644 --- a/src/console.c +++ b/src/console.c @@ -1236,7 +1236,7 @@ void CONS_Printf(const char *fmt, ...) txt = malloc(8192); va_start(argptr, fmt); - vsprintf(txt, fmt, argptr); + vsnprintf(txt, 8192, fmt, argptr); va_end(argptr); // echo console prints to log file diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 057aff951..5d04b98e0 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -50,6 +50,7 @@ #include "s_sound.h" // sfx_syfail #include "m_perfstats.h" #include "d_main.h" +#include "r_fps.h" #ifdef CLIENT_LOADINGSCREEN // cl loading screen @@ -139,10 +140,7 @@ static UINT8 gamestate_resend_counter[MAXNETNODES]; boolean hu_stopped = false; // Client specific -static ticcmd_t localcmds; -static ticcmd_t localcmds2; -static ticcmd_t localcmds3; -static ticcmd_t localcmds4; +static ticcmd_t localcmds[MAXSPLITSCREENPLAYERS]; static boolean cl_packetmissed; // here it is for the secondary local player (splitscreen) static UINT8 mynode; // my address pointofview server @@ -159,10 +157,7 @@ boolean is_client_saturn[MAXNETNODES]; #define ISSATURN 69 #endif -static UINT8 localtextcmd[MAXTEXTCMD]; -static UINT8 localtextcmd2[MAXTEXTCMD]; // splitscreen -static UINT8 localtextcmd3[MAXTEXTCMD]; // splitscreen == 2 -static UINT8 localtextcmd4[MAXTEXTCMD]; // splitscreen == 3 +static UINT8 localtextcmd[MAXSPLITSCREENPLAYERS][MAXTEXTCMD]; static tic_t neededtic; SINT8 servernode = 0; // the number of the server node char connectedservername[MAXSERVERNAME+1]; @@ -276,77 +271,30 @@ void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(UINT8 **p, INT32 playernum)) listnetxcmd[id] = cmd_f; } -void SendNetXCmd(netxcmd_t id, const void *param, size_t nparam) +void SendNetXCmdForPlayer(UINT8 playerid, netxcmd_t id, const void *param, size_t nparam) { - if (localtextcmd[0]+2+nparam > MAXTEXTCMD) + if ((localtextcmd[playerid])[0]+2+nparam > MAXTEXTCMD) { - // for future reference: if (cv_debug) != debug disabled. - CONS_Alert(CONS_ERROR, M_GetText("NetXCmd buffer full, cannot add netcmd %d! (size: %d, needed: %s)\n"), id, localtextcmd[0], sizeu1(nparam)); + // for future reference: if (cht_debug) != debug disabled. + CONS_Alert(CONS_ERROR, M_GetText("NetXCmd buffer full, cannot add netcmd %d! (size: %d, needed: %s)\n"), id, localtextcmd[playerid][0], sizeu1(nparam)); return; } - localtextcmd[0]++; - localtextcmd[localtextcmd[0]] = (UINT8)id; + + localtextcmd[playerid][0]++; + localtextcmd[playerid][localtextcmd[playerid][0]] = (UINT8)id; + if (param && nparam) { - M_Memcpy(&localtextcmd[localtextcmd[0]+1], param, nparam); - localtextcmd[0] = (UINT8)(localtextcmd[0] + (UINT8)nparam); + M_Memcpy(&localtextcmd[playerid][localtextcmd[playerid][0] + 1], param, nparam); + localtextcmd[playerid][0] = (UINT8)(localtextcmd[playerid][0] + (UINT8)nparam); } } -// splitscreen player -void SendNetXCmd2(netxcmd_t id, const void *param, size_t nparam) -{ - if (localtextcmd2[0]+2+nparam > MAXTEXTCMD) - { - I_Error("No more place in the buffer for netcmd %d\n",id); - return; - } - localtextcmd2[0]++; - localtextcmd2[localtextcmd2[0]] = (UINT8)id; - if (param && nparam) - { - M_Memcpy(&localtextcmd2[localtextcmd2[0]+1], param, nparam); - localtextcmd2[0] = (UINT8)(localtextcmd2[0] + (UINT8)nparam); - } -} - -void SendNetXCmd3(netxcmd_t id, const void *param, size_t nparam) -{ - if (localtextcmd3[0]+2+nparam > MAXTEXTCMD) - { - I_Error("No more place in the buffer for netcmd %d\n",id); - return; - } - localtextcmd3[0]++; - localtextcmd3[localtextcmd3[0]] = (UINT8)id; - if (param && nparam) - { - M_Memcpy(&localtextcmd3[localtextcmd3[0]+1], param, nparam); - localtextcmd3[0] = (UINT8)(localtextcmd3[0] + (UINT8)nparam); - } -} - -void SendNetXCmd4(netxcmd_t id, const void *param, size_t nparam) -{ - if (localtextcmd4[0]+2+nparam > MAXTEXTCMD) - { - I_Error("No more place in the buffer for netcmd %d\n",id); - return; - } - localtextcmd4[0]++; - localtextcmd4[localtextcmd4[0]] = (UINT8)id; - if (param && nparam) - { - M_Memcpy(&localtextcmd4[localtextcmd4[0]+1], param, nparam); - localtextcmd4[0] = (UINT8)(localtextcmd4[0] + (UINT8)nparam); - } -} - -UINT8 GetFreeXCmdSize(void) +/*UINT8 GetFreeXCmdSize(UINT8 playerid) { // -1 for the size and another -1 for the ID. - return (UINT8)(localtextcmd[0] - 2); -} + return (UINT8)(localtextcmd[playerid][0] - 2); +}*/ // Frees all textcmd memory for the specified tic static void D_FreeTextcmd(tic_t tic) @@ -510,10 +458,8 @@ void D_ResetTiccmds(void) { INT32 i; - memset(&localcmds, 0, sizeof(ticcmd_t)); - memset(&localcmds2, 0, sizeof(ticcmd_t)); - memset(&localcmds3, 0, sizeof(ticcmd_t)); - memset(&localcmds4, 0, sizeof(ticcmd_t)); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + memset(&localcmds[i], 0, sizeof(ticcmd_t)); // Reset the net command list for (i = 0; i < TEXTCMD_HASH_SIZE; i++) @@ -1228,7 +1174,7 @@ static inline void CL_DrawConnectionStatus(void) //Draw bottom box M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP, "Press ESC to abort"); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP|MENUCAPS, "Press ESC to abort"); for (i = 0; i < 16; ++i) V_DrawFill((BASEVIDWIDTH/2-128) + (i * 16), BASEVIDHEIGHT-24, 16, 8, palstart + ((animtime - i) & 15)); @@ -1275,7 +1221,7 @@ static inline void CL_DrawConnectionStatus(void) cltext = M_GetText("Connecting to server..."); break; } - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP, cltext); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP|MENUCAPS, cltext); } else { @@ -1285,7 +1231,7 @@ static inline void CL_DrawConnectionStatus(void) INT32 checkednum = 0; INT32 i; - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP, "Press ESC to abort"); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP|MENUCAPS, "Press ESC to abort"); //ima just count files here for (i = 0; i < fileneedednum; i++) @@ -1293,12 +1239,12 @@ static inline void CL_DrawConnectionStatus(void) checkednum++; // Loading progress - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP, "Checking server addons..."); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP|MENUCAPS, "Checking server addons..."); totalfileslength = (INT32)((checkednum/(double)(fileneedednum)) * 256); M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 175); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, totalfileslength, 8, 160); - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, va(" %2u/%2u Files",checkednum,fileneedednum)); } else if (cl_mode == CL_LOADFILES) @@ -1307,7 +1253,7 @@ static inline void CL_DrawConnectionStatus(void) INT32 loadcompletednum = 0; INT32 i; - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP, "Press ESC to abort"); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP|MENUCAPS, "Press ESC to abort"); //ima just count files here for (i = 0; i < fileneedednum; i++) @@ -1315,12 +1261,12 @@ static inline void CL_DrawConnectionStatus(void) loadcompletednum++; // Loading progress - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP, "Loading server addons..."); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP|MENUCAPS, "Loading server addons..."); totalfileslength = (INT32)((loadcompletednum/(double)(fileneedednum)) * 256); M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 175); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, totalfileslength, 8, 160); - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, va(" %2u/%2u Files",loadcompletednum,fileneedednum)); } else if (lastfilenum != -1) @@ -1334,7 +1280,7 @@ static inline void CL_DrawConnectionStatus(void) // Draw the bottom box. M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-58-8, 32, 1); - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-14, V_YELLOWMAP, "Press ESC to abort"); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-14, V_YELLOWMAP|MENUCAPS, "Press ESC to abort"); Net_GetNetStat(); dldlength = (INT32)((file->currentsize/(double)file->totalsize) * 256); @@ -1359,17 +1305,17 @@ static inline void CL_DrawConnectionStatus(void) strncpy(tempname, filename, sizeof(tempname)-1); } #ifdef HAVE_CURL - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-30, 0, + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-30, MENUCAPS, va(M_GetText("%s downloading"), ((cl_mode == CL_DOWNLOADHTTPFILES) ? "\x82""HTTP" : "\x85""Direct"))); #else - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-30, 0, + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-30, MENUCAPS, va(M_GetText("%s downloading"),("\x85""Direct"))); #endif - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-22, V_YELLOWMAP, + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-58-22, V_YELLOWMAP|MENUCAPS, va(M_GetText("\"%s\""), tempname)); - V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-58, V_20TRANS|V_MONOSPACE, + V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-58, V_20TRANS|V_MONOSPACE|MENUCAPS, va(" %4uK/%4uK",fileneeded[lastfilenum].currentsize>>10,file->totalsize>>10)); - V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-58, V_20TRANS|V_MONOSPACE, + V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-58, V_20TRANS|V_MONOSPACE|MENUCAPS, va("%3.1fK/s ", ((double)getbps)/1024)); // Download progress @@ -1379,20 +1325,20 @@ static inline void CL_DrawConnectionStatus(void) else totaldldsize = downloadcompletedsize; - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-14, V_YELLOWMAP, "Overall Download Progress"); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-14, V_YELLOWMAP|MENUCAPS, "Overall Download Progress"); totalfileslength = (INT32)((totaldldsize/(double)totalfilesrequestedsize) * 256); M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 175); V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, totalfileslength, 8, 160); if (totalfilesrequestedsize>>20 >= 10) //display in MB if over 10MB - V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, + V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, va(" %4uM/%4uM",totaldldsize>>20,totalfilesrequestedsize>>20)); else - V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, + V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, va(" %4uK/%4uK",totaldldsize>>10,totalfilesrequestedsize>>10)); - V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE, + V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS, va("%2u/%2u Files ",downloadcompletednum,totalfilesrequestednum)); } else @@ -1403,12 +1349,12 @@ static inline void CL_DrawConnectionStatus(void) //Draw bottom box M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1); - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP, "Press ESC to abort"); + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP|MENUCAPS, "Press ESC to abort"); for (i = 0; i < 16; ++i) V_DrawFill((BASEVIDWIDTH/2-128) + (i * 16), BASEVIDHEIGHT-24, 16, 8, palstart + ((animtime - i) & 15)); - V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP, + V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP|MENUCAPS, M_GetText("Waiting to download files...")); } } @@ -1796,7 +1742,7 @@ static boolean SV_ResendingSavegameToAnyone(void) INT32 i; for (i = 0; i < MAXNETNODES; i++) - if (resendingsavegame[i]) + if (nodeingame[i] && resendingsavegame[i]) return true; return false; } @@ -2008,12 +1954,12 @@ static void CL_ReloadReceivedSavegame(void) // we dont have P_ForceLocalAngle so were setting it manually here for (i = 0; i <= splitscreen; i++) { - localangle[i] = (angle_t)(players[displayplayers[i]].cmd.angleturn<<16); + localangle[i] = (angle_t)(players[displayplayers[i]].cmd.angleturn << 16); } for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { - camera[i].subsector = R_PointInSubsector(camera[i].x, camera[i].y); + camera[i].subsector = R_PointInSubsectorFast(camera[i].x, camera[i].y); } cl_redownloadinggamestate = false; @@ -3240,7 +3186,7 @@ void CL_RemovePlayer(INT32 playernum, INT32 reason) demo_extradata[playernum] |= DXD_PLAYSTATE; - if (server && !demo.playback) + if (server && !demo.playback && playernode[playernum] != UINT8_MAX) { INT32 node = playernode[playernum]; //playerpernode[node] = 0; // It'd be better to remove them all at once, but ghosting happened, so continue to let CL_RemovePlayer do it one-by-one @@ -3249,13 +3195,7 @@ void CL_RemovePlayer(INT32 playernum, INT32 reason) { SV_InitResynchVars(node); // If a resynch was in progress, well, it no longer needs to be. - nodeingame[node] = false; -#ifdef SATURNPAK - is_client_saturn[node] = false; -#endif -#ifdef SATURNSYNCH - can_receive_gamestate[node] = false; -#endif + nodeingame[node] = false; // do we even need this? Net_CloseConnection(node); ResetNode(node); } @@ -3297,7 +3237,10 @@ void CL_RemovePlayer(INT32 playernum, INT32 reason) } } - LUAh_PlayerQuit(&players[playernum], reason); // Lua hook for player quitting + LUA_HookPlayerQuit(&players[playernum], reason); // Lua hook for player quitting + + if (playernum == displayplayers[0] && !demo.playback) + displayplayers[0] = consoleplayer; // don't look through someone's view who isn't there // Reset player data CL_ClearPlayer(playernum); @@ -3318,9 +3261,6 @@ void CL_RemovePlayer(INT32 playernum, INT32 reason) RemoveAdminPlayer(playernum); // don't stay admin after you're gone } - if (playernum == displayplayers[0] && !demo.playback) - displayplayers[0] = consoleplayer; // don't look through someone's view who isn't there - LUA_InvalidatePlayer(&players[playernum]); if (G_BattleGametype()) // SRB2Kart @@ -3361,9 +3301,6 @@ void CL_Reset(void) if (servernode > 0 && servernode < MAXNETNODES) { nodeingame[(UINT8)servernode] = false; -#ifdef SATURNPAK - is_client_saturn[(UINT8)servernode] = false; -#endif Net_CloseConnection(servernode); } D_CloseConnection(); // netgame = false @@ -3708,16 +3645,13 @@ static void Command_Kick(void) if (pn == -1 || pn == 0) return; - if (server) + // Special case if we are trying to kick a player who is downloading the game state: + // trigger a timeout instead of kicking them, because a kick would only + // take effect after they have finished downloading + if (server && playernode[pn] != UINT8_MAX && sendingsavegame[playernode[pn]]) { - // Special case if we are trying to kick a player who is downloading the game state: - // trigger a timeout instead of kicking them, because a kick would only - // take effect after they have finished downloading - if (sendingsavegame[playernode[pn]]) - { - Net_ConnectionTimeout(playernode[pn]); - return; - } + Net_ConnectionTimeout(playernode[pn]); + return; } WRITESINT8(p, pn); @@ -3773,7 +3707,7 @@ static void Got_KickCmd(UINT8 **p, INT32 playernum) // Is playernum authorized to make this kick? if (playernum != serverplayer && !IsPlayerAdmin(playernum) - /*&& !(playerpernode[playernode[playernum]] == 2 + /*&& !(playernode[playernum] != UINT8_MAX && playerpernode[playernode[playernum]] == 2 //&& nodetoplayer2[playernode[playernum]] == pnum)*/) { // We received a kick command from someone who isn't the @@ -4275,14 +4209,20 @@ void SV_ResetServer(void) for (i = 0; i < MAXPLAYERS; i++) { LUA_InvalidatePlayer(&players[i]); - playeringame[i] = false; - playernode[i] = UINT8_MAX; sprintf(player_names[i], "Player %d", i + 1); - adminplayers[i] = -1; // Populate the entire adminplayers array with -1. } memset(player_name_changes, 0, sizeof player_name_changes); + memset(playeringame, false, sizeof playeringame); + memset(playernode, UINT8_MAX, sizeof playernode); + + pingmeasurecount = 1; + memset(realpingtable, 0, sizeof realpingtable); + memset(playerpingtable, 0, sizeof playerpingtable); + + ClearAdminPlayers(); + mynode = 0; cl_packetmissed = false; #ifdef SATURNSYNCH @@ -4464,12 +4404,12 @@ static void Got_AddPlayer(UINT8 **p, INT32 playernum) if (server && multiplayer && motd[0] != '\0') COM_BufAddText(va("sayto %d %s\n", newplayernum, motd)); - D_AddAutoloadFiles(); + D_AddPostloadFiles(); - LUAh_PlayerJoin(newplayernum); + LUA_HookInt(newplayernum, HOOK(PlayerJoin)); if (newplayernum == consoleplayer) - LUAh_ServerJoin(); + LUA_HookVoid(HOOK(ServerJoin)); #ifdef HAVE_DISCORDRPC DRPC_UpdatePresence(); @@ -4551,7 +4491,9 @@ static boolean SV_AddWaitingPlayers(void) buf[0] = (UINT8)node; buf[1] = newplayernum; if (playerpernode[node] < 1) + { nodetoplayer[node] = newplayernum; + } else if (playerpernode[node] < 2) { nodetoplayer2[node] = newplayernum; @@ -4649,10 +4591,8 @@ void SV_StopServer(void) Y_EndVote(); gamestate = wipegamestate = GS_NULL; - localtextcmd[0] = 0; - localtextcmd2[0] = 0; - localtextcmd3[0] = 0; - localtextcmd4[0] = 0; + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + localtextcmd[i][0] = 0; for (i = firstticstosend; i < firstticstosend + TICQUEUE; i++) D_Clearticcmd(i); @@ -5391,11 +5331,10 @@ static void HandlePacketFromPlayer(SINT8 node) } // Check player consistancy during the level - if (((!can_receive_gamestate[node]) && realstart <= gametic && realstart > gametic - TICQUEUE+1 && gamestate == GS_LEVEL - && consistancy[realstart%TICQUEUE] != SHORT(netbuffer->u.clientpak.consistancy)) || (can_receive_gamestate[node] && realstart <= gametic && realstart + TICQUEUE - 1 > gametic && gamestate == GS_LEVEL + if (gamestate == GS_LEVEL + && (realstart > gametic - TICQUEUE+1 && realstart <= gametic) && consistancy[realstart%TICQUEUE] != SHORT(netbuffer->u.clientpak.consistancy) - && !resendingsavegame[node] && savegameresendcooldown[node] <= I_GetTime() - && !SV_ResendingSavegameToAnyone())) + && (!can_receive_gamestate[node] || (!resendingsavegame[node] && savegameresendcooldown[node] <= I_GetTime() && !SV_ResendingSavegameToAnyone()))) { //#ifndef SATURNPAK // lug: keep this behaviour for v7.1 atleast // we need to send this so the client can tell us if it can receive the savegame @@ -5453,8 +5392,6 @@ static void HandlePacketFromPlayer(SINT8 node) DEBFILE(va("player %d kicked (synch failure) [%u] %d!=%d\n", netconsole, realstart, consistancy[realstart%TICQUEUE], SHORT(netbuffer->u.clientpak.consistancy))); - gamestate_resend_counter[node] = 0; - DEBFILE(va("gamestate counter %d for node %d\n", gamestate_resend_counter[node], netconsole)); break; } } @@ -5607,12 +5544,6 @@ static void HandlePacketFromPlayer(SINT8 node) } Net_CloseConnection(node); nodeingame[node] = false; -#ifdef SATURNPAK - is_client_saturn[node] = false; -#endif -#ifdef SATURNSYNCH - can_receive_gamestate[node] = false; -#endif break; // -------------------------------------------- CLIENT RECEIVE ---------- case PT_RESYNCHEND: @@ -6074,26 +6005,26 @@ static void CL_SendClientCmd(void) else if (gamestate != GS_NULL) { packetsize = sizeof (clientcmd_pak); - G_MoveTiccmd(&netbuffer->u.clientpak.cmd, &localcmds, 1); + G_MoveTiccmd(&netbuffer->u.clientpak.cmd, &localcmds[0], 1); netbuffer->u.clientpak.consistancy = SHORT(consistancy[gametic%TICQUEUE]); if (splitscreen || botingame) // Send a special packet with 2 cmd for splitscreen { netbuffer->packettype = (mis ? PT_CLIENT2MIS : PT_CLIENT2CMD); packetsize = sizeof (client2cmd_pak); - G_MoveTiccmd(&netbuffer->u.client2pak.cmd2, &localcmds2, 1); + G_MoveTiccmd(&netbuffer->u.client2pak.cmd2, &localcmds[1], 1); if (splitscreen > 1) { netbuffer->packettype = (mis ? PT_CLIENT3MIS : PT_CLIENT3CMD); packetsize = sizeof (client3cmd_pak); - G_MoveTiccmd(&netbuffer->u.client3pak.cmd3, &localcmds3, 1); + G_MoveTiccmd(&netbuffer->u.client3pak.cmd3, &localcmds[2], 1); if (splitscreen > 2) { netbuffer->packettype = (mis ? PT_CLIENT4MIS : PT_CLIENT4CMD); packetsize = sizeof (client4cmd_pak); - G_MoveTiccmd(&netbuffer->u.client4pak.cmd4, &localcmds4, 1); + G_MoveTiccmd(&netbuffer->u.client4pak.cmd4, &localcmds[3], 1); } } } @@ -6103,44 +6034,33 @@ static void CL_SendClientCmd(void) if (cl_mode == CL_CONNECTED || dedicated) { + UINT8 i; // Send extra data if needed - if (localtextcmd[0]) + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { - netbuffer->packettype = PT_TEXTCMD; - M_Memcpy(netbuffer->u.textcmd,localtextcmd, localtextcmd[0]+1); - // All extra data have been sent - if (HSendPacket(servernode, true, 0, localtextcmd[0]+1)) // Send can fail... - localtextcmd[0] = 0; - } + if (localtextcmd[i][0]) + { + switch (i) + { + case 3: + netbuffer->packettype = PT_TEXTCMD4; + break; + case 2: + netbuffer->packettype = PT_TEXTCMD3; + break; + case 1: + netbuffer->packettype = PT_TEXTCMD2; + break; + default: + netbuffer->packettype = PT_TEXTCMD; + break; + } - // Send extra data if needed for player 2 (splitscreen == 1) - if (localtextcmd2[0]) - { - netbuffer->packettype = PT_TEXTCMD2; - M_Memcpy(netbuffer->u.textcmd, localtextcmd2, localtextcmd2[0]+1); - // All extra data have been sent - if (HSendPacket(servernode, true, 0, localtextcmd2[0]+1)) // Send can fail... - localtextcmd2[0] = 0; - } - - // Send extra data if needed for player 3 (splitscreen == 2) - if (localtextcmd3[0]) - { - netbuffer->packettype = PT_TEXTCMD3; - M_Memcpy(netbuffer->u.textcmd, localtextcmd3, localtextcmd3[0]+1); - // All extra data have been sent - if (HSendPacket(servernode, true, 0, localtextcmd3[0]+1)) // Send can fail... - localtextcmd3[0] = 0; - } - - // Send extra data if needed for player 4 (splitscreen == 3) - if (localtextcmd4[0]) - { - netbuffer->packettype = PT_TEXTCMD4; - M_Memcpy(netbuffer->u.textcmd, localtextcmd4, localtextcmd4[0]+1); - // All extra data have been sent - if (HSendPacket(servernode, true, 0, localtextcmd4[0]+1)) // Send can fail... - localtextcmd4[0] = 0; + M_Memcpy(netbuffer->u.textcmd, localtextcmd[i], localtextcmd[i][0]+1); + // All extra data have been sent + if (HSendPacket(servernode, true, 0, localtextcmd[i][0]+1)) // Send can fail... + localtextcmd[i][0] = 0; + } } } } @@ -6160,106 +6080,108 @@ static void SV_SendTics(void) // for each node create a packet with x tics and send it // x is computed using supposedtics[n], max packet size and maketic for (n = 1; n < MAXNETNODES; n++) - if (nodeingame[n]) + { + if (!nodeingame[n]) + continue; + + // assert supposedtics[n]>=nettics[n] + realfirsttic = supposedtics[n]; + lasttictosend = maketic; + + if (lasttictosend - nettics[n] >= BACKUPTICS) + lasttictosend = nettics[n] + BACKUPTICS-1; + + if (realfirsttic >= lasttictosend) { - // assert supposedtics[n]>=nettics[n] - realfirsttic = supposedtics[n]; - lasttictosend = maketic; - - if (lasttictosend - nettics[n] >= BACKUPTICS) - lasttictosend = nettics[n] + BACKUPTICS-1; - - if (realfirsttic >= lasttictosend) - { - // well we have sent all tics we will so use extrabandwidth - // to resent packet that are supposed lost (this is necessary since lost - // packet detection work when we have received packet with firsttic > neededtic - // (getpacket servertics case) - DEBFILE(va("Nothing to send node %u mak=%u sup=%u net=%u \n", - n, lasttictosend, supposedtics[n], nettics[n])); - realfirsttic = nettics[n]; - if (realfirsttic >= lasttictosend || (I_GetTime() + n)&3) - // all tic are ok - continue; - DEBFILE(va("Sent %d anyway\n", realfirsttic)); - } - if (realfirsttic < firstticstosend) - realfirsttic = firstticstosend; - - // compute the length of the packet and cut it if too large - packsize = BASESERVERTICSSIZE; - for (i = realfirsttic; i < lasttictosend; i++) - { - packsize += sizeof (ticcmd_t) * doomcom->numslots; - packsize += TotalTextCmdPerTic(i); - - if (packsize > software_MAXPACKETLENGTH) - { - DEBFILE(va("packet too large (%s) at tic %d (should be from %d to %d)\n", - sizeu1(packsize), i, realfirsttic, lasttictosend)); - lasttictosend = i; - - // too bad: too much player have send extradata and there is too - // much data in one tic. - // To avoid it put the data on the next tic. (see getpacket - // textcmd case) but when numplayer changes the computation can be different - if (lasttictosend == realfirsttic) - { - if (packsize > MAXPACKETLENGTH) - I_Error("Too many players: can't send %s data for %d players to node %d\n" - "Well sorry nobody is perfect....\n", - sizeu1(packsize), doomcom->numslots, n); - else - { - lasttictosend++; // send it anyway! - DEBFILE("sending it anyway\n"); - } - } - break; - } - } - - // Send the tics - netbuffer->packettype = PT_SERVERTICS; - netbuffer->u.serverpak.starttic = (UINT8)realfirsttic; - netbuffer->u.serverpak.numtics = (UINT8)(lasttictosend - realfirsttic); - netbuffer->u.serverpak.numslots = (UINT8)SHORT(doomcom->numslots); - bufpos = (UINT8 *)&netbuffer->u.serverpak.cmds; - - for (i = realfirsttic; i < lasttictosend; i++) - { - bufpos = G_DcpyTiccmd(bufpos, netcmds[i%TICQUEUE], doomcom->numslots * sizeof (ticcmd_t)); - } - - // add textcmds - for (i = realfirsttic; i < lasttictosend; i++) - { - ntextcmd = bufpos++; - *ntextcmd = 0; - for (j = 0; j < MAXPLAYERS; j++) - { - UINT8 *textcmd = D_GetExistingTextcmd(i, j); - INT32 size = textcmd ? textcmd[0] : 0; - - if ((!j || playeringame[j]) && size) - { - (*ntextcmd)++; - WRITEUINT8(bufpos, j); - M_Memcpy(bufpos, textcmd, size + 1); - bufpos += size + 1; - } - } - } - packsize = bufpos - (UINT8 *)&(netbuffer->u); - - HSendPacket(n, false, 0, packsize); - // when tic are too large, only one tic is sent so don't go backward! - if (lasttictosend-doomcom->extratics > realfirsttic) - supposedtics[n] = lasttictosend-doomcom->extratics; - else - supposedtics[n] = lasttictosend; - if (supposedtics[n] < nettics[n]) supposedtics[n] = nettics[n]; + // well we have sent all tics we will so use extrabandwidth + // to resent packet that are supposed lost (this is necessary since lost + // packet detection work when we have received packet with firsttic > neededtic + // (getpacket servertics case) + DEBFILE(va("Nothing to send node %u mak=%u sup=%u net=%u \n", + n, lasttictosend, supposedtics[n], nettics[n])); + realfirsttic = nettics[n]; + if (realfirsttic >= lasttictosend || (I_GetTime() + n)&3) + // all tic are ok + continue; + DEBFILE(va("Sent %d anyway\n", realfirsttic)); } + if (realfirsttic < firstticstosend) + realfirsttic = firstticstosend; + + // compute the length of the packet and cut it if too large + packsize = BASESERVERTICSSIZE; + for (i = realfirsttic; i < lasttictosend; i++) + { + packsize += sizeof (ticcmd_t) * doomcom->numslots; + packsize += TotalTextCmdPerTic(i); + + if (packsize > software_MAXPACKETLENGTH) + { + DEBFILE(va("packet too large (%s) at tic %d (should be from %d to %d)\n", + sizeu1(packsize), i, realfirsttic, lasttictosend)); + lasttictosend = i; + + // too bad: too much player have send extradata and there is too + // much data in one tic. + // To avoid it put the data on the next tic. (see getpacket + // textcmd case) but when numplayer changes the computation can be different + if (lasttictosend == realfirsttic) + { + if (packsize > MAXPACKETLENGTH) + I_Error("Too many players: can't send %s data for %d players to node %d\n" + "Well sorry nobody is perfect....\n", + sizeu1(packsize), doomcom->numslots, n); + else + { + lasttictosend++; // send it anyway! + DEBFILE("sending it anyway\n"); + } + } + break; + } + } + + // Send the tics + netbuffer->packettype = PT_SERVERTICS; + netbuffer->u.serverpak.starttic = (UINT8)realfirsttic; + netbuffer->u.serverpak.numtics = (UINT8)(lasttictosend - realfirsttic); + netbuffer->u.serverpak.numslots = (UINT8)SHORT(doomcom->numslots); + bufpos = (UINT8 *)&netbuffer->u.serverpak.cmds; + + for (i = realfirsttic; i < lasttictosend; i++) + { + bufpos = G_DcpyTiccmd(bufpos, netcmds[i%TICQUEUE], doomcom->numslots * sizeof (ticcmd_t)); + } + + // add textcmds + for (i = realfirsttic; i < lasttictosend; i++) + { + ntextcmd = bufpos++; + *ntextcmd = 0; + for (j = 0; j < MAXPLAYERS; j++) + { + UINT8 *textcmd = D_GetExistingTextcmd(i, j); + INT32 size = textcmd ? textcmd[0] : 0; + + if ((!j || playeringame[j]) && size) + { + (*ntextcmd)++; + WRITEUINT8(bufpos, j); + M_Memcpy(bufpos, textcmd, size + 1); + bufpos += size + 1; + } + } + } + packsize = bufpos - (UINT8 *)&(netbuffer->u); + + HSendPacket(n, false, 0, packsize); + // when tic are too large, only one tic is sent so don't go backward! + if (lasttictosend-doomcom->extratics > realfirsttic) + supposedtics[n] = lasttictosend-doomcom->extratics; + else + supposedtics[n] = lasttictosend; + if (supposedtics[n] < nettics[n]) supposedtics[n] = nettics[n]; + } // node 0 is me! supposedtics[0] = maketic; } @@ -6267,27 +6189,27 @@ static void SV_SendTics(void) // // TryRunTics // +static inline void CreateNewLocalCMD(UINT8 p, INT32 realtics) +{ + G_BuildTiccmd(&localcmds[p], realtics, p+1); + localcmds[p].angleturn |= TICCMD_RECEIVED; +} + static void Local_Maketic(INT32 realtics) { + INT32 i; + I_OsPolling(); // I_Getevent D_ProcessEvents(); // menu responder, cons responder, // game responder calls HU_Responder, AM_Responder, F_Responder, // and G_MapEventsToControls if (!dedicated) rendergametic = gametic; // translate inputs (keyboard/mouse/joystick) into game controls - G_BuildTiccmd(&localcmds, realtics, 1); - if (splitscreen || botingame) - { - G_BuildTiccmd(&localcmds2, realtics, 2); - if (splitscreen > 1) - { - G_BuildTiccmd(&localcmds3, realtics, 3); - if (splitscreen > 2) - G_BuildTiccmd(&localcmds4, realtics, 4); - } - } - localcmds.angleturn |= TICCMD_RECEIVED; + for (i = 0; i <= splitscreen; i++) + { + CreateNewLocalCMD(i, realtics); + } } void SV_SpawnPlayer(INT32 playernum, INT32 x, INT32 y, angle_t angle) @@ -6326,29 +6248,31 @@ static void SV_Maketic(void) INT32 j; for (j = 0; j < MAXNETNODES; j++) - if (playerpernode[j]) - { - INT32 player = nodetoplayer[j]; - if ((netcmds[maketic%TICQUEUE][player].angleturn & TICCMD_RECEIVED) == 0) - { // we didn't receive this tic - INT32 i; + { + if (!playerpernode[j]) + continue; - DEBFILE(va("MISS tic%4d for node %d\n", maketic, j)); + INT32 player = nodetoplayer[j]; + if ((netcmds[maketic%TICQUEUE][player].angleturn & TICCMD_RECEIVED) == 0) + { // we didn't receive this tic + INT32 i; + + DEBFILE(va("MISS tic%4d for node %d\n", maketic, j)); #if defined(PARANOIA) && 0 - CONS_Debug(DBG_NETPLAY, "Client Misstic %d\n", maketic); + CONS_Debug(DBG_NETPLAY, "Client Misstic %d\n", maketic); #endif - // copy the old tic - for (i = 0; i < playerpernode[j]; i++) - { - if (i == 0) player = nodetoplayer[j]; - else if (i == 1) player = nodetoplayer2[j]; - else if (i == 2) player = nodetoplayer3[j]; - else if (i == 3) player = nodetoplayer4[j]; - netcmds[maketic%TICQUEUE][player] = netcmds[(maketic-1)%TICQUEUE][player]; - netcmds[maketic%TICQUEUE][player].angleturn &= ~TICCMD_RECEIVED; - } + // copy the old tic + for (i = 0; i < playerpernode[j]; i++) + { + if (i == 0) player = nodetoplayer[j]; + else if (i == 1) player = nodetoplayer2[j]; + else if (i == 2) player = nodetoplayer3[j]; + else if (i == 3) player = nodetoplayer4[j]; + netcmds[maketic%TICQUEUE][player] = netcmds[(maketic-1)%TICQUEUE][player]; + netcmds[maketic%TICQUEUE][player].angleturn &= ~TICCMD_RECEIVED; } } + } // all tic are now proceed make the next maketic++; @@ -6401,19 +6325,21 @@ boolean TryRunTics(tic_t realtics) } #endif - if (neededtic > gametic) + ticking = neededtic > gametic; + + if (ticking) { - hu_stopped = false; + if (realtics) + hu_stopped = false; } if (player_joining) { - hu_stopped = true; + if (realtics) + hu_stopped = true; return false; } - ticking = neededtic > gametic; - if (ticking) { // run the count * tics @@ -6444,7 +6370,8 @@ boolean TryRunTics(tic_t realtics) } else { - hu_stopped = true; + if (realtics) + hu_stopped = true; } return ticking; @@ -6574,7 +6501,7 @@ static void UpdatePingTable(void) PingUpdate(); // update node latency values so we can take an average later. for (i = 0; i < MAXPLAYERS; i++) - if (playeringame[i]) + if (playeringame[i] && playernode[i] != UINT8_MAX) realpingtable[i] += GetLag(playernode[i]); pingmeasurecount++; } @@ -6672,6 +6599,14 @@ void NetUpdate(void) if (realtics <= 0) // nothing new to update return; + if (realtics > 5) + { + if (server) + realtics = 1; + else + realtics = 5; + } + #ifdef DEDICATEDIDLETIME if (server && dedicated && gamestate == GS_LEVEL) { @@ -6720,14 +6655,6 @@ void NetUpdate(void) } #endif - if (realtics > 5) - { - if (server) - realtics = 1; - else - realtics = 5; - } - gametime = nowtime; UpdatePingTable(); @@ -6820,6 +6747,9 @@ void NetUpdate(void) } Net_AckTicker(); HandleNodeTimeouts(); + + nowtime /= NEWTICRATERATIO; + if (nowtime > resptime) { resptime = nowtime; diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 197f3b794..4e81621d9 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -600,10 +600,8 @@ void D_ClientServerInit(void); // Initialise the other field void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(UINT8 **p, INT32 playernum)); -void SendNetXCmd(netxcmd_t id, const void *param, size_t nparam); -void SendNetXCmd2(netxcmd_t id, const void *param, size_t nparam); // splitsreen player -void SendNetXCmd3(netxcmd_t id, const void *param, size_t nparam); // splitsreen3 player -void SendNetXCmd4(netxcmd_t id, const void *param, size_t nparam); // splitsreen4 player +void SendNetXCmdForPlayer(UINT8 playerid, netxcmd_t id, const void *param, size_t nparam); +#define SendNetXCmd(id, param, nparam) SendNetXCmdForPlayer(0, id, param, nparam) // Shortcut for P1 // Create any new ticcmds and broadcast to other players. void NetKeepAlive(void); @@ -650,7 +648,7 @@ INT32 D_NumPlayers(void); void D_ResetTiccmds(void); tic_t GetLag(INT32 node); -UINT8 GetFreeXCmdSize(void); +//UINT8 GetFreeXCmdSize(UINT8 playerid); extern UINT8 hu_resynching; #ifdef SATURNSYNCH diff --git a/src/d_main.c b/src/d_main.c index 1dfe3eafa..642870a86 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -15,6 +15,7 @@ /// plus functions to parse command line parameters, configure game /// parameters, and call the startup functions. +#include "d_netcmd.h" #if defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON) #include #include @@ -99,7 +100,6 @@ UINT8 window_notinfocus = false; // DEMO LOOP // //static INT32 demosequence; -static const char *pagename = "MAP1PIC"; static char *startupwadfiles[MAX_WADFILES]; static char *startuppwads[MAX_WADFILES]; @@ -116,7 +116,6 @@ boolean devparm = false; // started game with -devparm boolean singletics = false; // timedemo boolean lastdraw = false; -postimg_t postimgtype[MAXSPLITSCREENPLAYERS]; INT32 postimgparam[MAXSPLITSCREENPLAYERS]; // These variables are only true if @@ -183,7 +182,7 @@ static inline void D_DeviceLEDTick(void) for (i = 0; i <= splitscreen; i++) { - if (G_GetDeviceForPlayer(i) == 0) + if (cv_usejoystick[i].value == 0) continue; color[i] = G_GetSkinColor(i); @@ -451,6 +450,8 @@ static boolean D_Display(void) { if (players[displayplayers[i]].mo || players[displayplayers[i]].playerstate == PST_DEAD) { + viewssnum = i; + if (i == 0) // Initialize for P1 { viewwindowy = 0; @@ -460,8 +461,6 @@ static boolean D_Display(void) objectsdrawn = 0; } - viewssnum = i; - #ifdef HWRENDER if (rendermode == render_opengl) HWR_RenderPlayerView(i, &players[displayplayers[i]]); @@ -513,15 +512,12 @@ static boolean D_Display(void) if (rendermode == render_soft) { - if (!splitscreen) - R_ApplyViewMorph(); + if (!splitscreen) + R_ApplyViewMorph(); for (i = 0; i <= splitscreen; i++) { - if (!postimgtype[i]) - continue; - - V_DoPostProcessor(i, postimgtype[i], postimgparam[i]); + V_DoPostProcessor(i, &players[displayplayers[i]], postimgparam[i]); } } @@ -542,6 +538,8 @@ static boolean D_Display(void) PS_START_TIMING(ps_uitime); ST_Drawer(); HU_Drawer(); + + NetUpdate(); // TEST: run this EVERY frame } else { @@ -745,10 +743,10 @@ void D_SRB2Loop(void) renderisnewtic = (realtics > 0 || singletics); - refreshdirmenu = 0; // not sure where to put this, here as good as any? - if (renderisnewtic) { + refreshdirmenu = 0; // not sure where to put this, here as good as any? + // don't skip more than 10 frames at a time // (fadein / fadeout cause massive frame skip!) if (realtics > 8) @@ -818,7 +816,7 @@ void D_SRB2Loop(void) { renderdeltatics = FLOAT_TO_FIXED(deltatics); - if (!(paused || P_AutoPause()) && deltatics < 1.0 && !hu_stopped) + if (!(paused || P_AutoPause()) && !hu_stopped) { rendertimefrac = g_time.timefrac; } @@ -857,7 +855,7 @@ void D_SRB2Loop(void) LUA_Step(); #ifdef HAVE_DISCORDRPC - if (! dedicated) + if (!dedicated) { Discord_RunCallbacks(); } @@ -966,6 +964,9 @@ void D_StartTitle(void) //demosequence = -1; gametype = GT_RACE; // SRB2kart paused = false; + + S_ResetKeepAndSpecialMus(); // just in case + F_StartTitleScreen(); // Reset the palette -- SRB2Kart: actually never mind let's do this in the middle of every fade @@ -1072,8 +1073,7 @@ static void D_FindAddonsToAutoload(void) const char *autoloadpath; boolean postload; - INT32 i, len; - boolean hasprefix = false; + INT32 i; char wadsToAutoload[256] = ""; // does it exist tho @@ -1095,7 +1095,8 @@ static void D_FindAddonsToAutoload(void) || (wadsToAutoload[0] == '#')) continue; // this marks it so that it loads after loading server addons - else if (fastncmp(wadsToAutoload, "postload ", 9)) { + else if (fastncmp(wadsToAutoload, "postload ", 9)) + { strremove(wadsToAutoload, "postload "); postload = true; } @@ -1107,34 +1108,10 @@ static void D_FindAddonsToAutoload(void) wadsToAutoload[i] = '\0'; } - len = strlen(wadsToAutoload); - hasprefix = false; - - for (i = 0; i < len; ++i) + if (!postload && W_CheckPostLoadList(wadsToAutoload)) { - if (wadsToAutoload[i] == '_') - { - hasprefix = true; - break; - } - } - - // Lets just hope no one adds bonuschars in autoload - if (hasprefix) - { - // We searching for c in prefix, which stands for "character" and doesn't work well with - // autoload atm, only fine for postload - for (i = 0; i < len; ++i) - { - if (wadsToAutoload[i] == '_') break; // Prefix end - - if (wadsToAutoload[i] == 'c' || wadsToAutoload[i] == 'C') - { - CONS_Alert(CONS_WARNING, "forcing postload for %s as local skin\n", wadsToAutoload); - postload = true; - break; // Found it - } - } + CONS_Printf("forcing postload for file %s\n", wadsToAutoload); + postload = true; } // LOAD IT @@ -1152,30 +1129,30 @@ static void D_FindAddonsToAutoload(void) fclose(autoloadconfigfile); } -void D_AddAutoloadFiles(void) +static void D_AddAutoloadFiles(void) { - if (wasautoloaded && postautoloaded) + if (wasautoloaded) return; - if (!wasautoloaded && !modeattacking) - { - CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); - if (W_AddAutoloadedLocalFiles(autoloadwadfiles) == 0) - CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); - D_CleanFile(autoloadwadfiles); + CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); + if (W_AddAutoloadedLocalFiles(autoloadwadfiles) == 0) + CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); + D_CleanFile(autoloadwadfiles); - wasautoloaded = true; - } + wasautoloaded = true; +} - if ((!postautoloaded) && netgame) - { - CONS_Printf("D_AutoloadFile(): Loading postloaded addons...\n"); - if (W_AddAutoloadedLocalFiles(autoloadwadfilespost) == 0) - CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); - D_CleanFile(autoloadwadfilespost); +void D_AddPostloadFiles(void) +{ + if (postautoloaded || !netgame) + return; - postautoloaded = true; - } + CONS_Printf("D_AddPostloadFiles(): Loading postloaded addons...\n"); + if (W_AddAutoloadedLocalFiles(autoloadwadfilespost) == 0) + CONS_Printf("D_AddPostloadFiles(): Are you sure you put in valid files or what?\n"); + D_CleanFile(autoloadwadfilespost); + + postautoloaded = true; } void D_CleanFile(char **filearray) @@ -1865,11 +1842,12 @@ void D_SRB2Main(void) } S_InitMusicDefs(); - S_InitMTDefs(); CONS_Printf("ST_Init(): Init status bar.\n"); ST_Init(); + D_AddAutoloadFiles(); + // Set up splitscreen players before joining! if (!dedicated && (M_CheckParm("-splitscreen") && M_IsNextParm())) { @@ -2071,7 +2049,6 @@ void D_SRB2Main(void) if (dedicated && server) { - pagename = "TITLESKY"; levelstarttic = gametic; G_SetGamestate(GS_LEVEL); if (!P_SetupLevel(false, false)) diff --git a/src/d_main.h b/src/d_main.h index 851eaa8b5..ddd6c3ab4 100644 --- a/src/d_main.h +++ b/src/d_main.h @@ -45,12 +45,12 @@ extern boolean statdp; // stat display for extended player setup extern boolean nametaggfx; // Nametag stuffs extern boolean driftgaugegfx; -void D_AddAutoloadFiles(void); - +// autoload stuff extern boolean autoloading; extern boolean autoloaded; extern boolean postautoloaded; -extern boolean wasautoloaded; + +void D_AddPostloadFiles(void); extern char *autoloadwadfilespost[MAX_WADFILES]; extern char *autoloadwadfiles[MAX_WADFILES]; diff --git a/src/d_net.c b/src/d_net.c index a8602f567..2725fca14 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -69,8 +69,6 @@ INT16 hardware_MAXPACKETLENGTH; boolean (*I_NetGet)(void) = NULL; void (*I_NetSend)(void) = NULL; -boolean (*I_NetCanSend)(void) = NULL; -boolean (*I_NetCanGet)(void) = NULL; void (*I_NetCloseSocket)(void) = NULL; void (*I_NetFreeNodenum)(INT32 nodenum) = NULL; SINT8 (*I_NetMakeNodewPort)(const char *address, const char* port) = NULL; @@ -1087,15 +1085,7 @@ boolean HSendPacket(INT32 node, boolean reliable, UINT8 acknum, size_t packetlen netbuffer->ackreturn = 0; if (reliable) { - if (I_NetCanSend && !I_NetCanSend()) - { - if (netbuffer->packettype < PT_CANFAIL) - GetFreeAcknum(&netbuffer->ack, true); - - DEBFILE("HSendPacket: Out of bandwidth\n"); - return false; - } - else if (!GetFreeAcknum(&netbuffer->ack, false)) + if (!GetFreeAcknum(&netbuffer->ack, false)) return false; } else @@ -1292,7 +1282,6 @@ boolean D_CheckNetGame(void) I_NetGet = Internal_Get; I_NetSend = Internal_Send; - I_NetCanSend = NULL; I_NetCloseSocket = NULL; I_NetFreeNodenum = Internal_FreeNodenum; I_NetMakeNodewPort = NULL; @@ -1491,7 +1480,6 @@ void D_CloseConnection(void) I_NetGet = Internal_Get; I_NetSend = Internal_Send; - I_NetCanSend = NULL; I_NetCloseSocket = NULL; I_NetFreeNodenum = Internal_FreeNodenum; I_NetMakeNodewPort = NULL; diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 2d3007693..076bb10e0 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -16,6 +16,7 @@ #include "console.h" #include "command.h" +#include "dehacked.h" #include "i_time.h" #include "i_system.h" #include "g_game.h" @@ -141,6 +142,8 @@ static void Command_Addfile(void); static void Command_Addskins(void); static void Command_GLocalSkin(void); static void Command_ListWADS_f(void); +static void Command_ListDoomednums_f(void); +static void Command_ListUnusedSprites_f(void); static void Command_RunSOC(void); static void Command_Pause(void); static void Command_Respawn(void); @@ -303,14 +306,12 @@ consvar_t cv_mouseturn = {"mouseturn", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, consvar_t cv_laglesscam = {"laglesscamera", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; #if defined(HAVE_SDL) || defined(_WINDOWS) //joystick 1 and 2 -consvar_t cv_usejoystick = {"use_joystick", "1", CV_SAVE|CV_CALL, usejoystick_cons_t, - I_InitJoystick, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_usejoystick2 = {"use_joystick2", "2", CV_SAVE|CV_CALL, usejoystick_cons_t, - I_InitJoystick2, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_usejoystick3 = {"use_joystick3", "3", CV_SAVE|CV_CALL, usejoystick_cons_t, - I_InitJoystick3, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_usejoystick4 = {"use_joystick4", "4", CV_SAVE|CV_CALL, usejoystick_cons_t, - I_InitJoystick4, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_usejoystick[MAXSPLITSCREENPLAYERS] = { + {"use_joystick", "1", CV_SAVE|CV_CALL, usejoystick_cons_t, I_InitJoystick1, 0, NULL, NULL, 0, 0, NULL}, + {"use_joystick2", "2", CV_SAVE|CV_CALL, usejoystick_cons_t, I_InitJoystick2, 0, NULL, NULL, 0, 0, NULL}, + {"use_joystick3", "3", CV_SAVE|CV_CALL, usejoystick_cons_t, I_InitJoystick3, 0, NULL, NULL, 0, 0, NULL}, + {"use_joystick4", "4", CV_SAVE|CV_CALL, usejoystick_cons_t, I_InitJoystick4, 0, NULL, NULL, 0, 0, NULL} +}; #endif #if (defined (LJOYSTICK) || defined (HAVE_SDL)) @@ -318,13 +319,17 @@ consvar_t cv_usejoystick4 = {"use_joystick4", "4", CV_SAVE|CV_CALL, usejoystick_ consvar_t cv_joyport = {"joyport", "/dev/js0", CV_SAVE, joyport_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_joyport2 = {"joyport2", "/dev/js0", CV_SAVE, joyport_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; //Alam: for later #endif -consvar_t cv_joyscale = {"joyscale", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_joyscale2 = {"joyscale2", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale2, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_joyscale3 = {"joyscale3", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale3, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_joyscale4 = {"joyscale4", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale4, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_joyscale[MAXSPLITSCREENPLAYERS] = { + {"joyscale", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale, 0, NULL, NULL, 0, 0, NULL}, + {"joyscale2", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale2, 0, NULL, NULL, 0, 0, NULL}, + {"joyscale3", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale3, 0, NULL, NULL, 0, 0, NULL}, + {"joyscale4", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale4, 0, NULL, NULL, 0, 0, NULL} +}; #else -consvar_t cv_joyscale = {"joyscale", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; //Alam: Dummy for save -consvar_t cv_joyscale2 = {"joyscale2", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}; //Alam: Dummy for save +consvar_t cv_joyscale[2] = { //Alam: Dummy for save + {"joyscale", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyscale", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL} +}; #endif #if defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON) consvar_t cv_mouse2port = {"mouse2port", "/dev/gpmdata", CV_SAVE, mouse2port_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -539,9 +544,9 @@ consvar_t cv_nametagscore = {"kartnametagscore", "Off", CV_SAVE, CV_OnOff, NULL, consvar_t cv_shownametagfinish = {"kartshownametagfinished", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_shownametagspectator = {"kartshownametagspectator", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL}; + static CV_PossibleValue_t driftgaugeoffset_cons_t[] = { {-FRACUNIT*128, "MIN"}, {FRACUNIT*128, "MAX"}, {0, NULL}}; - static CV_PossibleValue_t driftgaugestyle_cons_t[] = { {1, "Default"}, {2, "Small"}, {3, "Big Numbers"}, {4, "Numbers Only"}, {0, NULL}}; @@ -703,6 +708,8 @@ void D_RegisterServerCommands(void) COM_AddCommand("addskins", Command_Addskins); COM_AddCommand("localskin", Command_GLocalSkin); COM_AddCommand("listwad", Command_ListWADS_f); + COM_AddCommand("listmapthings", Command_ListDoomednums_f); + COM_AddCommand("listunusedsprites", Command_ListUnusedSprites_f); COM_AddCommand("runsoc", Command_RunSOC); COM_AddCommand("pause", Command_Pause); @@ -900,6 +907,7 @@ void D_RegisterClientCommands(void) COM_AddCommand("screenshot", M_ScreenShot); COM_AddCommand("startmovie", Command_StartMovie_f); COM_AddCommand("stopmovie", Command_StopMovie_f); + COM_AddCommand("minigen", M_MinimapGenerate); CV_RegisterVar(&cv_screenshot_option); CV_RegisterVar(&cv_screenshot_folder); @@ -1019,58 +1027,22 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_pauseifunfocused); // g_input.c - CV_RegisterVar(&cv_turnaxis); - CV_RegisterVar(&cv_turnaxis2); - CV_RegisterVar(&cv_turnaxis3); - CV_RegisterVar(&cv_turnaxis4); - CV_RegisterVar(&cv_moveaxis); - CV_RegisterVar(&cv_moveaxis2); - CV_RegisterVar(&cv_moveaxis3); - CV_RegisterVar(&cv_moveaxis4); - CV_RegisterVar(&cv_brakeaxis); - CV_RegisterVar(&cv_brakeaxis2); - CV_RegisterVar(&cv_brakeaxis3); - CV_RegisterVar(&cv_brakeaxis4); - CV_RegisterVar(&cv_aimaxis); - CV_RegisterVar(&cv_aimaxis2); - CV_RegisterVar(&cv_aimaxis3); - CV_RegisterVar(&cv_aimaxis4); - CV_RegisterVar(&cv_lookaxis); - CV_RegisterVar(&cv_lookaxis2); - CV_RegisterVar(&cv_lookaxis3); - CV_RegisterVar(&cv_lookaxis4); - CV_RegisterVar(&cv_fireaxis); - CV_RegisterVar(&cv_fireaxis2); - CV_RegisterVar(&cv_fireaxis3); - CV_RegisterVar(&cv_fireaxis4); - CV_RegisterVar(&cv_driftaxis); - CV_RegisterVar(&cv_driftaxis2); - CV_RegisterVar(&cv_driftaxis3); - CV_RegisterVar(&cv_driftaxis4); - CV_RegisterVar(&cv_lookbackaxis); - CV_RegisterVar(&cv_lookbackaxis2); - CV_RegisterVar(&cv_lookbackaxis3); - CV_RegisterVar(&cv_lookbackaxis4); - CV_RegisterVar(&cv_custom1axis); - CV_RegisterVar(&cv_custom1axis2); - CV_RegisterVar(&cv_custom1axis3); - CV_RegisterVar(&cv_custom1axis4); - CV_RegisterVar(&cv_custom2axis); - CV_RegisterVar(&cv_custom2axis2); - CV_RegisterVar(&cv_custom2axis3); - CV_RegisterVar(&cv_custom2axis4); - CV_RegisterVar(&cv_custom3axis); - CV_RegisterVar(&cv_custom3axis2); - CV_RegisterVar(&cv_custom3axis3); - CV_RegisterVar(&cv_custom3axis4); - CV_RegisterVar(&cv_xdeadzone); - CV_RegisterVar(&cv_ydeadzone); - CV_RegisterVar(&cv_xdeadzone2); - CV_RegisterVar(&cv_ydeadzone2); - CV_RegisterVar(&cv_xdeadzone3); - CV_RegisterVar(&cv_ydeadzone3); - CV_RegisterVar(&cv_xdeadzone4); - CV_RegisterVar(&cv_ydeadzone4); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + CV_RegisterVar(&cv_turnaxis[i]); + CV_RegisterVar(&cv_moveaxis[i]); + CV_RegisterVar(&cv_brakeaxis[i]); + CV_RegisterVar(&cv_aimaxis[i]); + CV_RegisterVar(&cv_lookaxis[i]); + CV_RegisterVar(&cv_fireaxis[i]); + CV_RegisterVar(&cv_driftaxis[i]); + CV_RegisterVar(&cv_lookbackaxis[i]); + CV_RegisterVar(&cv_custom1axis[i]); + CV_RegisterVar(&cv_custom2axis[i]); + CV_RegisterVar(&cv_custom3axis[i]); + CV_RegisterVar(&cv_xdeadzone[i]); + CV_RegisterVar(&cv_ydeadzone[i]); + } // filesrch.c CV_RegisterVar(&cv_addons_option); @@ -1107,28 +1079,19 @@ void D_RegisterClientCommands(void) //CV_RegisterVar(&cv_mousemove); //CV_RegisterVar(&cv_mousemove2); - CV_RegisterVar(&cv_usejoystick); - CV_RegisterVar(&cv_usejoystick2); - CV_RegisterVar(&cv_usejoystick3); - CV_RegisterVar(&cv_usejoystick4); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + CV_RegisterVar(&cv_usejoystick[i]); + } #ifdef LJOYSTICK CV_RegisterVar(&cv_joyport); CV_RegisterVar(&cv_joyport2); #endif - CV_RegisterVar(&cv_joyscale); - CV_RegisterVar(&cv_joyscale2); - CV_RegisterVar(&cv_joyscale3); - CV_RegisterVar(&cv_joyscale4); - // Analog Control - /*CV_RegisterVar(&cv_analog); - CV_RegisterVar(&cv_analog2); - CV_RegisterVar(&cv_analog3); - CV_RegisterVar(&cv_analog4); - CV_RegisterVar(&cv_useranalog); - CV_RegisterVar(&cv_useranalog2); - CV_RegisterVar(&cv_useranalog3); - CV_RegisterVar(&cv_useranalog4);*/ + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + CV_RegisterVar(&cv_joyscale[i]); + } // s_sound.c CV_RegisterVar(&cv_soundvolume); @@ -1157,7 +1120,7 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_scr_height); CV_RegisterVar(&cv_soundtest); - + CV_RegisterVar(&cv_nametag); CV_RegisterVar(&cv_nametagtrans); CV_RegisterVar(&cv_nametagfacerank); @@ -1172,7 +1135,7 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_nametagscore); CV_RegisterVar(&cv_shownametagfinish); CV_RegisterVar(&cv_shownametagspectator); - + CV_RegisterVar(&cv_driftgauge); CV_RegisterVar(&cv_driftgaugeofs); CV_RegisterVar(&cv_driftgaugetrans); @@ -1675,25 +1638,9 @@ static void SendNameAndColor(void) } else if ((foundskin = R_SkinAvailable(cv_skin.string)) != -1) { - //boolean notsame; - cv_skin.value = foundskin; - - //notsame = (cv_skin.value != players[consoleplayer].skin); - SetPlayerSkin(consoleplayer, cv_skin.string); CV_StealthSet(&cv_skin, skins[cv_skin.value].name); - - // SRB2Kart - /*if (notsame) - { - CV_StealthSetValue(&cv_playercolor, skins[cv_skin.value].prefcolor); - - players[consoleplayer].skincolor = (cv_playercolor.value&0x3F) % MAXSKINCOLORS; - - if (players[consoleplayer].mo) - players[consoleplayer].mo->color = (UINT8)players[consoleplayer].skincolor; - }*/ } else { @@ -1737,7 +1684,7 @@ static void SendNameAndColor(void) WRITESTRINGN(p, cv_playername.zstring, MAXPLAYERNAME); WRITEUINT8(p, (UINT8)cv_playercolor.value); WRITEUINT8(p, (UINT8)cv_skin.value); - SendNetXCmd(XD_NAMEANDCOLOR, buf, p - buf); + SendNetXCmdForPlayer(0, XD_NAMEANDCOLOR, buf, p - buf); } // splitscreen @@ -1807,24 +1754,8 @@ static void SendNameAndColor2(void) if ((foundskin = R_SkinAvailable(cv_skin2.string)) != -1) { - //boolean notsame; - cv_skin2.value = foundskin; - - //notsame = (cv_skin2.value != players[secondplaya].skin); - SetPlayerSkin(secondplaya, cv_skin2.string); - - // SRB2Kart - /*if (notsame) - { - CV_StealthSetValue(&cv_playercolor2, skins[players[secondplaya].skin].prefcolor); - - players[secondplaya].skincolor = (cv_playercolor2.value&0x3F) % MAXSKINCOLORS; - - if (players[secondplaya].mo) - players[secondplaya].mo->color = players[secondplaya].skincolor; - }*/ } else { @@ -1867,7 +1798,7 @@ static void SendNameAndColor2(void) WRITESTRINGN(p, cv_playername2.zstring, MAXPLAYERNAME); WRITEUINT8(p, (UINT8)cv_playercolor2.value); WRITEUINT8(p, (UINT8)cv_skin2.value); - SendNetXCmd2(XD_NAMEANDCOLOR, buf, p - buf); + SendNetXCmdForPlayer(1, XD_NAMEANDCOLOR, buf, p - buf); } static void SendNameAndColor3(void) @@ -1988,7 +1919,7 @@ static void SendNameAndColor3(void) WRITESTRINGN(p, cv_playername3.zstring, MAXPLAYERNAME); WRITEUINT8(p, (UINT8)cv_playercolor3.value); WRITEUINT8(p, (UINT8)cv_skin3.value); - SendNetXCmd3(XD_NAMEANDCOLOR, buf, p - buf); + SendNetXCmdForPlayer(2, XD_NAMEANDCOLOR, buf, p - buf); } static void SendNameAndColor4(void) @@ -2057,24 +1988,8 @@ static void SendNameAndColor4(void) if ((foundskin = R_SkinAvailable(cv_skin4.string)) != -1) { - //boolean notsame; - cv_skin4.value = foundskin; - - //notsame = (cv_skin4.value != players[fourthplaya].skin); - SetPlayerSkin(fourthplaya, cv_skin4.string); - - // SRB2Kart - /*if (notsame) - { - CV_StealthSetValue(&cv_playercolor4, skins[players[fourthplaya].skin].prefcolor); - - players[fourthplaya].skincolor = (cv_playercolor4.value&0x3F) % MAXSKINCOLORS; - - if (players[fourthplaya].mo) - players[fourthplaya].mo->color = players[fourthplaya].skincolor; - }*/ } else { @@ -2117,7 +2032,7 @@ static void SendNameAndColor4(void) WRITESTRINGN(p, cv_playername4.zstring, MAXPLAYERNAME); WRITEUINT8(p, (UINT8)cv_playercolor4.value); WRITEUINT8(p, (UINT8)cv_skin4.value); - SendNetXCmd4(XD_NAMEANDCOLOR, buf, p - buf); + SendNetXCmdForPlayer(3, XD_NAMEANDCOLOR, buf, p - buf); } static void Got_NameAndColor(UINT8 **cp, INT32 playernum) @@ -2222,11 +2137,9 @@ void SendWeaponPref(void) UINT8 buf[1]; buf[0] = 0; - if (cv_flipcam.value) + if (cv_flipcam[0].value) buf[0] |= 1; - if (cv_analog.value) - buf[0] |= 2; - SendNetXCmd(XD_WEAPONPREF, buf, 1); + SendNetXCmdForPlayer(0, XD_WEAPONPREF, buf, 1); } void SendWeaponPref2(void) @@ -2234,11 +2147,9 @@ void SendWeaponPref2(void) UINT8 buf[1]; buf[0] = 0; - if (cv_flipcam2.value) + if (cv_flipcam[1].value) buf[0] |= 1; - if (cv_analog2.value) - buf[0] |= 2; - SendNetXCmd2(XD_WEAPONPREF, buf, 1); + SendNetXCmdForPlayer(1, XD_WEAPONPREF, buf, 1); } void SendWeaponPref3(void) @@ -2246,11 +2157,9 @@ void SendWeaponPref3(void) UINT8 buf[1]; buf[0] = 0; - if (cv_flipcam3.value) + if (cv_flipcam[2].value) buf[0] |= 1; - if (cv_analog3.value) - buf[0] |= 2; - SendNetXCmd3(XD_WEAPONPREF, buf, 1); + SendNetXCmdForPlayer(2, XD_WEAPONPREF, buf, 1); } void SendWeaponPref4(void) @@ -2258,11 +2167,9 @@ void SendWeaponPref4(void) UINT8 buf[1]; buf[0] = 0; - if (cv_flipcam4.value) + if (cv_flipcam[3].value) buf[0] |= 1; - if (cv_analog4.value) - buf[0] |= 2; - SendNetXCmd4(XD_WEAPONPREF, buf, 1); + SendNetXCmdForPlayer(3, XD_WEAPONPREF, buf, 1); } static void Got_WeaponPref(UINT8 **cp,INT32 playernum) @@ -2521,6 +2428,12 @@ static void Command_Playdemo_f(void) return; } + if (!demo.playback && gamestate == GS_LEVEL) // special case: allow starting another demo while watching a demo + { + CONS_Printf(M_GetText("You can't time a demo while in a game.\n")); + return; + } + // disconnect from server here? if (demo.playback) G_StopDemo(); @@ -2560,6 +2473,12 @@ static void Command_Timedemo_f(void) return; } + if (!demo.playback && gamestate == GS_LEVEL) // special case: allow starting another demo while watching a demo + { + CONS_Printf(M_GetText("You can't time a demo while in a game.\n")); + return; + } + // disconnect from server here? if (demo.playback) G_StopDemo(); @@ -2983,6 +2902,14 @@ static void Command_Map_f(void) // G_TOLFlag handles both multiplayer gametype and ignores it for !multiplayer else { + if (!mapheaderinfo[newmapnum-1] || mapheaderinfo[newmapnum-1] == NULL) + { + CONS_Alert(CONS_WARNING, M_GetText("Invalid mapheaderinfo for Course %s (%s)\n"), realmapname, G_BuildMapName(newmapnum)); + Z_Free(realmapname); + Z_Free(mapname); + return; + } + if (!(mapheaderinfo[newmapnum-1]->typeoflevel & G_TOLFlag(newgametype))) { CONS_Alert(CONS_WARNING, M_GetText("Course %s (%s) doesn't support %s mode!\n(Use -force to override)\n"), realmapname, G_BuildMapName(newmapnum), @@ -3015,9 +2942,14 @@ static void Command_Map_f(void) } } - // spend atleast 35 seconds in one map - if (cv_demochangemap.value && demo.recording && demo.savemode != DSM_NOTSAVING && (timeinmap > 1463) && ((cv_demochangemap.value == 2 && newmapnum == gamemap) || newmapnum != gamemap)) - G_SaveDemo(); + if (cv_demochangemap.value && demo.recording) + { + // spend atleast 40 seconds in one map + if (demo.savemode != DSM_NOTSAVING && (timeinmap > (TICRATE * 40)) && ((cv_demochangemap.value == 2 && newmapnum == gamemap) || newmapnum != gamemap)) + G_SaveDemo(); + else + G_ResetDemoRecording(); + } fromlevelselect = false; D_MapChange(newmapnum, newgametype, newencoremode, newresetplayers, 0, false, false); @@ -3106,7 +3038,7 @@ static void Got_Mapcmd(UINT8 **cp, INT32 playernum) SetPlayerSkinByNum(0, cv_chooseskin.value-1); //mapnumber = M_MapNumber(mapname[3], mapname[4]); - //LUAh_MapChange(mapnumber); + //LUA_HookInt(mapnumber, HOOK(MapChange)); demo.savemode = (cv_recordmultiplayerdemos.value == 2) ? DSM_WILLAUTOSAVE : DSM_NOTSAVING; demo.savebutton = 0; @@ -3466,7 +3398,7 @@ static void Command_Teamchange_f(void) } usvalue = SHORT(NetPacket.value.l|NetPacket.value.b); - SendNetXCmd(XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); + SendNetXCmdForPlayer(0, XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); } static void Command_Teamchange2_f(void) @@ -3557,7 +3489,7 @@ static void Command_Teamchange2_f(void) } usvalue = SHORT(NetPacket.value.l|NetPacket.value.b); - SendNetXCmd2(XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); + SendNetXCmdForPlayer(1, XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); } static void Command_Teamchange3_f(void) @@ -3648,7 +3580,7 @@ static void Command_Teamchange3_f(void) } usvalue = SHORT(NetPacket.value.l|NetPacket.value.b); - SendNetXCmd3(XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); + SendNetXCmdForPlayer(2, XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); } static void Command_Teamchange4_f(void) @@ -3739,7 +3671,7 @@ static void Command_Teamchange4_f(void) } usvalue = SHORT(NetPacket.value.l|NetPacket.value.b); - SendNetXCmd4(XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); + SendNetXCmdForPlayer(3, XD_TEAMCHANGE, &usvalue, sizeof(usvalue)); } static void Command_ServerTeamChange_f(void) @@ -4005,19 +3937,7 @@ static void Got_Teamchange(UINT8 **cp, INT32 playernum) if (!players[playernum].spectator) { if (players[playernum].mo) - { - //if (!players[playernum].spectator) - P_DamageMobj(players[playernum].mo, NULL, NULL, 10000); - /*else - { - if (players[playernum].mo) - { - P_RemoveMobj(players[playernum].mo); - players[playernum].mo = NULL; - } - players[playernum].playerstate = PST_REBORN; - }*/ - } + P_DamageMobj(players[playernum].mo, NULL, NULL, 10000); else players[playernum].playerstate = PST_REBORN; } @@ -4151,10 +4071,7 @@ static void Got_Teamchange(UINT8 **cp, INT32 playernum) players[playernum].mo->health = 1; } - // In tag, check to see if you still have a game. - /*if (G_TagGametype()) - P_CheckSurvivors(); - else*/ if (G_BattleGametype()) + if (G_BattleGametype()) K_CheckBumpers(); // SRB2Kart else if (G_RaceGametype()) P_CheckRacers(); // also SRB2Kart @@ -4878,10 +4795,6 @@ static void Got_RequestAddfilecmd(UINT8 **cp, INT32 playernum) boolean kick = false; boolean toomany = false; INT32 i,j; - serverinfo_pak *dummycheck = NULL; - - // Shut the compiler up. - (void)dummycheck; READSTRINGN(*cp, filename, 240); READMEM(*cp, md5sum, 16); @@ -5009,6 +4922,151 @@ static void Command_ListWADS_f(void) } } +#define MAXDOOMEDNUM 4095 + +static void Command_ListDoomednums_f(void) +{ + INT16 i, j, k = 0, l = 0; + INT32 argc = COM_Argc(); + INT16 table[MAXDOOMEDNUM]; + + switch (argc) + { + case 1: + l = MAXDOOMEDNUM; + break; + case 3: + l = atoi(COM_Argv(2)); + if (l < 1 || l > MAXDOOMEDNUM) + { + CONS_Printf("arg 2: doomednum \x82""%d \x85out of range (1-4095)\n", k); + return; + } + //FALLTHRU + case 2: + k = atoi(COM_Argv(1)); + if (k < 1 || k > MAXDOOMEDNUM) + { + CONS_Printf("arg 1: doomednum \x82""%d \x85out of range (1-4095)\n", k); + return; + } + if (!l) + l = k; + else if (l < k) // silently and helpfully swap. + { + j = k; + k = l; + l = j; + } + break; + default: + CONS_Printf("listmapthings: \x86too many arguments!\n"); + return; + } + + // see P_SpawnNonMobjMapThing + memset(table, 0, sizeof(table)); + for (i = 1; i <= MAXPLAYERS; i++) + table[i-1] = MT_PLAYER; // playerstarts + table[33-1] = table[34-1] = table[35-1] = MT_PLAYER; // battle/team starts + table[750-1] = table[777-1] = table[778-1] = MT_UNKNOWN; // slopes + for (i = 600; i <= 609; i++) + table[i-1] = MT_RING; // placement patterns + table[1705-1] = table[1713-1] = MT_HOOP; // types of hoop + + CONS_Printf("\x82""Checking for double defines...\n"); + for (i = 1; i < MT_FIRSTFREESLOT+NUMMOBJFREESLOTS; i++) + { + j = mobjinfo[i].doomednum; + if (j < (k ? k : 1) || j > (l ? l : MAXDOOMEDNUM)) + continue; + if (table[j-1]) + { + CONS_Printf(" doomednum \x82""%d""\x80 is \x85""double-defined\x80 by ", j); + if (i < MT_FIRSTFREESLOT) + { + CONS_Printf("\x87""hardcode %s <-- MAJOR ERROR\n", MOBJTYPE_LIST[i]); + continue; + } + CONS_Printf("\x81""freeslot MT_""%s\n", FREE_MOBJS[i-MT_FIRSTFREESLOT]); + continue; + } + table[j-1] = i; + } + CONS_Printf("\x82Printing doomednum usage...\n"); + if (!k) + { + i = 35; // skip MT_PLAYER spam + CONS_Printf(" doomednums \x82""1-35""\x80 are used by ""\x87""hardcode MT_PLAYER\n"); + } + else + i = k-1; + + for (; i < l; i++) + { + if (!table[i]) + { + if (k) + { + CONS_Printf(" doomednum \x82""%d""\x80 is \x83""free!", i+1); + if (i < 99) // above the humble crawla? how dare you + CONS_Printf(" (Don't freeslot this low...)"); + CONS_Printf("\n"); + } + continue; + } + CONS_Printf(" doomednum \x82""%d""\x80 is used by ", i+1); + if (table[i] < MT_FIRSTFREESLOT) + { + CONS_Printf("\x87""hardcode %s\n", MOBJTYPE_LIST[table[i]]); + continue; + } + CONS_Printf("\x81""freeslot MT_""%s\n", FREE_MOBJS[table[i]-MT_FIRSTFREESLOT]); + } +} + +#undef MAXDOOMEDNUM + +void Command_ListUnusedSprites_f(void) +{ + size_t i, j; + + CONS_Printf("\x82Printing sprite non-usage...\n"); + + for (i = 0; i < NUMSPRITES; i++) + { + if (sprites[i].numframes) + { + // We're only showing unused sprites... + continue; + } + + if (i < SPR_FIRSTFREESLOT) + { + CONS_Printf(" \x87""hardcode SPR_""%.4s\n", sprnames[i]); + continue; + } + + if (used_spr[(i-SPR_FIRSTFREESLOT)/8] == 0xFF) + { + for (j = 0; j < 8; j++) + { + CONS_Printf(" \x81""freeslot SPR_""%.4s\n", sprnames[i+j]); + } + + i += j; + } + + if (used_spr[(i-SPR_FIRSTFREESLOT)/8] & (1<<(i%8))) + { + CONS_Printf(" \x81""freeslot SPR_""%.4s\n", sprnames[i]); + continue; + } + + break; + } +} + // ========================================================================= // MISC. COMMANDS // ========================================================================= @@ -5298,9 +5356,6 @@ void D_GameTypeChanged(INT32 lastgametype) else if (!multiplayer && !netgame) { gametype = GT_RACE; // SRB2kart - // These shouldn't matter anymore - //CV_Set(&cv_itemrespawntime, cv_itemrespawntime.defaultvalue); - //CV_SetValue(&cv_itemrespawn, 0); } // reset timelimit and pointlimit in race/coop, prevent stupid cheats @@ -5322,19 +5377,6 @@ void D_GameTypeChanged(INT32 lastgametype) } } - // When swapping to a gametype that supports spectators, - // make everyone a spectator initially. - /*if (G_GametypeHasSpectators()) - { - INT32 i; - for (i = 0; i < MAXPLAYERS; i++) - if (playeringame[i]) - { - players[i].ctfteam = 0; - players[i].spectator = true; - } - }*/ - // don't retain teams in other modes or between changes from ctf to team match. // also, stop any and all forms of team scrambling that might otherwise take place. if (G_GametypeHasTeams()) @@ -5785,10 +5827,6 @@ void Command_Retry_f(void) CONS_Printf(M_GetText("You must be in a level to use this.\n")); else if (netgame || multiplayer) CONS_Printf(M_GetText("This only works in single player.\n")); - /*else if (!&players[consoleplayer] || players[consoleplayer].lives <= 1) - CONS_Printf(M_GetText("You can't retry without any lives remaining!\n")); - else if (G_IsSpecialStage(gamemap)) - CONS_Printf(M_GetText("You can't retry special stages!\n"));*/ else { M_ClearMenus(true); diff --git a/src/d_netcmd.h b/src/d_netcmd.h index 01fb98243..87d96b40d 100644 --- a/src/d_netcmd.h +++ b/src/d_netcmd.h @@ -43,18 +43,12 @@ extern consvar_t cv_seenames, cv_allowseenames; extern consvar_t cv_usemouse; //WTF extern consvar_t cv_mouseturn; -extern consvar_t cv_usejoystick; -extern consvar_t cv_usejoystick2; -extern consvar_t cv_usejoystick3; -extern consvar_t cv_usejoystick4; +extern consvar_t cv_usejoystick[4]; //MAXSPLITSCREENPLAYERS #ifdef LJOYSTICK extern consvar_t cv_joyport; extern consvar_t cv_joyport2; #endif -extern consvar_t cv_joyscale; -extern consvar_t cv_joyscale2; -extern consvar_t cv_joyscale3; -extern consvar_t cv_joyscale4; +extern consvar_t cv_joyscale[4]; //MAXSPLITSCREENPLAYERS // splitscreen with second mouse extern consvar_t cv_mouse2port; diff --git a/src/d_player.h b/src/d_player.h index c2a5d32ce..140a4a748 100644 --- a/src/d_player.h +++ b/src/d_player.h @@ -403,7 +403,6 @@ typedef struct player_s angle_t old_frameangle, old_frameangle2; // SRB2Kart CEP: Sliptide rolling - INT32 sliptidemem; angle_t sliproll; INT16 lturn_max[MAXPREDICTTICS]; // What's the expected turn value for full-left for a number of frames back (to account for netgame latency)? @@ -413,6 +412,8 @@ typedef struct player_s // See pflags_t, above. pflags_t pflags; + UINT16 postimgflags; + // playing animation. panim_t panim; diff --git a/src/d_think.h b/src/d_think.h index b907c17fd..6b8ee113a 100644 --- a/src/d_think.h +++ b/src/d_think.h @@ -49,6 +49,7 @@ typedef struct thinker_s // killough 11/98: count of how many other objects reference // this one using pointers. Used for garbage collection. INT32 references; + boolean cachable; } thinker_t; #endif diff --git a/src/dehacked.c b/src/dehacked.c index e1f3adba2..e4b4028ef 100644 --- a/src/dehacked.c +++ b/src/dehacked.c @@ -14,7 +14,6 @@ #include "d_main.h" // for srb2home #include "g_game.h" #include "sounds.h" -#include "info.h" #include "d_think.h" #include "m_argv.h" #include "z_zone.h" @@ -33,12 +32,12 @@ #include "r_sky.h" #include "r_draw.h" // translation colormap consts (for lua) #include "fastcmp.h" -#include "lua_script.h" -#include "lua_glib.h" -#include "lua_hook.h" + #include "d_clisrv.h" #include "v_video.h" // video flags (for lua) +#include "lua_glib.h" +#include "lua_hook.h" #include "lua_script.h" #include "lua_libs.h" @@ -48,13 +47,14 @@ // Free slot names // The crazy word-reading stuff uses these. -static char *FREE_STATES[NUMSTATEFREESLOTS]; -static char *FREE_MOBJS[NUMMOBJFREESLOTS]; -static UINT8 used_spr[(NUMSPRITEFREESLOTS / 8) + 1]; // Bitwise flag for sprite freeslot in use! I would use ceil() here if I could, but it only saves 1 byte of memory anyway. +char *FREE_STATES[NUMSTATEFREESLOTS]; +char *FREE_MOBJS[NUMMOBJFREESLOTS]; +UINT8 used_spr[(NUMSPRITEFREESLOTS / 8) + 1]; // Bitwise flag for sprite freeslot in use! I would use ceil() here if I could, but it only saves 1 byte of memory anyway. + #define initfreeslots() {\ -memset(FREE_STATES,0,sizeof(char *) * NUMSTATEFREESLOTS);\ -memset(FREE_MOBJS,0,sizeof(char *) * NUMMOBJFREESLOTS);\ -memset(used_spr,0,sizeof(UINT8) * ((NUMSPRITEFREESLOTS / 8) + 1));\ + memset(FREE_STATES,0,sizeof(char *) * NUMSTATEFREESLOTS);\ + memset(FREE_MOBJS,0,sizeof(char *) * NUMMOBJFREESLOTS);\ + memset(used_spr,0,sizeof(UINT8) * ((NUMSPRITEFREESLOTS / 8) + 1));\ } // Crazy word-reading stuff @@ -1493,9 +1493,6 @@ actionpointer_t actionpointers[] = {{A_SpawnObjectRelative}, "A_SPAWNOBJECTRELATIVE"}, {{A_ChangeAngleRelative}, "A_CHANGEANGLERELATIVE"}, {{A_ChangeAngleAbsolute}, "A_CHANGEANGLEABSOLUTE"}, - {{A_RollAngle}, "A_ROLLANGLE"}, - {{A_ChangeRollAngleRelative},"A_CHANGEROLLANGLERELATIVE"}, - {{A_ChangeRollAngleAbsolute},"A_CHANGEROLLANGLEABSOLUTE"}, {{A_PlaySound}, "A_PLAYSOUND"}, {{A_FindTarget}, "A_FINDTARGET"}, {{A_FindTracer}, "A_FINDTRACER"}, @@ -3150,7 +3147,7 @@ void DEH_LoadDehackedLump(lumpnum_t lumpnum) // RegEx to generate this from info.h: ^\tS_([^,]+), --> \t"S_\1", // I am leaving the prefixes solely for clarity to programmers, // because sadly no one remembers this place while searching for full state names. -static const char *const STATE_LIST[] = { // array length left dynamic for sanity testing later. +const char *const STATE_LIST[] = { // array length left dynamic for sanity testing later. "S_NULL", "S_UNKNOWN", "S_INVISIBLE", // state for invisible sprite @@ -6364,7 +6361,7 @@ static const char *const STATE_LIST[] = { // array length left dynamic for sanit // RegEx to generate this from info.h: ^\tMT_([^,]+), --> \t"MT_\1", // I am leaving the prefixes solely for clarity to programmers, // because sadly no one remembers this place while searching for full state names. -static const char *const MOBJTYPE_LIST[] = { // array length left dynamic for sanity testing later. +const char *const MOBJTYPE_LIST[] = { // array length left dynamic for sanity testing later. "MT_NULL", "MT_UNKNOWN", @@ -7155,7 +7152,7 @@ static const char *const MOBJTYPE_LIST[] = { // array length left dynamic for s #endif }; -static const char *const MOBJFLAG_LIST[] = { +const char *const MOBJFLAG_LIST[] = { "SPECIAL", "SOLID", "SHOOTABLE", @@ -7191,7 +7188,7 @@ static const char *const MOBJFLAG_LIST[] = { }; // \tMF2_(\S+).*// (.+) --> \t"\1", // \2 -static const char *const MOBJFLAG2_LIST[] = { +const char *const MOBJFLAG2_LIST[] = { "AXIS", // It's a NiGHTS axis! (For faster checking) "TWOD", // Moves like it's in a 2D level "DONTRESPAWN", // Don't respawn this object! @@ -7224,7 +7221,7 @@ static const char *const MOBJFLAG2_LIST[] = { NULL }; -static const char *const MOBJEFLAG_LIST[] = { +const char *const MOBJEFLAG_LIST[] = { "ONGROUND", // The mobj stands on solid floor (not on another mobj or in air) "JUSTHITFLOOR", // The mobj just hit the floor while falling, this is cleared on next frame "TOUCHWATER", // The mobj stands in a sector with water, and touches the surface @@ -7242,14 +7239,14 @@ static const char *const MOBJEFLAG_LIST[] = { NULL }; -static const char *const MAPTHINGFLAG_LIST[4] = { +const char *const MAPTHINGFLAG_LIST[4] = { NULL, "OBJECTFLIP", // Reverse gravity flag for objects. "OBJECTSPECIAL", // Special flag used with certain objects. "AMBUSH" // Deaf monsters/do not react to sound. }; -static const char *const PLAYERFLAG_LIST[] = { +const char *const PLAYERFLAG_LIST[] = { // Flip camera angle with gravity flip prefrence. "FLIPCAM", @@ -7321,7 +7318,7 @@ static const char *const PLAYERFLAG_LIST[] = { }; // Linedef flags -static const char *const ML_LIST[16] = { +const char *const ML_LIST[16] = { "IMPASSIBLE", "BLOCKMONSTERS", "TWOSIDED", @@ -7342,7 +7339,7 @@ static const char *const ML_LIST[16] = { // This DOES differ from r_draw's Color_Names, unfortunately. // Also includes Super colors -static const char *COLOR_ENUMS[] = { // Rejigged for Kart. +const char *COLOR_ENUMS[] = { // Rejigged for Kart. "NONE", // SKINCOLOR_NONE "WHITE", // SKINCOLOR_WHITE "SILVER", // SKINCOLOR_SILVER @@ -7510,7 +7507,7 @@ static const char *COLOR_ENUMS[] = { // Rejigged for Kart. "CSUPER5" // SKINCOLOR_CSUPER5, }; -static const char *const POWERS_LIST[] = { +const char *const POWERS_LIST[] = { "INVULNERABILITY", "SNEAKERS", "FLASHING", @@ -7545,7 +7542,7 @@ static const char *const POWERS_LIST[] = { "INGOOP" // In goop }; -static const char *const KARTSTUFF_LIST[] = { +const char *const KARTSTUFF_LIST[] = { "POSITION", "OLDPOSITION", "POSITIONDELAY", @@ -7632,7 +7629,7 @@ static const char *const KARTSTUFF_LIST[] = { "GROWCANCEL" }; -static const char *const HUDITEMS_LIST[] = { +const char *const HUDITEMS_LIST[] = { "LIVESNAME", "LIVESPIC", "LIVESNUM", @@ -9149,7 +9146,6 @@ int LUA_EnumLib(lua_State *L) PUSHGETTER(globalweather, u8); PUSHGETTER(levelskynum, i32); PUSHGETTER(globallevelskynum, i32); - PUSHGETTER((*mapmusname), str); PUSHGETTER(mapmusflags, u16); PUSHGETTER(mapmusposition, u32); PUSHGETTER(gravity, fxp); @@ -9166,6 +9162,11 @@ int LUA_EnumLib(lua_State *L) PUSHGETTER(racecountdown, u32); PUSHGETTER(exitcountdown, u32); + lua_pushcfunction(L, lua_glib_new_getter); + lua_pushliteral(L, "mapmusname"); + lua_glib_push_str_getter(L, mapmusname); + lua_call(L, 2, 0); + lua_pushcfunction(L, lua_glib_new_getter); lua_pushliteral(L, "mariomode"); lua_pushcfunction(L, lua_enumlib_mariomode_get); diff --git a/src/dehacked.h b/src/dehacked.h index 0d3778b28..eb22c5f6a 100644 --- a/src/dehacked.h +++ b/src/dehacked.h @@ -14,6 +14,26 @@ #define __DEHACKED_H__ #include "m_fixed.h" // for get_number +#include "info.h" + +// Free slot names +// The crazy word-reading stuff uses these. +extern char *FREE_STATES[NUMSTATEFREESLOTS]; +extern char *FREE_MOBJS[NUMMOBJFREESLOTS]; +extern UINT8 used_spr[(NUMSPRITEFREESLOTS / 8) + 1]; // Bitwise flag for sprite freeslot in use! I would use ceil() here if I could, but it only saves 1 byte of memory anyway. + +extern const char *const STATE_LIST[]; +extern const char *const MOBJTYPE_LIST[]; +extern const char *const MOBJFLAG_LIST[]; +extern const char *const MOBJFLAG2_LIST[]; // \tMF2_(\S+).*// (.+) --> \t"\1", // \2 +extern const char *const MOBJEFLAG_LIST[]; +extern const char *const MAPTHINGFLAG_LIST[4]; +extern const char *const PLAYERFLAG_LIST[]; +extern const char *const ML_LIST[]; // Linedef flags +extern const char *COLOR_ENUMS[]; +extern const char *const POWERS_LIST[]; +extern const char *const KARTSTUFF_LIST[]; +extern const char *const HUDITEMS_LIST[]; void DEH_LoadDehackedLump(lumpnum_t lumpnum); void DEH_LoadDehackedLumpPwad(UINT16 wad, UINT16 lump); diff --git a/src/doomdef.h b/src/doomdef.h index 046cd6897..c8d2a28f7 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -127,8 +127,8 @@ extern char logfilename[1024]; #else #define VERSION 1 // Game version #define SUBVERSION 6 // more precise version number -#define VERSIONSTRING "Saturn v7.1" -#define VERSIONSTRINGW L"Saturn v7.1" +#define VERSIONSTRING "Saturn v7.2" +#define VERSIONSTRINGW L"Saturn v7.2" // Hey! If you change this, add 1 to the MODVERSION below! Otherwise we can't force updates! // And change CMakeLists.txt (not src/, but in root), for CMake users! // AND appveyor.yml, for the build bots! @@ -522,6 +522,22 @@ extern boolean capslock; // i_system.c, replace getchar() once the keyboard has been appropriated INT32 I_GetKey(void); +/* http://www.cse.yorku.ca/~oz/hash.html */ +static inline +UINT32 quickncasehash (const char *p, size_t n) +{ + size_t i = 0; + UINT32 x = 5381; + + while (i < n && p[i]) + { + x = (x * 33) ^ tolower(p[i]); + i++; + } + + return x; +} + #ifndef min // Double-Check with WATTCP-32's cdefs.h #define min(x, y) (((x) < (y)) ? (x) : (y)) #endif diff --git a/src/doomstat.h b/src/doomstat.h index 01d98fd4e..f70f97059 100644 --- a/src/doomstat.h +++ b/src/doomstat.h @@ -112,7 +112,6 @@ extern UINT8 window_notinfocus; // are we in focus? (backend independant -- hand extern boolean nodrawers; extern boolean noblit; extern boolean lastdraw; -extern postimg_t postimgtype[MAXSPLITSCREENPLAYERS]; extern INT32 postimgparam[MAXSPLITSCREENPLAYERS]; extern INT32 viewwindowx, viewwindowy; diff --git a/src/doomtype.h b/src/doomtype.h index 1dcf47ea7..429eba77e 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -344,14 +344,12 @@ typedef union FColorRGBA RGBA_t; typedef enum { - postimg_none, - postimg_water, - postimg_motion, - postimg_flip, - postimg_heat, - postimg_mirror, - postimg_mirrorflip -} postimg_t; + POSTIMG_WATER = 1, // Underwater screen effect. + POSTIMG_MOTION = 1<<1, // Unused motion blur effect. + POSTIMG_FLIP = 1<<2, // Flipcam screen effect. + POSTIMG_HEAT = 1<<3, // Heatwave screen effect. + POSTIMG_MIRROR = 1<<4, // encore screen effect. +} postimgflag_t; typedef UINT32 lumpnum_t; // 16 : 16 unsigned long (wad num: lump num) #define LUMPERROR UINT32_MAX @@ -367,6 +365,30 @@ typedef UINT32 tic_t; #define UINT2RGBA(a) (UINT32)((a&0xff)<<24)|((a&0xff00)<<8)|((a&0xff0000)>>8)|(((UINT32)a&0xff000000)>>24) #endif +#define TOSTR(x) #x + +typedef UINT8 bitarray_t; + +#define BIT_ARRAY_SIZE(n) (((n) + 7) >> 3) + +static inline int +in_bit_array (const bitarray_t * const array, const int value) +{ + return (array[value >> 3] & (1<<(value & 7))); +} + +static inline void +set_bit_array (bitarray_t * const array, const int value) +{ + array[value >> 3] |= (1<<(value & 7)); +} + +static inline void +unset_bit_array (bitarray_t * const array, const int value) +{ + array[value >> 3] &= ~(1<<(value & 7)); +} + typedef UINT64 precise_t; #endif //__DOOMTYPE__ diff --git a/src/filesrch.c b/src/filesrch.c index 3a3a576ce..84766f395 100644 --- a/src/filesrch.c +++ b/src/filesrch.c @@ -327,7 +327,8 @@ char menupath[1024]; size_t menupathindex[menudepth]; size_t menudepthleft = menudepth; -char menusearch[MAXSTRINGLENGTH+1]; +char menusearchbuf[MAXSTRINGLENGTH+1]; +textinput_t menusearch; char **dirmenu, **coredirmenu; // core only local for this file size_t sizedirmenu, sizecoredirmenu; // ditto @@ -497,7 +498,7 @@ static boolean filemenucmp(char *haystack, char *needle) strupr(localhaystack); if (cv_addons_search_type.value) return (strstr(localhaystack, needle) != 0); - return (!strncmp(localhaystack, needle, menusearch[0])); + return (!strncmp(localhaystack, needle, menusearch.length)); } void closefilemenu(boolean validsize) @@ -563,7 +564,7 @@ void searchfilemenu(char *tempname) first = (((UINT8)(coredirmenu[0][DIR_TYPE]) == EXT_UP) ? 1 : 0); // skip UP... - if (!menusearch[0]) + if (!menusearch.length) { if (dirmenu) Z_Free(dirmenu); @@ -590,7 +591,7 @@ void searchfilemenu(char *tempname) return; } - strcpy(localmenusearch, menusearch+1); + strcpy(localmenusearch, menusearch.buffer); if (!cv_addons_search_case.value) strupr(localmenusearch); @@ -652,7 +653,7 @@ boolean preparefilemenu(boolean samedepth, boolean replayhut) tempname = Z_StrDup(dirmenu[dir_on[menudepthleft]]+DIR_STRING); // don't need to I_Error if can't make - not important, just QoL } else - menusearch[0] = menusearch[1] = 0; // clear search + M_TextInputInit(&menusearch, menusearchbuf, MAXSTRINGLENGTH+1); if (!(dirhandle = opendir(menupath))) // get directory { diff --git a/src/filesrch.h b/src/filesrch.h index dd0fb404a..76d5700c0 100644 --- a/src/filesrch.h +++ b/src/filesrch.h @@ -7,6 +7,7 @@ #include "doomdef.h" #include "d_netfil.h" #include "m_menu.h" // MAXSTRINGLENGTH +#include "m_textinput.h" extern consvar_t cv_addons_option, cv_addons_folder, cv_addons_md5, cv_addons_showall, cv_addons_search_case, cv_addons_search_type; @@ -34,7 +35,8 @@ extern char menupath[1024]; extern size_t menupathindex[menudepth]; extern size_t menudepthleft; -extern char menusearch[MAXSTRINGLENGTH+1]; +extern char menusearchbuf[MAXSTRINGLENGTH+1]; +extern textinput_t menusearch; extern char **dirmenu; extern size_t sizedirmenu; diff --git a/src/g_game.c b/src/g_game.c index 5b0514572..9bee4a399 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -66,10 +66,7 @@ boolean botingame; UINT8 botskin; UINT8 botcolor; -JoyType_t Joystick; -JoyType_t Joystick2; -JoyType_t Joystick3; -JoyType_t Joystick4; +JoyType_t Joystick[MAXSPLITSCREENPLAYERS]; // 1024 bytes is plenty for a savegame #define SAVEGAMESIZE (1024) @@ -85,6 +82,8 @@ static void G_DoContinued(void); static void G_DoWorldDone(void); static void G_DoStartVote(void); +static void G_ResetDemoPlayback(char *pdemoname); + char mapmusname[7]; // Music name UINT16 mapmusflags; // Track and reset bit UINT32 mapmusposition; // Position to jump to @@ -354,33 +353,12 @@ static CV_PossibleValue_t demochangemap_cons_t[] = {{0, "Disabled"}, {1, "Diff M consvar_t cv_demochangemap = {"netdemo_savemapchange", "Disabled", CV_SAVE, demochangemap_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; // Analog Control -static void Analog_OnChange(void); -static void Analog2_OnChange(void); -static void Analog3_OnChange(void); -static void Analog4_OnChange(void); void SendWeaponPref(void); void SendWeaponPref2(void); void SendWeaponPref3(void); void SendWeaponPref4(void); -//static CV_PossibleValue_t crosshair_cons_t[] = {{0, "Off"}, {1, "Cross"}, {2, "Angle"}, {3, "Point"}, {0, NULL}}; -static CV_PossibleValue_t joyaxis_cons_t[] = {{0, "None"}, -{1, "Left X"}, {2, "Left Y"}, {-1, "Left X-"}, {-2, "Left Y-"}, -#if JOYAXISSET > 1 -{3, "Right X"}, {4, "Right Y"}, {-3, "Right X-"}, {-4, "Right Y-"}, -#endif -#if JOYAXISSET > 2 -{5, "L Trigger"}, {6, "R Trigger"}, {-5, "L Trigger-"}, {-6, "R Trigger-"}, -#endif -#if JOYAXISSET > 3 -{7, "U-Axis"}, {8, "V-Axis"}, {-7, "U-Axis-"}, {-8, "V-Axis-"}, -#endif - {0, NULL}}; -#if JOYAXISSET > 4 -"More Axis Sets" -#endif - -static CV_PossibleValue_t deadzone_cons_t[] = {{FRACUNIT/16, "MIN"}, {FRACUNIT, "MAX"}, {0, NULL}}; +static void G_FixCamera(UINT8 view); // don't mind me putting these here, I was lazy to figure out where else I could put those without blowing up the compiler. @@ -435,70 +413,116 @@ consvar_t cv_chasefreelook = {"chasemlook", "Off", CV_SAVE, CV_OnOff, NULL, 0, N consvar_t cv_chasefreelook2 = {"chasemlook2", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_mousemove = {"mousemove", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_mousemove2 = {"mousemove2", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};*/ -consvar_t cv_analog = {"analog", "Off", CV_CALL, CV_OnOff, Analog_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_analog2 = {"analog2", "Off", CV_CALL, CV_OnOff, Analog2_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_analog3 = {"analog3", "Off", CV_CALL, CV_OnOff, Analog3_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_analog4 = {"analog4", "Off", CV_CALL, CV_OnOff, Analog4_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_useranalog = {"useranalog", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_useranalog2 = {"useranalog2", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_useranalog3 = {"useranalog3", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_useranalog4 = {"useranalog4", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_turnaxis = {"joyaxis_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_moveaxis = {"joyaxis_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_brakeaxis = {"joyaxis_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_aimaxis = {"joyaxis_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookaxis = {"joyaxis_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_fireaxis = {"joyaxis_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_driftaxis = {"joyaxis_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookbackaxis = {"joyaxis_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom1axis = {"joyaxis_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom2axis = {"joyaxis_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom3axis = {"joyaxis_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_xdeadzone = {"joy_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ydeadzone = {"joy_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +//static CV_PossibleValue_t crosshair_cons_t[] = {{0, "Off"}, {1, "Cross"}, {2, "Angle"}, {3, "Point"}, {0, NULL}}; +static CV_PossibleValue_t joyaxis_cons_t[] = {{0, "None"}, +{1, "Left X"}, {2, "Left Y"}, {-1, "Left X-"}, {-2, "Left Y-"}, +#if JOYAXISSET > 1 +{3, "Right X"}, {4, "Right Y"}, {-3, "Right X-"}, {-4, "Right Y-"}, +#endif +#if JOYAXISSET > 2 +{5, "L Trigger"}, {6, "R Trigger"}, {-5, "L Trigger-"}, {-6, "R Trigger-"}, +#endif +#if JOYAXISSET > 3 +{7, "U-Axis"}, {8, "V-Axis"}, {-7, "U-Axis-"}, {-8, "V-Axis-"}, +#endif + {0, NULL}}; +#if JOYAXISSET > 4 +"More Axis Sets" +#endif -consvar_t cv_turnaxis2 = {"joyaxis2_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_moveaxis2 = {"joyaxis2_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_brakeaxis2 = {"joyaxis2_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_aimaxis2 = {"joyaxis2_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookaxis2 = {"joyaxis2_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_fireaxis2 = {"joyaxis2_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_driftaxis2 = {"joyaxis2_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookbackaxis2 = {"joyaxis2_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom1axis2 = {"joyaxis2_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom2axis2 = {"joyaxis2_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom3axis2 = {"joyaxis2_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_xdeadzone2 = {"joy2_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ydeadzone2 = {"joy2_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t deadzone_cons_t[] = {{FRACUNIT/16, "MIN"}, {FRACUNIT, "MAX"}, {0, NULL}}; -consvar_t cv_turnaxis3 = {"joyaxis3_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_moveaxis3 = {"joyaxis3_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_brakeaxis3 = {"joyaxis3_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_aimaxis3 = {"joyaxis3_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookaxis3 = {"joyaxis3_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_fireaxis3 = {"joyaxis3_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_driftaxis3 = {"joyaxis3_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookbackaxis3 = {"joyaxis3_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom1axis3 = {"joyaxis3_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom2axis3 = {"joyaxis3_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom3axis3 = {"joyaxis3_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_xdeadzone3 = {"joy3_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ydeadzone3 = {"joy3_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_turnaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; -consvar_t cv_turnaxis4 = {"joyaxis4_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_moveaxis4 = {"joyaxis4_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_brakeaxis4 = {"joyaxis4_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_aimaxis4 = {"joyaxis4_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookaxis4 = {"joyaxis4_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_fireaxis4 = {"joyaxis4_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_driftaxis4 = {"joyaxis4_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_lookbackaxis4 = {"joyaxis4_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom1axis4 = {"joyaxis4_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom2axis4 = {"joyaxis4_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_custom3axis4 = {"joyaxis4_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_xdeadzone4 = {"joy4_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ydeadzone4 = {"joy4_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_moveaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_brakeaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_brake", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_aimaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_aim", "Left Y", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_lookaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_look", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_fireaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_fire", "L Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_driftaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_drift", "R Trigger", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_lookbackaxis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_lookback", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_custom1axis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_custom1", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_custom2axis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_custom2", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_custom3axis[MAXSPLITSCREENPLAYERS] = { + {"joyaxis_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis2_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis3_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis4_custom3", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_xdeadzone[MAXSPLITSCREENPLAYERS] = { + {"joy_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joy2_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joy3_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joy4_xdeadzone", "0.3", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_ydeadzone[MAXSPLITSCREENPLAYERS] = { + {"joy_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joy2_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joy3_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joy4_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; static CV_PossibleValue_t driftsparkpulse_t[] = {{0, "MIN"}, {FRACUNIT*3, "MAX"}, {0, NULL}}; consvar_t cv_driftsparkpulse = {"driftsparkpulse", "1.4", CV_FLOAT | CV_SAVE, driftsparkpulse_t, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -519,7 +543,6 @@ static CV_PossibleValue_t sloperolldist_cons_t[] = { {8192, "8192"}, {0, "Infinite"}, {0, NULL}}; consvar_t cv_sloperolldist = {"sloperolldist", "Infinite", CV_SAVE, sloperolldist_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t sloperoll_cons_t[] = {{0, "Off"}, {1, "Players"}, {2, "Everything"}, {0, NULL}}; -consvar_t cv_spriteroll = {"spriteroll", "Off", CV_SAVE|CV_CALL, CV_OnOff, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_sloperoll = {"sloperoll", "Off", CV_SAVE|CV_CALL, sloperoll_cons_t, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_sparkroll = {"sparkroll", "Off", CV_SAVE|CV_CALL, CV_OnOff, PDistort_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_sliptideroll = {"sliptideroll", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -705,7 +728,7 @@ INT16 G_SoftwareClipAimingPitch(INT32 *aiming) return (INT16)((*aiming)>>16); } -static INT32 Joy1Axis(axis_input_e axissel) +INT32 JoyAxis(axis_input_e axissel, UINT8 player) { INT32 retaxis; INT32 axisval; @@ -715,37 +738,37 @@ static INT32 Joy1Axis(axis_input_e axissel) switch (axissel) { case AXISTURN: - axisval = cv_turnaxis.value; + axisval = cv_turnaxis[player-1].value; break; case AXISMOVE: - axisval = cv_moveaxis.value; + axisval = cv_moveaxis[player-1].value; break; case AXISBRAKE: - axisval = cv_brakeaxis.value; + axisval = cv_brakeaxis[player-1].value; break; case AXISAIM: - axisval = cv_aimaxis.value; + axisval = cv_aimaxis[player-1].value; break; case AXISLOOK: - axisval = cv_lookaxis.value; + axisval = cv_lookaxis[player-1].value; break; case AXISFIRE: - axisval = cv_fireaxis.value; + axisval = cv_fireaxis[player-1].value; break; case AXISDRIFT: - axisval = cv_driftaxis.value; + axisval = cv_driftaxis[player-1].value; break; case AXISLOOKBACK: - axisval = cv_lookbackaxis.value; + axisval = cv_lookbackaxis[player-1].value; break; case AXISCUSTOM1: - axisval = cv_custom1axis.value; + axisval = cv_custom1axis[player-1].value; break; case AXISCUSTOM2: - axisval = cv_custom2axis.value; + axisval = cv_custom2axis[player-1].value; break; case AXISCUSTOM3: - axisval = cv_custom3axis.value; + axisval = cv_custom3axis[player-1].value; break; default: return 0; @@ -768,9 +791,9 @@ static INT32 Joy1Axis(axis_input_e axissel) retaxis = -JOYAXISRANGE; if (retaxis > (+JOYAXISRANGE)) retaxis = +JOYAXISRANGE; - if (!Joystick.bGamepadStyle && axissel < AXISDEAD) + if (!Joystick[player-1].bGamepadStyle && axissel < AXISDEAD) { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_xdeadzone.value) >> FRACBITS; + const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_xdeadzone[player-1].value) >> FRACBITS; if (abs(retaxis) <= jdeadzone) return 0; } @@ -787,9 +810,9 @@ static INT32 Joy1Axis(axis_input_e axissel) retaxis = -JOYAXISRANGE; if (retaxis > (+JOYAXISRANGE)) retaxis = +JOYAXISRANGE; - if (!Joystick.bGamepadStyle && axissel < AXISDEAD) + if (!Joystick[player-1].bGamepadStyle && axissel < AXISDEAD) { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_ydeadzone.value) >> FRACBITS; + const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_ydeadzone[player-1].value) >> FRACBITS; if (abs(retaxis) <= jdeadzone) return 0; } @@ -798,291 +821,6 @@ static INT32 Joy1Axis(axis_input_e axissel) } } -static INT32 Joy2Axis(axis_input_e axissel) -{ - INT32 retaxis; - INT32 axisval; - boolean flp = false; - - //find what axis to get - switch (axissel) - { - case AXISTURN: - axisval = cv_turnaxis2.value; - break; - case AXISMOVE: - axisval = cv_moveaxis2.value; - break; - case AXISBRAKE: - axisval = cv_brakeaxis2.value; - break; - case AXISAIM: - axisval = cv_aimaxis2.value; - break; - case AXISLOOK: - axisval = cv_lookaxis2.value; - break; - case AXISFIRE: - axisval = cv_fireaxis2.value; - break; - case AXISDRIFT: - axisval = cv_driftaxis2.value; - break; - case AXISLOOKBACK: - axisval = cv_lookbackaxis2.value; - break; - case AXISCUSTOM1: - axisval = cv_custom1axis2.value; - break; - case AXISCUSTOM2: - axisval = cv_custom2axis2.value; - break; - case AXISCUSTOM3: - axisval = cv_custom3axis2.value; - break; - default: - return 0; - } - - if (axisval < 0) //odd -axises - { - axisval = -axisval; - flp = true; - } - if (axisval > JOYAXISSET*2 || axisval == 0) //not there in array or None - return 0; - - if (axisval%2) - { - axisval /= 2; - retaxis = joy2xmove[axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick2.bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_xdeadzone2.value) >> FRACBITS; - if (-jdeadzone < retaxis && retaxis < jdeadzone) - return 0; - } - if (flp) retaxis = -retaxis; //flip it around - return retaxis; - - } - else - { - axisval--; - axisval /= 2; - retaxis = joy2ymove[axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick2.bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_ydeadzone2.value) >> FRACBITS; - if (-jdeadzone < retaxis && retaxis < jdeadzone) - return 0; - } - if (flp) retaxis = -retaxis; //flip it around - return retaxis; - - } -} - -static INT32 Joy3Axis(axis_input_e axissel) -{ - INT32 retaxis; - INT32 axisval; - boolean flp = false; - - //find what axis to get - switch (axissel) - { - case AXISTURN: - axisval = cv_turnaxis3.value; - break; - case AXISMOVE: - axisval = cv_moveaxis3.value; - break; - case AXISBRAKE: - axisval = cv_brakeaxis3.value; - break; - case AXISAIM: - axisval = cv_aimaxis3.value; - break; - case AXISLOOK: - axisval = cv_lookaxis3.value; - break; - case AXISFIRE: - axisval = cv_fireaxis3.value; - break; - case AXISDRIFT: - axisval = cv_driftaxis3.value; - break; - case AXISLOOKBACK: - axisval = cv_lookbackaxis3.value; - break; - case AXISCUSTOM1: - axisval = cv_custom1axis3.value; - break; - case AXISCUSTOM2: - axisval = cv_custom2axis3.value; - break; - case AXISCUSTOM3: - axisval = cv_custom3axis3.value; - break; - default: - return 0; - } - - if (axisval < 0) //odd -axises - { - axisval = -axisval; - flp = true; - } - if (axisval > JOYAXISSET*2 || axisval == 0) //not there in array or None - return 0; - - if (axisval%2) - { - axisval /= 2; - retaxis = joy3xmove[axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick3.bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_xdeadzone3.value) >> FRACBITS; - if (-jdeadzone < retaxis && retaxis < jdeadzone) - return 0; - } - if (flp) retaxis = -retaxis; //flip it around - return retaxis; - - } - else - { - axisval--; - axisval /= 2; - retaxis = joy3ymove[axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick3.bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_ydeadzone3.value) >> FRACBITS; - if (-jdeadzone < retaxis && retaxis < jdeadzone) - return 0; - } - if (flp) retaxis = -retaxis; //flip it around - return retaxis; - - } -} - -static INT32 Joy4Axis(axis_input_e axissel) -{ - INT32 retaxis; - INT32 axisval; - boolean flp = false; - - //find what axis to get - switch (axissel) - { - case AXISTURN: - axisval = cv_turnaxis4.value; - break; - case AXISMOVE: - axisval = cv_moveaxis4.value; - break; - case AXISBRAKE: - axisval = cv_brakeaxis4.value; - break; - case AXISAIM: - axisval = cv_aimaxis4.value; - break; - case AXISLOOK: - axisval = cv_lookaxis4.value; - break; - case AXISFIRE: - axisval = cv_fireaxis4.value; - break; - case AXISDRIFT: - axisval = cv_driftaxis4.value; - break; - case AXISLOOKBACK: - axisval = cv_lookbackaxis4.value; - break; - case AXISCUSTOM1: - axisval = cv_custom1axis4.value; - break; - case AXISCUSTOM2: - axisval = cv_custom2axis4.value; - break; - case AXISCUSTOM3: - axisval = cv_custom3axis4.value; - break; - default: - return 0; - } - - if (axisval < 0) //odd -axises - { - axisval = -axisval; - flp = true; - } - if (axisval > JOYAXISSET*2 || axisval == 0) //not there in array or None - return 0; - - if (axisval%2) - { - axisval /= 2; - retaxis = joy4xmove[axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick4.bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_xdeadzone4.value) >> FRACBITS; - if (-jdeadzone < retaxis && retaxis < jdeadzone) - return 0; - } - if (flp) retaxis = -retaxis; //flip it around - return retaxis; - - } - else - { - axisval--; - axisval /= 2; - retaxis = joy4ymove[axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick4.bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_ydeadzone4.value) >> FRACBITS; - if (-jdeadzone < retaxis && retaxis < jdeadzone) - return 0; - } - if (flp) retaxis = -retaxis; //flip it around - return retaxis; - - } -} - boolean InputDown(INT32 gc, UINT8 p) { switch (p) @@ -1098,21 +836,6 @@ boolean InputDown(INT32 gc, UINT8 p) } } -INT32 JoyAxis(axis_input_e axissel, UINT8 p) -{ - switch (p) - { - case 2: - return Joy2Axis(axissel); - case 3: - return Joy3Axis(axissel); - case 4: - return Joy4Axis(axissel); - default: - return Joy1Axis(axissel); - } -} - // // G_BuildTiccmd // Builds a ticcmd from all of the available inputs @@ -1131,11 +854,12 @@ static fixed_t angleturn[3] = {KART_FULLTURN/2, KART_FULLTURN, KART_FULLTURN/4}; void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) { + const UINT8 forplayer = ssplayer-1; INT32 laim, th, tspeed, forward, side, axis; //i const INT32 speed = 1; // these ones used for multiple conditions - boolean turnleft, turnright, mouseaiming, analogjoystickmove, gamepadjoystickmove; - boolean invertmouse, lookaxis, usejoystick, kbl, rd; + boolean turnleft, turnright, mouseaiming; + boolean invertmouse, usejoystick, kbl, rd; player_t *player; camera_t *thiscam; angle_t lang; @@ -1144,22 +868,26 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) static boolean keyboard_look[MAXSPLITSCREENPLAYERS]; // true if lookup/down using keyboard static boolean resetdown[MAXSPLITSCREENPLAYERS]; // don't cam reset every frame + const boolean lookaxis = cv_lookaxis[forplayer].value; + const boolean analogjoystickmove = cv_usejoystick[forplayer].value && !Joystick[forplayer].bGamepadStyle; + const boolean gamepadjoystickmove = cv_usejoystick[forplayer].value && Joystick[forplayer].bGamepadStyle; + if (demo.playback) return; if (ssplayer == 1) player = &players[consoleplayer]; else - player = &players[displayplayers[ssplayer-1]]; + player = &players[displayplayers[forplayer]]; if (ssplayer == 2) - thiscam = (player->bot == 2 ? &camera[0] : &camera[ssplayer-1]); + thiscam = (player->bot == 2 ? &camera[0] : &camera[forplayer]); else - thiscam = &camera[ssplayer-1]; - lang = localangle[ssplayer-1]; - laim = localaiming[ssplayer-1]; - th = turnheld[ssplayer-1]; - kbl = keyboard_look[ssplayer-1]; - rd = resetdown[ssplayer-1]; + thiscam = &camera[forplayer]; + lang = localangle[forplayer]; + laim = localaiming[forplayer]; + th = turnheld[forplayer]; + kbl = keyboard_look[forplayer]; + rd = resetdown[forplayer]; switch (ssplayer) { @@ -1193,31 +921,19 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) case 2: mouseaiming = player->spectator; //(PLAYER2INPUTDOWN(gc_mouseaiming)) ^ cv_alwaysfreelook2.value; invertmouse = cv_invertmouse2.value; - lookaxis = cv_lookaxis2.value; - analogjoystickmove = cv_usejoystick2.value && !Joystick2.bGamepadStyle; - gamepadjoystickmove = cv_usejoystick2.value && Joystick2.bGamepadStyle; break; case 3: mouseaiming = false; invertmouse = false; - lookaxis = cv_lookaxis3.value; - analogjoystickmove = cv_usejoystick3.value && !Joystick3.bGamepadStyle; - gamepadjoystickmove = cv_usejoystick3.value && Joystick3.bGamepadStyle; break; case 4: mouseaiming = false; invertmouse = false; - lookaxis = cv_lookaxis4.value; - analogjoystickmove = cv_usejoystick4.value && !Joystick4.bGamepadStyle; - gamepadjoystickmove = cv_usejoystick4.value && Joystick4.bGamepadStyle; break; case 1: default: mouseaiming = player->spectator; //(PLAYER1INPUTDOWN(gc_mouseaiming)) ^ cv_alwaysfreelook.value; invertmouse = cv_invertmouse.value; - lookaxis = cv_lookaxis.value; - analogjoystickmove = cv_usejoystick.value && !Joystick.bGamepadStyle; - gamepadjoystickmove = cv_usejoystick.value && Joystick.bGamepadStyle; break; } @@ -1280,7 +996,7 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) if (player->spectator || cv_mouseturn.value) { - //THIS WORKS WTF???????? + //THIS WORKS WTF???????? cmd->angleturn = (INT16)(cmd->angleturn - ((mousex*(encoremode ? -1 : 1)*8))); cmd->driftturn = (INT16)(cmd->driftturn - ((mousex*(encoremode ? -1 : 1)*8))); } @@ -1464,13 +1180,13 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) if (!hu_stopped) { - localangle[ssplayer-1] = lang; - localaiming[ssplayer-1] = laim; - keyboard_look[ssplayer-1] = kbl; - turnheld[ssplayer-1] = th; - resetdown[ssplayer-1] = rd; + localangle[forplayer] = lang; + localaiming[forplayer] = laim; + keyboard_look[forplayer] = kbl; + turnheld[forplayer] = th; + resetdown[forplayer] = rd; axis = JoyAxis(AXISLOOKBACK, ssplayer); - camspin[ssplayer-1] = (InputDown(gc_lookback, ssplayer) || (usejoystick && axis > 0)); + camspin[forplayer] = (InputDown(gc_lookback, ssplayer) || (usejoystick && axis > 0)); } /* Lua: Allow this hook to overwrite ticcmd. @@ -1484,54 +1200,31 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) -Making a Mario Kart 8 Deluxe tier baby mode that steers you away from walls and whatnot. You know what, do what you want! */ if (gamestate == GS_LEVEL) - LUAh_PlayerCmd(player, cmd); + LUA_HookTiccmd(player, cmd, HOOK(PlayerCmd)); //Reset away view if a command is given. if ((cmd->forwardmove || cmd->sidemove || cmd->buttons) && displayplayers[0] != consoleplayer && ssplayer == 1) + { displayplayers[0] = consoleplayer; - -} - -static void Analog_OnChange(void) -{ - if (!cv_cam_dist.string) - return; - - SendWeaponPref(); -} - -static void Analog2_OnChange(void) -{ - if (!(splitscreen || botingame) || !cv_cam2_dist.string) - return; - - SendWeaponPref2(); -} - -static void Analog3_OnChange(void) -{ - if (splitscreen < 2 || !cv_cam3_dist.string) - return; - - SendWeaponPref3(); -} - -static void Analog4_OnChange(void) -{ - if (splitscreen < 3 || !cv_cam4_dist.string) - return; - - SendWeaponPref4(); + G_FixCamera(1); + // i dont like this lmao + if (cv_director.value) + CV_SetValue(&cv_director, 0); + } } // // G_DoLoadLevel // -void G_DoLoadLevel(boolean resetplayer) +static void G_DoLoadLevel(boolean resetplayer) { INT32 i; + // Saturn Music Feature stuffs + S_ResetKeepAndSpecialMus(); + S_CheckMap(); + // Make sure objectplace is OFF when you first start the level! OP_ResetObjectplace(); @@ -1787,7 +1480,7 @@ boolean G_Responder(event_t *ev) if (!camtoggledelay) { camtoggledelay = NEWTICRATE / 7; - CV_SetValue(&cv_chasecam, cv_chasecam.value ? 0 : 1); + CV_SetValue(&cv_chasecam[0], cv_chasecam[0].value ? 0 : 1); } } if (ev->data1 == gamecontrolbis[gc_camtoggle][0] @@ -1796,7 +1489,7 @@ boolean G_Responder(event_t *ev) if (!camtoggledelay2) { camtoggledelay2 = NEWTICRATE / 7; - CV_SetValue(&cv_chasecam2, cv_chasecam2.value ? 0 : 1); + CV_SetValue(&cv_chasecam[1], cv_chasecam[1].value ? 0 : 1); } } if (ev->data1 == gamecontrol3[gc_camtoggle][0] @@ -1805,7 +1498,7 @@ boolean G_Responder(event_t *ev) if (!camtoggledelay3) { camtoggledelay3 = NEWTICRATE / 7; - CV_SetValue(&cv_chasecam3, cv_chasecam3.value ? 0 : 1); + CV_SetValue(&cv_chasecam[2], cv_chasecam[2].value ? 0 : 1); } } if (ev->data1 == gamecontrol4[gc_camtoggle][0] @@ -1814,7 +1507,7 @@ boolean G_Responder(event_t *ev) if (!camtoggledelay4) { camtoggledelay4 = NEWTICRATE / 7; - CV_SetValue(&cv_chasecam4, cv_chasecam4.value ? 0 : 1); + CV_SetValue(&cv_chasecam[3], cv_chasecam[3].value ? 0 : 1); } } if (ev->data1 == gamecontrol[gc_spectate][0] @@ -1999,15 +1692,12 @@ static void G_FixCamera(UINT8 view) // The order of displayplayers can change, which would // invalidate localangle. - localangle[view - 1] = player->cmd.angleturn; + localangle[view - 1] = (angle_t)(player->cmd.angleturn << 16); P_ResetCamera(player, &camera[view - 1]); // Make sure the viewport doesn't interpolate at all into // its new position -- just snap instantly into place. - - // Why does it need to be done twice? - R_ResetViewInterpolation(view); R_ResetViewInterpolation(view); } @@ -2022,7 +1712,9 @@ void G_ResetView(UINT8 viewnum, INT32 playernum, boolean onlyactive) UINT8 splits; UINT8 viewd; - INT32 *displayplayerp; + INT32 playernumd; + + INT32 *displayplayerp; INT32 olddisplayplayer; INT32 playersviewable; @@ -2050,30 +1742,21 @@ void G_ResetView(UINT8 viewnum, INT32 playernum, boolean onlyactive) R_ExecuteSetViewSize(); } - displayplayerp = (&displayplayers[viewnum-1]); - olddisplayplayer = (*displayplayerp); - - /* Check if anyone is available to view. */ - if ((playernum = G_FindView(playernum, viewnum, onlyactive, playernum < olddisplayplayer)) == -1) - return; - - /* Focus our target view first so that we don't take its player. */ - (*displayplayerp) = playernum; - - /* If a viewpoint changes, reset the camera to clear uninitialized memory. */ - if (viewnum > splits) + for (viewd = min(splits+1, viewnum); viewd <= viewnum; ++viewd) { - for (viewd = splits+1; viewd <= viewnum; ++viewd) - { - G_FixCamera(viewd); - } - } - else - { - if ((*displayplayerp) != olddisplayplayer) - { - G_FixCamera(viewnum); - } + playernumd = (viewd == viewnum) ? playernum : displayplayers[viewd-1]; + displayplayerp = (&displayplayers[viewd-1]); + olddisplayplayer = (*displayplayerp); + + /* Check if anyone is available to view. */ + if ((playernumd = G_FindView(playernumd, viewd, onlyactive, playernumd < olddisplayplayer)) == -1) + continue; + + /* Focus our target view first so that we don't take its player. */ + (*displayplayerp) = playernumd; + + /* If a viewpoint changes, reset the camera to clear uninitialized memory. */ + G_FixCamera(viewd); } if (viewnum == 1 && demo.playback) @@ -2719,7 +2402,7 @@ void G_SpawnPlayer(INT32 playernum, boolean starpost) if (starpost) //Don't even bother with looking for a place to spawn. { P_MovePlayerToStarpost(playernum); - LUAh_PlayerSpawn(&players[playernum]); // Lua hook for player spawning :) + LUA_HookPlayer(&players[playernum], HOOK(PlayerSpawn)); // Lua hook for player spawning :) return; } @@ -2775,7 +2458,7 @@ void G_SpawnPlayer(INT32 playernum, boolean starpost) } P_MovePlayerToSpawn(playernum, spawnpoint); - LUAh_PlayerSpawn(&players[playernum]); // Lua hook for player spawning :) + LUA_HookPlayer(&players[playernum], HOOK(PlayerSpawn)); // Lua hook for player spawning :) } mapthing_t *G_FindCTFStart(INT32 playernum) @@ -3620,6 +3303,8 @@ void G_AfterIntermission(void) } else if (demo.recording && (modeattacking || demo.savemode != DSM_NOTSAVING)) G_SaveDemo(); + else if (demo.recording) + G_ResetDemoRecording(); if (modeattacking) // End the run. { @@ -3767,6 +3452,8 @@ void G_EndGame(void) { if (demo.recording && (modeattacking || demo.savemode != DSM_NOTSAVING)) G_SaveDemo(); + else if (demo.recording) + G_ResetDemoRecording(); // Only do evaluation and credits in coop games. if (gametype == GT_COOP) @@ -4378,8 +4065,7 @@ void G_InitNew(UINT8 pencoremode, const char *mapname, boolean resetplayer, bool F_StartCustomCutscene(mapheaderinfo[gamemap-1]->precutscenenum-1, true, resetplayer); else { - LUAh_MapChange(gamemap); - S_CheckMap(); + LUA_HookInt(gamemap, HOOK(MapChange)); G_DoLoadLevel(resetplayer); } @@ -4541,8 +4227,7 @@ INT32 G_FindMap(const char *mapname, char **foundmapnamep, break; } } - else - if (apromapnum == 0 || wanttable) + else if (apromapnum == 0 || wanttable) { /* LEVEL 1--match keywords verbatim */ if (( aprop = strcasestr(realmapname, mapname) )) @@ -4633,8 +4318,8 @@ INT32 G_FindMapByNameOrCode(const char *mapname, char **realmapnamep) { if (mapname[0] == '*') // current map return gamemap; - else if (mapname[0] == '?') - return G_RandMap(G_TOLFlag(gametype), prevmap, false, 0, false, NULL); + else if (mapname[0] == '?' && mapheaderinfo[gamemap-1]) + return G_RandMap(G_TOLFlag(gametype), gamemap-1, false, 0, false, NULL)+1; else if (mapname[0] == '+' && mapheaderinfo[gamemap-1]) // next map { newmapnum = mapheaderinfo[gamemap-1]->nextlevel; @@ -6310,11 +5995,8 @@ void G_RecordDemo(const char *name) { INT32 maxsize; - demobuf.p = NULL; - demo.recording = false; - if (demobuf.buffer) - free(demobuf.buffer); - demobuf.buffer = NULL; + demo_p = NULL; + G_ResetDemoRecording(); demoend = NULL; if (cv_recordmultiplayerdemos.value) @@ -6326,8 +6008,8 @@ void G_RecordDemo(const char *name) maxsize = cv_maxdemosize.value*1024*1024; - demobuf.buffer = malloc(maxsize); - demoend = demobuf.buffer + maxsize; + demobuffer = Z_Malloc(maxsize, PU_STATIC, NULL); + demoend = demobuffer + maxsize; if (demobuf.buffer) demo.recording = true; @@ -6340,12 +6022,12 @@ void G_RecordMetal(void) { INT32 maxsize; maxsize = cv_maxdemosize.value*1024*1024; - if (demobuf.buffer) - free(demobuf.buffer); - demobuf.p = NULL; + if (demobuffer) + Z_Free(demobuffer); + demo_p = NULL; metalrecording = false; - demobuf.buffer = malloc(maxsize); - demoend = demobuf.buffer + maxsize; + demobuffer = Z_Malloc(maxsize, PU_STATIC, NULL); + demoend = demobuffer + maxsize; if (demobuf.buffer) metalrecording = true; @@ -7196,11 +6878,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } demobuf.p += 12; // DEMOHEADER @@ -7225,11 +6903,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } demobuf.p += 16; // demo checksum @@ -7238,11 +6912,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } demobuf.p += 4; // "PLAY" @@ -7258,11 +6928,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is an alpha multiplayer replay and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } } @@ -7319,11 +6985,7 @@ void G_DoPlayDemo(char *defdemoname) CONS_Alert(CONS_ERROR, "%s", msg); if (!CON_Ready()) // In the console they'll just see the notice there! No point pulling them out. M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } } @@ -7386,11 +7048,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s features a character that is not currently loaded.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } @@ -7400,11 +7058,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s features a course that is not currently loaded.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } @@ -7425,11 +7079,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } @@ -7469,11 +7119,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } @@ -7500,7 +7146,7 @@ void G_DoPlayDemo(char *defdemoname) // didn't start recording right away. demo.deferstart = false; - //LUAh_MapChange(gamemap); + //LUA_HookInt(gamemap, HOOK(MapChange)); displayplayers[0] = consoleplayer = 0; memset(playeringame,0,sizeof(playeringame)); @@ -7524,11 +7170,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with spectators, and is thus invalid.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } } @@ -7539,11 +7181,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with multiple players, and is thus invalid.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - Z_Free(pdemoname); - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - demo.title = false; + G_ResetDemoPlayback(pdemoname); return; } @@ -8186,8 +7824,8 @@ ATTRNORETURN void FUNCNORETURN G_StopMetalRecording(void) #endif saved = FIL_WriteFile(va("%sMS.LMP", G_BuildMapName(gamemap)), demobuf.buffer, demobuf.p - demobuf.buffer); // finally output the file. } - free(demobuf.buffer); - demobuf.buffer = NULL; + Z_Free(demobuffer); + demobuffer = NULL; metalrecording = false; if (saved) I_Error("Saved to %sMS.LMP", G_BuildMapName(gamemap)); @@ -8291,7 +7929,10 @@ boolean G_CheckDemoStatus(void) return true; } - if (demo.recording && (modeattacking || demo.savemode != DSM_NOTSAVING)) + if (!demo.recording) + return false; + + if (modeattacking || demo.savemode != DSM_NOTSAVING) { if (demobuf.p) { @@ -8300,14 +7941,41 @@ boolean G_CheckDemoStatus(void) return true; } - demo.recording = false; + G_ResetDemoRecording(); return false; } +void G_ResetDemoRecording(void) +{ + if (demobuffer) + Z_Free(demobuffer); + demobuffer = NULL; + demo.recording = false; +} + +static void G_ResetDemoPlayback(char *pdemoname) +{ + if (pdemoname) + Z_Free(pdemoname); + if (demobuffer) + Z_Free(demobuffer); + demobuffer = NULL; + demo.playback = false; + demo.title = false; +} + void G_SaveDemo(void) { - UINT8 *p = demobuf.buffer+16; // after version + if (!demo_p) + { + CONS_Alert(CONS_ERROR, "Failed to save Demo. No Demo pointer exists!\n"); + // reset the demo buffer + G_ResetDemoRecording(); + return; + } + + UINT8 *p = demobuffer+16; // after version UINT32 length; #ifdef NOMD5 UINT8 i; @@ -8376,9 +8044,8 @@ void G_SaveDemo(void) if (FIL_WriteFile(va(pandf, srb2home, demoname), demobuf.buffer, demobuf.p - demobuf.buffer)) // finally output the file. demo.savemode = DSM_SAVED; - free(demobuf.buffer); - demobuf.buffer = NULL; - demo.recording = false; + + G_ResetDemoRecording(); if (modeattacking != ATTACKING_RECORD) { diff --git a/src/g_game.h b/src/g_game.h index f954e0c3e..7c81ab79e 100644 --- a/src/g_game.h +++ b/src/g_game.h @@ -121,12 +121,21 @@ extern consvar_t cv_pauseifunfocused; //extern consvar_t cv_crosshair, cv_crosshair2, cv_crosshair3, cv_crosshair4; extern consvar_t cv_invertmouse/*, cv_alwaysfreelook, cv_chasefreelook, cv_mousemove*/; extern consvar_t cv_invertmouse2/*, cv_alwaysfreelook2, cv_chasefreelook2, cv_mousemove2*/; -extern consvar_t cv_useranalog, cv_useranalog2, cv_useranalog3, cv_useranalog4; -extern consvar_t cv_analog, cv_analog2, cv_analog3, cv_analog4; -extern consvar_t cv_turnaxis,cv_moveaxis,cv_brakeaxis,cv_aimaxis,cv_lookaxis,cv_fireaxis,cv_driftaxis,cv_lookbackaxis,cv_custom1axis,cv_custom2axis,cv_custom3axis,cv_xdeadzone,cv_ydeadzone; -extern consvar_t cv_turnaxis2,cv_moveaxis2,cv_brakeaxis2,cv_aimaxis2,cv_lookaxis2,cv_fireaxis2,cv_driftaxis2,cv_lookbackaxis2,cv_custom1axis2,cv_custom2axis2,cv_custom3axis2,cv_xdeadzone2,cv_ydeadzone2; -extern consvar_t cv_turnaxis3,cv_moveaxis3,cv_brakeaxis3,cv_aimaxis3,cv_lookaxis3,cv_fireaxis3,cv_driftaxis3,cv_lookbackaxis3,cv_custom1axis3,cv_custom2axis3,cv_custom3axis3,cv_xdeadzone3,cv_ydeadzone3; -extern consvar_t cv_turnaxis4,cv_moveaxis4,cv_brakeaxis4,cv_aimaxis4,cv_lookaxis4,cv_fireaxis4,cv_driftaxis4,cv_lookbackaxis4,cv_custom1axis4,cv_custom2axis4,cv_custom3axis4,cv_xdeadzone4,cv_ydeadzone4; + +extern consvar_t cv_turnaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_moveaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_brakeaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_aimaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_lookaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_lookbackaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_fireaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_driftaxis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_custom1axis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_custom2axis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_custom3axis[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_xdeadzone[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_ydeadzone[MAXSPLITSCREENPLAYERS]; + extern consvar_t cv_ghost_besttime, cv_ghost_bestlap, cv_ghost_last, cv_ghost_guest, cv_ghost_staff; // Hud offsets @@ -167,7 +176,6 @@ extern consvar_t cv_saltysquish; extern consvar_t cv_driftsparkpulse; extern consvar_t cv_gravstretch; extern consvar_t cv_sloperoll; -extern consvar_t cv_spriteroll; extern consvar_t cv_sliptideroll; extern consvar_t cv_slamsound; extern consvar_t cv_sloperolldist; @@ -267,7 +275,6 @@ void G_SpawnPlayer(INT32 playernum, boolean starpost); // A normal game starts at map 1, but a warp test can start elsewhere void G_DeferedInitNew(boolean pencoremode, const char *mapname, INT32 pickedchar, UINT8 ssplayers, boolean FLS); -void G_DoLoadLevel(boolean resetplayer); void G_LoadDemoInfo(menudemo_t *pdemo); void G_LoadDemoTitle(menudemo_t *pdemo); // For use in replay search feature @@ -357,6 +364,7 @@ extern demoghost *ghosts; #define DFILE_ERROR_CANNOTLOAD 0x04 // Files are missing and cannot be loaded. #define DFILE_ERROR_EXTRAFILES 0x05 // Extra files outside of the replay's file list are loaded. +void G_ResetDemoRecording(void); void G_DoPlayDemo(char *defdemoname); void G_TimeDemo(const char *name); void G_AddGhost(char *defdemoname); diff --git a/src/g_input.c b/src/g_input.c index ad7758a7a..7f2fff283 100644 --- a/src/g_input.c +++ b/src/g_input.c @@ -908,28 +908,6 @@ static const char *gamecontrolname[num_gamecontrols] = #include "k_kart.h" -INT32 G_GetDeviceForPlayer(INT32 player) -{ - switch (player) - { - case 0: - return cv_usejoystick.value; - break; - case 1: - return cv_usejoystick2.value; - break; - case 2: - return cv_usejoystick3.value; - break; - case 3: - return cv_usejoystick4.value; - break; - default: - return 0; - break; - } -} - inline UINT16 G_GetSkinColor(INT32 player) { // make rgb rainbow vomit when invul or flash blue when grow @@ -972,7 +950,7 @@ void G_SetPlayerGamepadIndicatorColor(INT32 player, UINT16 color) if (cv_gamepadled[player].value == 0) return; - device = G_GetDeviceForPlayer(player); + device = cv_usejoystick[player].value; if (device <= 0) { @@ -989,7 +967,7 @@ static void G_ResetPlayerGamepadIndicatorColor(INT32 player) { if (cv_gamepadled[player].value == 0) { - INT32 device = G_GetDeviceForPlayer(player); + INT32 device = cv_usejoystick[player].value; if (device <= 0) return; @@ -1003,7 +981,7 @@ static void G_ResetPlayerDeviceRumble(INT32 player) { INT32 device_id; - device_id = G_GetDeviceForPlayer(player); + device_id = cv_usejoystick[player].value; if (device_id < 1) { @@ -1022,7 +1000,7 @@ void G_ResetAllDeviceRumbles(void) for (i = 0; i < devices; i++) { - INT32 device_id = G_GetDeviceForPlayer(i); + INT32 device_id = cv_usejoystick[i].value; I_GamepadRumble(device_id, 0, 0, 0); } @@ -1037,7 +1015,7 @@ void G_PlayerDeviceRumble(INT32 player, UINT16 low_strength, UINT16 high_strengt return; } - device_id = G_GetDeviceForPlayer(player); + device_id = cv_usejoystick[player].value; if (device_id < 1) { diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c index a4984a905..82cfd31db 100644 --- a/src/hardware/hw_batching.c +++ b/src/hardware/hw_batching.c @@ -15,8 +15,9 @@ #include "hw_main.h" #include "../i_system.h" -#include "../qs22j.h" +#include "../doomdef.h" +#include "../qs22j.h" // The texture for the next polygon given to HWR_ProcessPolygon. // Set with HWR_SetCurrentTexture. @@ -46,12 +47,12 @@ int unsortedVertexArrayAllocSize = 65536; // Call HWR_RenderBatches to render all the collected geometry. void HWR_StartBatching(void) { - if (currently_batching) + if (currently_batching) { - I_Error("Repeat call to HWR_StartBatching without HWR_RenderBatches"); + I_Error("Repeat call to HWR_StartBatching without HWR_RenderBatches"); } - // init arrays if that has not been done yet + // init arrays if that has not been done yet if (!finalVertexArray) { finalVertexArray = malloc(finalVertexArrayAllocSize * sizeof(FOutVector)); @@ -61,22 +62,22 @@ void HWR_StartBatching(void) unsortedVertexArray = malloc(unsortedVertexArrayAllocSize * sizeof(FOutVector)); } - currently_batching = true; + currently_batching = true; } -// This replaces the direct calls to pfnSetTexture in cases where batching is available. +// This replaces the direct calls to GL_SetTexture in cases where batching is available. // The texture selection is saved for the next HWR_ProcessPolygon call. // Doing this was easier than getting a texture pointer to HWR_ProcessPolygon. void HWR_SetCurrentTexture(GLMipmap_t *texture) { - if (currently_batching) - { - current_texture = texture; - } - else - { - HWD.pfnSetTexture(texture); - } + if (currently_batching) + { + current_texture = texture; + } + else + { + GL_SetTexture(texture); + } } // If batching is enabled, this function collects the polygon data and the chosen texture @@ -84,7 +85,7 @@ void HWR_SetCurrentTexture(GLMipmap_t *texture) // render the polygon immediately. void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, int shader_target, boolean horizonSpecial) { - if (currently_batching) + if (currently_batching) { if (!pSurf) I_Error("Got a null FSurfaceInfo in batching");// nulls should not come in the stuff that batching currently applies to @@ -129,8 +130,8 @@ void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPt } else { - HWD.pfnSetShader((shader_target != SHADER_NONE) ? HWR_GetShaderFromTarget(shader_target) : shader_target); - HWD.pfnDrawPolygon(pSurf, pOutVerts, iNumPts, PolyFlags); + GL_SetShader((shader_target != SHADER_NONE) ? HWR_GetShaderFromTarget(shader_target) : shader_target); + GL_DrawPolygon(pSurf, pOutVerts, iNumPts, PolyFlags); } } @@ -220,14 +221,14 @@ static int comparePolygonsNoShaders(const void *p1, const void *p2) // the rendering backend to draw them. void HWR_RenderBatches(void) { - int finalVertexWritePos = 0;// position in finalVertexArray + int finalVertexWritePos = 0;// position in finalVertexArray int finalIndexWritePos = 0;// position in finalVertexIndexArray int polygonReadPos = 0;// position in polygonArraySorted int currentShader; int nextShader = 0; - GLMipmap_t *currentTexture; + GLMipmap_t *currentTexture = NULL; GLMipmap_t *nextTexture = NULL; FBITFIELD currentPolyFlags = 0; FBITFIELD nextPolyFlags = 0; @@ -236,7 +237,7 @@ void HWR_RenderBatches(void) int i; - if (!currently_batching) + if (!currently_batching) I_Error("HWR_RenderBatches called without starting batching"); nextSurfaceInfo.LightInfo.fade_end = 0; @@ -256,6 +257,7 @@ void HWR_RenderBatches(void) ps_hw_numcalls.value.i = ps_hw_numverts.value.i = 0; ps_hw_numshaders.value.i = ps_hw_numtextures.value.i = ps_hw_numpolyflags.value.i = ps_hw_numcolors.value.i = 1; + // init polygonArraySorted for (i = 0; i < polygonArraySize; i++) { @@ -264,11 +266,12 @@ void HWR_RenderBatches(void) // sort polygons PS_START_TIMING(ps_hw_batchsorttime); - if (cv_grshaders.value && gr_shadersavailable) + if (cv_glshaders.value && gl_shadersavailable) qs22j(polygonArraySorted, polygonArraySize, sizeof(PolygonArrayEntry *), comparePolygons); else qs22j(polygonArraySorted, polygonArraySize, sizeof(PolygonArrayEntry *), comparePolygonsNoShaders); PS_STOP_TIMING(ps_hw_batchsorttime); + // sort order // 1. shader // 2. texture @@ -287,15 +290,15 @@ void HWR_RenderBatches(void) // set state for first batch - if (cv_grshaders.value && gr_shadersavailable) + if (cv_glshaders.value && gl_shadersavailable) { - HWD.pfnSetShader(currentShader); + GL_SetShader(currentShader); } if (currentPolyFlags & PF_NoTexture) currentTexture = NULL; - else - HWD.pfnSetTexture(currentTexture); + else + GL_SetTexture(currentTexture); while (1)// note: remember handling notexture polyflag as having texture number 0 (also in comparePolygons) { @@ -369,7 +372,7 @@ void HWR_RenderBatches(void) nextSurfaceInfo = nextEntry->surf; if (nextPolyFlags & PF_NoTexture) nextTexture = 0; - if (currentShader != nextShader && cv_grshaders.value && gr_shadersavailable) + if (currentShader != nextShader && cv_glshaders.value && gl_shadersavailable) { changeState = true; changeShader = true; @@ -384,7 +387,7 @@ void HWR_RenderBatches(void) changeState = true; changePolyFlags = true; } - if (cv_grshaders.value && gr_shadersavailable) + if (cv_glshaders.value && gl_shadersavailable) { if (currentSurfaceInfo.PolyColor.rgba != nextSurfaceInfo.PolyColor.rgba || currentSurfaceInfo.TintColor.rgba != nextSurfaceInfo.TintColor.rgba || @@ -410,7 +413,7 @@ void HWR_RenderBatches(void) if (changeState || stopFlag) { // execute draw call - HWD.pfnDrawIndexedTriangles(¤tSurfaceInfo, finalVertexArray, finalIndexWritePos, currentPolyFlags, finalVertexIndexArray); + GL_DrawIndexedTriangles(¤tSurfaceInfo, finalVertexArray, finalIndexWritePos, currentPolyFlags, finalVertexIndexArray); // update stats ps_hw_numcalls.value.i++; ps_hw_numverts.value.i += finalIndexWritePos; @@ -428,7 +431,7 @@ void HWR_RenderBatches(void) { if (changeShader) { - HWD.pfnSetShader(nextShader); + GL_SetShader(nextShader); currentShader = nextShader; changeShader = false; @@ -436,8 +439,8 @@ void HWR_RenderBatches(void) } if (changeTexture) { - // texture should be already ready for use from calls to SetTexture during batch collection - HWD.pfnSetTexture(nextTexture); + // texture should be already ready for use from calls to GL_SetTexture during batch collection + GL_SetTexture(nextTexture); currentTexture = nextTexture; changeTexture = false; @@ -457,6 +460,7 @@ void HWR_RenderBatches(void) ps_hw_numcolors.value.i++; } + // and that should be it? } } // reset the arrays (set sizes to 0) @@ -466,5 +470,4 @@ void HWR_RenderBatches(void) PS_STOP_TIMING(ps_hw_batchdrawtime); } - #endif // HWRENDER diff --git a/src/hardware/hw_batching.h b/src/hardware/hw_batching.h index 22a4cc4c0..7f418fc77 100644 --- a/src/hardware/hw_batching.h +++ b/src/hardware/hw_batching.h @@ -15,7 +15,9 @@ #include "hw_defs.h" #include "hw_data.h" -#include "hw_drv.h" +#include "hw_gl.h" + +extern boolean currently_batching; typedef struct { diff --git a/src/hardware/hw_bsp.c b/src/hardware/hw_bsp.c index a5f76df06..88ef77320 100644 --- a/src/hardware/hw_bsp.c +++ b/src/hardware/hw_bsp.c @@ -46,7 +46,7 @@ typedef struct // when loading the map, this is set to true if portals are found. // if no portals are found, the portal scanning phase can be skipped while rendering, saving a bit of time. -boolean gr_maphasportals = false; +boolean gl_maphasportals = false; // ========================================================================== // FLOOR & CEILING CONVEX POLYS GENERATION @@ -371,14 +371,14 @@ static poly_t *CutOutSubsecPoly(seg_t *lseg, INT32 count, poly_t *poly) line_t *line = lseg->linedef; // portal check - if (!gr_maphasportals && line->special == 40 && lseg->side == 0) + if (!gl_maphasportals && line->special == 40 && lseg->side == 0) { // Find the other side! INT32 line2 = P_FindSpecialLineFromTag(40, line->tag, -1); if (line == &lines[line2]) line2 = P_FindSpecialLineFromTag(40, line->tag, line2); if (line2 >= 0) // found it! - gr_maphasportals = 1; + gl_maphasportals = 1; } p1.x = FIXED_TO_FLOAT(lseg->side ? line->v2->x : line->v1->x); @@ -768,7 +768,7 @@ static INT32 SolveTProblem(void) INT32 i; size_t l; - if (cv_grsolvetjoin.value == 0) + if (cv_glsolvetjoin.value == 0) return 0; CONS_Debug(DBG_RENDER, "Solving T-joins. This may take a while. Please wait...\n"); @@ -905,7 +905,7 @@ void HWR_CreatePlanePolygons(INT32 bspnum) #endif // reset the portal flag - gr_maphasportals = 0; + gl_maphasportals = 0; // find min/max boundaries of map //CONS_Debug(DBG_RENDER, "Looking for boundaries of map...\n"); @@ -923,9 +923,9 @@ void HWR_CreatePlanePolygons(INT32 bspnum) I_Error("couldn't malloc extrasubsectors totsubsectors %s\n", sizeu1(totsubsectors)); // allocate table for back to front drawing of subsectors - /*gr_drawsubsectors = (INT16 *)malloc(sizeof (*gr_drawsubsectors) * totsubsectors); - if (!gr_drawsubsectors) - I_Error("couldn't malloc gr_drawsubsectors\n");*/ + /*gl_drawsubsectors = (INT16 *)malloc(sizeof (*gl_drawsubsectors) * totsubsectors); + if (!gl_drawsubsectors) + I_Error("couldn't malloc gl_drawsubsectors\n");*/ // number of the first new subsector that might be added addsubsector = numsubsectors; diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index 9f02007d4..ad140c025 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -14,9 +14,10 @@ #include "../doomdef.h" #ifdef HWRENDER + #include "hw_main.h" #include "hw_glob.h" -#include "hw_drv.h" +#include "hw_gl.h" #include "hw_batching.h" #include "../doomstat.h" //gamemode @@ -54,10 +55,10 @@ static INT32 format2bpp(GLTextureFormat_t format) // It is now split from it for my sanity! (and the sanity of others) // -- Monster Iestyn (13/02/19) static void HWR_DrawColumnInCache(const column_t *patchcol, UINT8 *block, GLMipmap_t *mipmap, - INT32 pblockheight, INT32 blockmodulo, - fixed_t yfracstep, fixed_t scale_y, - texpatch_t *originPatch, INT32 patchheight, - INT32 bpp, RGBA_t *palette) + INT32 pblockheight, INT32 blockmodulo, + fixed_t yfracstep, fixed_t scale_y, + texpatch_t *originPatch, INT32 patchheight, + INT32 bpp, RGBA_t *palette) { fixed_t yfrac, position, count; UINT8 *dest; @@ -73,6 +74,9 @@ static void HWR_DrawColumnInCache(const column_t *patchcol, UINT8 *block, GLMipm (void)patchheight; // This parameter is unused + if (!mipmap) + return; + if (originPatch) // originPatch can be NULL here, unlike in the software version originy = originPatch->originy; @@ -108,14 +112,14 @@ static void HWR_DrawColumnInCache(const column_t *patchcol, UINT8 *block, GLMipm count--; texel = source[yfrac>>FRACBITS]; - alpha = 0xff; + alpha = 0xFF; - //Hurdler: not perfect, but better than holes - if (texel == HWR_PATCHES_CHROMAKEY_COLORINDEX && (mipmap->flags & TF_CHROMAKEYED)) + // Make pixel transparent if chroma keyed + if ((mipmap && mipmap->flags & TF_CHROMAKEYED) && (texel == HWR_PATCHES_CHROMAKEY_COLORINDEX)) alpha = 0x00; //Hurdler: 25/04/2000: now support colormap in hardware mode - if (mipmap->colormap) + if (mipmap && mipmap->colormap) texel = mipmap->colormap[texel]; // hope compiler will get this switch out of the loops (dreams...) @@ -123,7 +127,8 @@ static void HWR_DrawColumnInCache(const column_t *patchcol, UINT8 *block, GLMipm // Alam: SRB2 uses Mingw, HUGS switch (bpp) { - case 2 : texelu16 = (UINT16)((alpha<<8) | texel); + case 2 : // uhhhhhhhh.......... + texelu16 = (UINT16)((alpha<<8) | texel); memcpy(dest, &texelu16, sizeof(UINT16)); break; case 3 : colortemp = palette[texel]; @@ -141,6 +146,7 @@ static void HWR_DrawColumnInCache(const column_t *patchcol, UINT8 *block, GLMipm dest += blockmodulo; yfrac += yfracstep; } + patchcol = (const column_t *)((const UINT8 *)patchcol + patchcol->length + 4); } } @@ -166,7 +172,7 @@ static void HWR_DrawPatchInCache(GLMipmap_t *mipmap, if (pwidth <= 0 || pheight <= 0) return; - + palette = HWR_GetTexturePalette(); ncols = pwidth; @@ -182,6 +188,7 @@ static void HWR_DrawPatchInCache(GLMipmap_t *mipmap, if (bpp < 1 || bpp > 4) I_Error("HWR_DrawPatchInCache: no drawer defined for this bpp (%d)\n",bpp); + // NOTE: should this actually be pblockwidth*bpp? blockmodulo = pblockwidth*bpp; // Draw each column to the block cache @@ -216,7 +223,7 @@ static void HWR_DrawTexturePatchInCache(GLMipmap_t *mipmap, if (texture->width <= 0 || texture->height <= 0) return; - + palette = HWR_GetTexturePalette(); x1 = patch->originx; @@ -260,6 +267,7 @@ static void HWR_DrawTexturePatchInCache(GLMipmap_t *mipmap, if (bpp < 1 || bpp > 4) I_Error("HWR_DrawTexturePatchInCache: no drawer defined for this bpp (%d)\n",bpp); + // NOTE: should this actually be pblockwidth*bpp? blockmodulo = pblockwidth*bpp; // Draw each column to the block cache @@ -275,15 +283,15 @@ static void HWR_DrawTexturePatchInCache(GLMipmap_t *mipmap, } } -static UINT8 *MakeBlock(GLMipmap_t *grMipmap) +static UINT8 *MakeBlock(GLMipmap_t *glMipmap) { UINT8 *block; INT32 bpp, i; UINT16 bu16 = ((0x00 <<8) | HWR_PATCHES_CHROMAKEY_COLORINDEX); - INT32 blocksize = (grMipmap->width * grMipmap->height); + INT32 blocksize = (glMipmap->width * glMipmap->height); - bpp = format2bpp(grMipmap->format); - block = Z_Malloc(blocksize*bpp, PU_HWRCACHE, &(grMipmap->data)); + bpp = format2bpp(glMipmap->format); + block = Z_Malloc(blocksize*bpp, PU_HWRCACHE, &(glMipmap->data)); switch (bpp) { @@ -303,7 +311,7 @@ static UINT8 *MakeBlock(GLMipmap_t *grMipmap) // Create a composite texture from patches, adapt the texture size to a power of 2 // height and width for the hardware texture cache. // -static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *grtex, boolean noencore) +static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noencore) { UINT8 *block; texture_t *texture; @@ -313,7 +321,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *grtex, boolean noe INT32 i; boolean skyspecial = false; //poor hack for Legacy large skies.. - + RGBA_t *palette; palette = HWR_GetTexturePalette(); @@ -328,30 +336,30 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *grtex, boolean noe ) { skyspecial = true; - grtex->mipmap.flags = TF_WRAPXY; // don't use the chromakey for sky + gltex->mipmap.flags = TF_WRAPXY; // don't use the chromakey for sky } else - grtex->mipmap.flags = TF_CHROMAKEYED | TF_WRAPXY; + gltex->mipmap.flags = TF_CHROMAKEYED | TF_WRAPXY; - grtex->mipmap.width = (UINT16)texture->width; - grtex->mipmap.height = (UINT16)texture->height; + gltex->mipmap.width = (UINT16)(texture->width); + gltex->mipmap.height = (UINT16)(texture->height); if (skyspecial) - grtex->mipmap.format = GL_TEXFMT_RGBA; // that skyspecial code below assumes this format ... + gltex->mipmap.format = GL_TEXFMT_RGBA; // that skyspecial code below assumes this format ... else - grtex->mipmap.format = textureformat; + gltex->mipmap.format = textureformat; - grtex->mipmap.colormap = colormaps; + gltex->mipmap.colormap = colormaps; #ifdef GLENCORE if (encoremap && !noencore) - grtex->mipmap.colormap += COLORMAP_REMAPOFFSET; + gltex->mipmap.colormap += COLORMAP_REMAPOFFSET; #endif - + blockwidth = texture->width; blockheight = texture->height; blocksize = (blockwidth * blockheight); - block = MakeBlock(&grtex->mipmap); + block = MakeBlock(&gltex->mipmap); if (skyspecial) //Hurdler: not efficient, but better than holes in the sky (and it's done only at level loading) { @@ -359,14 +367,17 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *grtex, boolean noe RGBA_t col; col = palette[HWR_CHROMAKEY_EQUIVALENTCOLORINDEX]; + for (j = 0; j < blockheight; j++) { for (i = 0; i < blockwidth; i++) { - block[4*(j*blockwidth+i)+0] = col.s.red; - block[4*(j*blockwidth+i)+1] = col.s.green; - block[4*(j*blockwidth+i)+2] = col.s.blue; - block[4*(j*blockwidth+i)+3] = 0xff; + int idx = (j*blockwidth+i); + + block[4*idx+0] = col.s.red; + block[4*idx+1] = col.s.green; + block[4*idx+2] = col.s.blue; + block[4*idx+3] = 0xff; } } } @@ -375,86 +386,81 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *grtex, boolean noe for (i = 0, patch = texture->patches; i < texture->patchcount; i++, patch++) { realpatch = W_CacheLumpNumPwad(patch->wad, patch->lump, PU_CACHE); - HWR_DrawTexturePatchInCache(&grtex->mipmap, - blockwidth, blockheight, - texture, patch, - realpatch); + HWR_DrawTexturePatchInCache(&gltex->mipmap, blockwidth, blockheight, texture, patch, realpatch); Z_ChangeTag(realpatch, PU_HWRCACHE_UNLOCKED); } //Hurdler: not efficient at all but I don't remember exactly how HWR_DrawPatchInCache works :( - if (format2bpp(grtex->mipmap.format)==4) + if (format2bpp(gltex->mipmap.format) == 4) { for (i = 3; i < blocksize*4; i += 4) // blocksize*4 because blocksize doesn't include the bpp { if (block[i] != 0) continue; - grtex->mipmap.flags |= TF_TRANSPARENT; + gltex->mipmap.flags |= TF_TRANSPARENT; break; } } - grtex->scaleX = 1.0f/(texture->width*FRACUNIT); - grtex->scaleY = 1.0f/(texture->height*FRACUNIT); + gltex->scaleX = 1.0f/(texture->width*FRACUNIT); + gltex->scaleY = 1.0f/(texture->height*FRACUNIT); } -// patch may be NULL if grMipmap has been initialised already and makebitmap is false -void HWR_MakePatch (patch_t *patch, GLPatch_t *grPatch, GLMipmap_t *grMipmap, boolean makebitmap) +// patch may be NULL if glMipmap has been initialised already and makebitmap is false +void HWR_MakePatch (patch_t *patch, GLPatch_t *glPatch, GLMipmap_t *glMipmap, boolean makebitmap) { // don't do it twice (like a cache) - if (grMipmap->width == 0) + if (glMipmap->width == 0) { // save the original patch header so that the GLPatch can be casted // into a standard patch_t struct and the existing code can get the // orginal patch dimensions and offsets. - grPatch->width = SHORT(patch->width); - grPatch->height = SHORT(patch->height); - grPatch->leftoffset = SHORT(patch->leftoffset); - grPatch->topoffset = SHORT(patch->topoffset); + glPatch->width = SHORT(patch->width); + glPatch->height = SHORT(patch->height); + glPatch->leftoffset = SHORT(patch->leftoffset); + glPatch->topoffset = SHORT(patch->topoffset); - //grMipmap->width = (UINT16)SHORT(patch->width); - //grMipmap->height = (UINT16)SHORT(patch->height); - grMipmap->width = grMipmap->height = 1; - while (grMipmap->width < grPatch->width) grMipmap->width <<= 1; - while (grMipmap->height < grPatch->height) grMipmap->height <<= 1; + glMipmap->width = glMipmap->height = 1; + while (glMipmap->width < glPatch->width) glMipmap->width <<= 1; + while (glMipmap->height < glPatch->height) glMipmap->height <<= 1; // no wrap around, no chroma key - grMipmap->flags = 0; + glMipmap->flags = 0; + // setup the texture info - grMipmap->format = patchformat; - - //grPatch->max_s = grPatch->max_t = 1.0f; - grPatch->max_s = (float)grPatch->width / (float)grMipmap->width; - grPatch->max_t = (float)grPatch->height / (float)grMipmap->height; + glMipmap->format = patchformat; + + //glPatch->max_s = glPatch->max_t = 1.0f; + glPatch->max_s = (float)glPatch->width / (float)glMipmap->width; + glPatch->max_t = (float)glPatch->height / (float)glMipmap->height; } - Z_Free(grMipmap->data); - grMipmap->data = NULL; + Z_Free(glMipmap->data); + glMipmap->data = NULL; if (makebitmap) { - MakeBlock(grMipmap); - HWR_DrawPatchInCache(grMipmap, - grMipmap->width, grMipmap->height, - grPatch->width, grPatch->height, + MakeBlock(glMipmap); + + HWR_DrawPatchInCache(glMipmap, + glMipmap->width, glMipmap->height, + glPatch->width, glPatch->height, patch); } - - //grPatch->max_s = grPatch->max_t = 1.0f; } // ================================================= // CACHING HANDLING // ================================================= -static size_t gr_numtextures; -static GLMapTexture_t *gr_textures; // For all textures +static size_t gl_numtextures; +static GLMapTexture_t *gl_textures; // For all textures void HWR_InitTextureCache(void) { - gr_numtextures = 0; - gr_textures = NULL; + gl_numtextures = 0; + gl_textures = NULL; } // Callback function for HWR_FreeTextureCache. @@ -494,7 +500,7 @@ static void FreeMipmapColormap(INT32 patchnum, void *patch) if (next->data) Z_Free(next->data); next->data = NULL; - HWD.pfnDeleteTexture(next); + GL_DeleteTexture(next); // Free the old colormap mipmap from memory. free(next); @@ -505,7 +511,7 @@ void HWR_FreeMipmapCache(void) { INT32 i; // free references to the textures - HWD.pfnClearMipMapCache(); + GL_ClearMipMapCache(); // free all hardware-converted graphics cached in the heap // our gool is only the textures since user of the texture is the texture cache @@ -526,10 +532,10 @@ void HWR_FreeTextureCache(void) // now the heap don't have any 'user' pointing to our // texturecache info, we can free it - if (gr_textures) - free(gr_textures); - gr_textures = NULL; - gr_numtextures = 0; + if (gl_textures) + free(gl_textures); + gl_textures = NULL; + gl_numtextures = 0; } void HWR_LoadTextures(size_t pnumtextures) @@ -537,13 +543,13 @@ void HWR_LoadTextures(size_t pnumtextures) // we must free it since numtextures changed HWR_FreeTextureCache(); - gr_numtextures = pnumtextures; + gl_numtextures = pnumtextures; #ifdef GLENCORE - gr_textures = calloc(pnumtextures, sizeof (*gr_textures)*2); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore) + gl_textures = calloc(pnumtextures, sizeof (*gl_textures)*2); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore) #else - gr_textures = calloc(pnumtextures, sizeof (*gr_textures)); + gl_textures = calloc(pnumtextures, sizeof (*gl_textures)); #endif - if (gr_textures == NULL) + if (gl_textures == NULL) I_Error("HWR_LoadTextures: ran out of memory for OpenGL textures. Sad!"); } @@ -552,9 +558,9 @@ void HWR_LoadTextures(size_t pnumtextures) // -------------------------------------------------------------------------- GLMapTexture_t *HWR_GetTexture(INT32 tex, boolean noencore) { - GLMapTexture_t *grtex; + GLMapTexture_t *gltex; - if (tex < 0 || tex >= (signed)gr_numtextures) + if (tex < 0 || tex >= (signed)gl_numtextures) { #ifdef PARANOIA I_Error("HWR_GetTexture: Invalid texture ID %d", tex); @@ -563,25 +569,25 @@ GLMapTexture_t *HWR_GetTexture(INT32 tex, boolean noencore) #endif } #ifdef GLENCORE - grtex = &gr_textures[tex*2 + (encoremap && !noencore ? 0 : 1)]; + gltex = &gl_textures[tex*2 + (encoremap && !noencore ? 0 : 1)]; #else - grtex = &gr_textures[tex]; + gltex = &gl_textures[tex]; #endif - if (!grtex->mipmap.data && !grtex->mipmap.downloaded) - HWR_GenerateTexture(tex, grtex, noencore); + if (!gltex->mipmap.data && !gltex->mipmap.downloaded) + HWR_GenerateTexture(tex, gltex, noencore); // If hardware does not have the texture, then call pfnSetTexture to upload it - if (!grtex->mipmap.downloaded) - HWD.pfnSetTexture(&grtex->mipmap); - HWR_SetCurrentTexture(&grtex->mipmap); + if (!gltex->mipmap.downloaded) + GL_SetTexture(&gltex->mipmap); + HWR_SetCurrentTexture(&gltex->mipmap); // The system-memory data can be purged now. - Z_ChangeTag(grtex->mipmap.data, PU_HWRCACHE_UNLOCKED); + Z_ChangeTag(gltex->mipmap.data, PU_HWRCACHE_UNLOCKED); - return grtex; + return gltex; } -static void HWR_CacheFlat(GLMipmap_t *grMipmap, lumpnum_t flatlumpnum) +static void HWR_CacheFlat(GLMipmap_t *glMipmap, lumpnum_t flatlumpnum) { #ifdef GLENCORE UINT8 *flat; @@ -590,8 +596,8 @@ static void HWR_CacheFlat(GLMipmap_t *grMipmap, lumpnum_t flatlumpnum) size_t size, pflatsize; // setup the texture info - grMipmap->format = GL_TEXFMT_P_8; - grMipmap->flags = TF_WRAPXY|TF_CHROMAKEYED; + glMipmap->format = GL_TEXFMT_P_8; + glMipmap->flags = TF_WRAPXY|TF_CHROMAKEYED; size = W_LumpLength(flatlumpnum); @@ -619,21 +625,21 @@ static void HWR_CacheFlat(GLMipmap_t *grMipmap, lumpnum_t flatlumpnum) pflatsize = 64; break; } - grMipmap->width = (UINT16)pflatsize; - grMipmap->height = (UINT16)pflatsize; + glMipmap->width = (UINT16)pflatsize; + glMipmap->height = (UINT16)pflatsize; // the flat raw data needn't be converted with palettized textures W_ReadLump(flatlumpnum, Z_Malloc(W_LumpLength(flatlumpnum), - PU_HWRCACHE, &grMipmap->data)); + PU_HWRCACHE, &glMipmap->data)); #ifdef GLENCORE - flat = grMipmap->data; + flat = glMipmap->data; for (steppy = 0; steppy < size; steppy++) { if (flat[steppy] == HWR_PATCHES_CHROMAKEY_COLORINDEX) continue; - flat[steppy] = grMipmap->colormap[flat[steppy]]; + flat[steppy] = glMipmap->colormap[flat[steppy]]; } #endif } @@ -641,117 +647,117 @@ static void HWR_CacheFlat(GLMipmap_t *grMipmap, lumpnum_t flatlumpnum) // Download a Doom 'flat' to the hardware cache and make it ready for use void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap) { - GLMipmap_t *grmip; - + GLMipmap_t *glMipmap; + if (flatlumpnum == LUMPERROR) return; - grmip = HWR_GetCachedGLPatch(flatlumpnum)->mipmap; + glMipmap = HWR_GetCachedGLPatch(flatlumpnum)->mipmap; - grmip->colormap = colormaps; + glMipmap->colormap = colormaps; #ifdef GLENCORE if (!noencoremap && encoremap) - grmip->colormap += COLORMAP_REMAPOFFSET; + glMipmap->colormap += COLORMAP_REMAPOFFSET; #endif - if (!grmip->downloaded && !grmip->data) - HWR_CacheFlat(grmip, flatlumpnum); + if (!glMipmap->downloaded && !glMipmap->data) + HWR_CacheFlat(glMipmap, flatlumpnum); // If hardware does not have the texture, then call pfnSetTexture to upload it - if (!grmip->downloaded) - HWD.pfnSetTexture(grmip); - HWR_SetCurrentTexture(grmip); + if (!glMipmap->downloaded) + GL_SetTexture(glMipmap); + HWR_SetCurrentTexture(glMipmap); // The system-memory data can be purged now. - Z_ChangeTag(grmip->data, PU_HWRCACHE_UNLOCKED); + Z_ChangeTag(glMipmap->data, PU_HWRCACHE_UNLOCKED); } // // HWR_LoadMappedPatch(): replace the skin color of the sprite in cache // : load it first in doom cache if not already // -static void HWR_LoadMappedPatch(GLMipmap_t *grmip, GLPatch_t *gpatch) +static void HWR_LoadMappedPatch(GLMipmap_t *glMipmap, GLPatch_t *glPatch) { - if (!grmip->downloaded && !grmip->data) + if (!glMipmap->downloaded && !glMipmap->data) { - patch_t *patch = gpatch->rawpatch; + patch_t *patch = glPatch->rawpatch; if (!patch) - patch = W_CacheLumpNumPwad(gpatch->wadnum, gpatch->lumpnum, PU_STATIC); - HWR_MakePatch(patch, gpatch, grmip, true); + patch = W_CacheLumpNumPwad(glPatch->wadnum, glPatch->lumpnum, PU_STATIC); + HWR_MakePatch(patch, glPatch, glMipmap, true); // You can't free rawpatch for some reason? // (Obviously I can't, sprite rotation needs that...) - if (!gpatch->rawpatch) + if (!glPatch->rawpatch) Z_Free(patch); } // If hardware does not have the texture, then call pfnSetTexture to upload it - if (!grmip->downloaded) - HWD.pfnSetTexture(grmip); - HWR_SetCurrentTexture(grmip); + if (!glMipmap->downloaded) + GL_SetTexture(glMipmap); + HWR_SetCurrentTexture(glMipmap); // The system-memory data can be purged now. - Z_ChangeTag(grmip->data, PU_HWRCACHE_UNLOCKED); + Z_ChangeTag(glMipmap->data, PU_HWRCACHE_UNLOCKED); } // -----------------+ -// HWR_GetPatch : Download a patch to the hardware cache and make it ready for use +// HWR_GetPatch : Downloads a patch to the hardware cache and make it ready for use // -----------------+ -void HWR_GetPatch(GLPatch_t *gpatch) +void HWR_GetPatch(GLPatch_t *glPatch) { // is it in hardware cache - if (!gpatch->mipmap->downloaded && !gpatch->mipmap->data) + if (!glPatch->mipmap->downloaded && !glPatch->mipmap->data) { // load the software patch, PU_STATIC or the Z_Malloc for hardware patch will // flush the software patch before the conversion! oh yeah I suffered - patch_t *ptr = gpatch->rawpatch; + patch_t *ptr = glPatch->rawpatch; if (!ptr) - ptr = W_CacheLumpNumPwad(gpatch->wadnum, gpatch->lumpnum, PU_STATIC); - HWR_MakePatch(ptr, gpatch, gpatch->mipmap, true); + ptr = W_CacheLumpNumPwad(glPatch->wadnum, glPatch->lumpnum, PU_STATIC); + HWR_MakePatch(ptr, glPatch, glPatch->mipmap, true); // this is inefficient.. but the hardware patch in heap is purgeable so it should // not fragment memory, and besides the REAL cache here is the hardware memory - if (!gpatch->rawpatch) + if (!glPatch->rawpatch) Z_Free(ptr); } // If hardware does not have the texture, then call pfnSetTexture to upload it - if (!gpatch->mipmap->downloaded) - HWD.pfnSetTexture(gpatch->mipmap); - HWR_SetCurrentTexture(gpatch->mipmap); + if (!glPatch->mipmap->downloaded) + GL_SetTexture(glPatch->mipmap); + HWR_SetCurrentTexture(glPatch->mipmap); // The system-memory patch data can be purged now. - Z_ChangeTag(gpatch->mipmap->data, PU_HWRCACHE_UNLOCKED); + Z_ChangeTag(glPatch->mipmap->data, PU_HWRCACHE_UNLOCKED); } // -------------------+ // HWR_GetMappedPatch : Same as HWR_GetPatch for sprite color // -------------------+ -void HWR_GetMappedPatch(GLPatch_t *gpatch, const UINT8 *colormap) +void HWR_GetMappedPatch(GLPatch_t *glPatch, const UINT8 *colormap) { - GLMipmap_t *grmip, *newmip; + GLMipmap_t *glMipmap, *newMipmap; // Blatant hack for encore colormapping aside... if (colormap == colormaps || colormap == NULL || colormap == (const UINT8*)(COLORMAP_REMAPOFFSET)) { // Load the default (green) color in doom cache (temporary?) AND hardware cache - HWR_GetPatch(gpatch); + HWR_GetPatch(glPatch); return; } - // search for the mimmap + // search for the mipmap // skip the first (no colormap translated) - for (grmip = gpatch->mipmap; grmip->nextcolormap; ) + for (glMipmap = glPatch->mipmap; glMipmap->nextcolormap; ) { - grmip = grmip->nextcolormap; + glMipmap = glMipmap->nextcolormap; - if (grmip->colormap != colormap) + if (glMipmap->colormap != colormap) continue; - HWR_LoadMappedPatch(grmip, gpatch); + HWR_LoadMappedPatch(glMipmap, glPatch); return; } // not found, create it! @@ -761,38 +767,38 @@ void HWR_GetMappedPatch(GLPatch_t *gpatch, const UINT8 *colormap) // (it have a liste of mipmap) // this malloc is cleared in HWR_FreeTextureCache // (...) unfortunately z_malloc fragment alot the memory :(so malloc is better - newmip = calloc(1, sizeof (*newmip)); - if (newmip == NULL) + newMipmap = calloc(1, sizeof (*newMipmap)); + if (newMipmap == NULL) I_Error("%s: Out of memory", "HWR_GetMappedPatch"); - grmip->nextcolormap = newmip; + glMipmap->nextcolormap = newMipmap; - newmip->colormap = colormap; - HWR_LoadMappedPatch(newmip, gpatch); + newMipmap->colormap = colormap; + HWR_LoadMappedPatch(newMipmap, glPatch); } -void HWR_UnlockCachedPatch(GLPatch_t *gpatch) +void HWR_UnlockCachedPatch(GLPatch_t *glPatch) { - if (!gpatch) + if (!glPatch) return; - Z_ChangeTag(gpatch->mipmap->data, PU_HWRCACHE_UNLOCKED); + Z_ChangeTag(glPatch->mipmap->data, PU_HWRCACHE_UNLOCKED); } GLPatch_t *HWR_GetCachedGLPatchPwad(UINT16 wadnum, UINT16 lumpnum) { aatree_t *hwrcache = wadfiles[wadnum]->hwrcache; - GLPatch_t *grpatch; + GLPatch_t *glPatch; - if (!(grpatch = M_AATreeGet(hwrcache, lumpnum))) + if (!(glPatch = M_AATreeGet(hwrcache, lumpnum))) { - grpatch = Z_Calloc(sizeof(GLPatch_t), PU_HWRPATCHINFO, NULL); - grpatch->wadnum = wadnum; - grpatch->lumpnum = lumpnum; - grpatch->mipmap = Z_Calloc(sizeof(GLMipmap_t), PU_HWRPATCHINFO, NULL); - M_AATreeSet(hwrcache, lumpnum, grpatch); + glPatch = Z_Calloc(sizeof(GLPatch_t), PU_HWRPATCHINFO, NULL); + glPatch->wadnum = wadnum; + glPatch->lumpnum = lumpnum; + glPatch->mipmap = Z_Calloc(sizeof(GLMipmap_t), PU_HWRPATCHINFO, NULL); + M_AATreeSet(hwrcache, lumpnum, glPatch); } - return grpatch; + return glPatch; } GLPatch_t *HWR_GetCachedGLPatch(lumpnum_t lumpnum) @@ -840,14 +846,14 @@ static void HWR_DrawFadeMaskInCache(GLMipmap_t *mipmap, INT32 pblockwidth, INT32 Z_Free(flat); } -static void HWR_CacheFadeMask(GLMipmap_t *grMipmap, lumpnum_t fademasklumpnum) +static void HWR_CacheFadeMask(GLMipmap_t *glMipmap, lumpnum_t fademasklumpnum) { size_t size; UINT16 fmheight = 0, fmwidth = 0; // setup the texture info - grMipmap->format = GL_TEXFMT_ALPHA_8; // put the correct alpha levels straight in so I don't need to convert it later - grMipmap->flags = 0; + glMipmap->format = GL_TEXFMT_ALPHA_8; // put the correct alpha levels straight in so I don't need to convert it later + glMipmap->flags = 0; size = W_LumpLength(fademasklumpnum); @@ -876,28 +882,28 @@ static void HWR_CacheFadeMask(GLMipmap_t *grMipmap, lumpnum_t fademasklumpnum) } // Thankfully, this will still work for this scenario - grMipmap->width = fmwidth; - grMipmap->height = fmheight; + glMipmap->width = fmwidth; + glMipmap->height = fmheight; - MakeBlock(grMipmap); + MakeBlock(glMipmap); - HWR_DrawFadeMaskInCache(grMipmap, fmwidth, fmheight, fademasklumpnum, fmwidth, fmheight); + HWR_DrawFadeMaskInCache(glMipmap, fmwidth, fmheight, fademasklumpnum, fmwidth, fmheight); // I DO need to convert this because it isn't power of 2 and we need the alpha } void HWR_GetFadeMask(lumpnum_t fademasklumpnum) { - GLMipmap_t *grmip; + GLMipmap_t *glMipmap; - grmip = HWR_GetCachedGLPatch(fademasklumpnum)->mipmap; + glMipmap = HWR_GetCachedGLPatch(fademasklumpnum)->mipmap; - if (!grmip->downloaded && !grmip->data) - HWR_CacheFadeMask(grmip, fademasklumpnum); + if (!glMipmap->downloaded && !glMipmap->data) + HWR_CacheFadeMask(glMipmap, fademasklumpnum); - HWD.pfnSetTexture(grmip); + GL_SetTexture(glMipmap); // The system-memory data can be purged now. - Z_ChangeTag(grmip->data, PU_HWRCACHE_UNLOCKED); + Z_ChangeTag(glMipmap->data, PU_HWRCACHE_UNLOCKED); } // ================================================= @@ -909,15 +915,15 @@ void HWR_SetPalette(RGBA_t *palette) if (HWR_ShouldUsePaletteRendering()) { // set the palette for palette postprocessing - if (cv_grpalettedepth.value == 16) + if (cv_glpalettedepth.value == 16) { // crush to 16-bit rgb565, like software currently does in the standard configuration // Note: Software's screenshots have the 24-bit palette, but the screen gets // the 16-bit version! For making comparison screenshots either use an external screenshot // tool or set the palette depth to 24 bits. RGBA_t crushed_palette[256]; - int i; - for (i = 0; i < 256; i++) + + for (int i = 0; i < 256; i++) { float fred = (float)(palette[i].s.red >> 3); float fgreen = (float)(palette[i].s.green >> 2); @@ -927,21 +933,21 @@ void HWR_SetPalette(RGBA_t *palette) crushed_palette[i].s.blue = (UINT8)(fblue / 31.0f * 255.0f); crushed_palette[i].s.alpha = 255; } - HWD.pfnSetScreenPalette(crushed_palette); + GL_SetScreenPalette(crushed_palette); } else { - HWD.pfnSetScreenPalette(palette); + GL_SetScreenPalette(palette); } // this part is responsible for keeping track of the palette OUTSIDE of a level. - if ((!(gamestate == GS_LEVEL)) || (gamestate == GS_TITLESCREEN)) + if (gamestate != GS_LEVEL || gamestate == GS_TITLESCREEN) HWR_SetMapPalette(); } else { // set the palette for the textures - HWD.pfnSetTexturePalette(palette); + GL_SetPalette(palette); // reset mapPalette so next call to HWR_SetMapPalette will update everything correctly memset(mapPalette, 0, sizeof(mapPalette)); // hardware driver will flush there own cache if cache is non paletized @@ -974,7 +980,7 @@ static void HWR_SetPaletteLookup(RGBA_t *palette) } } #undef STEP_SIZE - HWD.pfnSetPaletteLookup(lut); + GL_SetPaletteLookup(lut); Z_Free(lut); } @@ -987,11 +993,9 @@ void HWR_SetMapPalette(void) RGBA_t *palette; int i; - if ((!(gamestate == GS_LEVEL)) || (gamestate == GS_TITLESCREEN)) + if (gamestate != GS_LEVEL || gamestate == GS_TITLESCREEN) { - // outside of a level, pMasterPalette should have PLAYPAL ready for us - //palette = pMasterPalette; // we dont have this in kart so just use pLocalPalette as before - + // outside of a level, pLocalPalette should have PLAYPAL ready for us palette = pLocalPalette; } else @@ -1001,8 +1005,10 @@ void HWR_SetMapPalette(void) lumpnum_t lumpnum = W_GetNumForName(GetPalette()); size_t palsize = W_LumpLength(lumpnum); UINT8 *RGB_data; + if (palsize < 768) // 256 * 3 I_Error("HWR_SetMapPalette: A programmer assumed palette lumps are at least 768 bytes long, but apparently this was a wrong assumption!\n"); + RGB_data = W_CacheLumpNum(lumpnum, PU_CACHE); // we got the RGB palette now, but we need it in RGBA format. for (i = 0; i < 256; i++) @@ -1022,7 +1028,7 @@ void HWR_SetMapPalette(void) // in palette rendering mode, this means that all rgba textures now have wrong colors // and the lookup table is outdated HWR_SetPaletteLookup(mapPalette); - HWD.pfnSetTexturePalette(mapPalette); + GL_SetPalette(mapPalette); if (patchformat == GL_TEXFMT_RGBA || textureformat == GL_TEXFMT_RGBA) { @@ -1045,12 +1051,11 @@ UINT32 HWR_CreateLightTable(UINT8 *lighttable) for (i = 0; i < 256 * 32; i++) hw_lighttable[i] = palette[lighttable[i]]; - id = HWD.pfnCreateLightTable(hw_lighttable); + id = GL_CreateLightTable(hw_lighttable); Z_Free(hw_lighttable); return id; } - // get hwr lighttable id for colormap, create it if it doesn't already exist UINT32 HWR_GetLightTableID(extracolormap_t *colormap) { @@ -1082,7 +1087,7 @@ UINT32 HWR_GetLightTableID(extracolormap_t *colormap) void HWR_ClearLightTables(void) { if (vid.glstate == VID_GL_LIBRARY_LOADED) - HWD.pfnClearLightTables(); + GL_ClearLightTables(); } #endif //HWRENDER diff --git a/src/hardware/hw_clip.c b/src/hardware/hw_clip.c index 2c6e1d52e..e9b1bce98 100644 --- a/src/hardware/hw_clip.c +++ b/src/hardware/hw_clip.c @@ -333,11 +333,11 @@ angle_t gld_FrustumAngle(angle_t tiltangle) // ok, this is a gross hack that barely works... // but at least it doesn't overestimate too much... - clipfov = atan(1 / projMatrix[0]) * 360 / M_PI; + clipfov = atan(1 / projMatrix[0]) * 360 / M_PIl; floatangle = 2.0f + (45.0f + (tilt / 1.9f)) * clipfov / 90.0f; if (floatangle >= 180.0) return 0xffffffff; - a1 = (angle_t)(ANG1 * (int)floatangle); + a1 = (angle_t)xs_CRoundToInt(ANG1 * floatangle); return a1; } @@ -458,4 +458,4 @@ boolean gld_SphereInFrustum(float x, float y, float z, float radius) } return true; } -#endif \ No newline at end of file +#endif diff --git a/src/hardware/hw_data.h b/src/hardware/hw_data.h index b149493c5..1f16ebf2a 100644 --- a/src/hardware/hw_data.h +++ b/src/hardware/hw_data.h @@ -33,16 +33,18 @@ typedef enum GLTextureFormat_e GL_TEXFMT_ALPHA_INTENSITY_88 = 0x22, } GLTextureFormat_t; -// data holds the address of the graphics data cached in heap memory -// NULL if the texture is not in Doom heap cache. +// Texture information (misleadingly named "mipmap" all over the code.) +// The *data pointer holds the address of the graphics data cached in heap memory. +// NULL if the texture is not in SRB2's heap cache. struct GLMipmap_s { + // for UpdateTexture GLTextureFormat_t format; void *data; UINT32 flags; UINT16 width, height; - UINT32 downloaded; // tex_downloaded + UINT32 downloaded; // The GPU has this texture. struct GLMipmap_s *nextcolormap; const UINT8 *colormap; @@ -50,12 +52,12 @@ struct GLMipmap_s typedef struct GLMipmap_s GLMipmap_t; // -// Doom texture info, as cached for hardware rendering +// Level textures, as cached for hardware rendering. // struct GLMapTexture_s { GLMipmap_t mipmap; - float scaleX; //used for scaling textures on walls + float scaleX; //used for scaling textures on walls float scaleY; }; typedef struct GLMapTexture_s GLMapTexture_t; diff --git a/src/hardware/hw_defs.h b/src/hardware/hw_defs.h index dc8d44ca8..91146f228 100644 --- a/src/hardware/hw_defs.h +++ b/src/hardware/hw_defs.h @@ -121,8 +121,6 @@ typedef struct poly_t *planepoly; // the generated convex polygon } extrasubsector_t; -//here lies gr_vissprite - // Kart features #define USE_FTRANSFORM_ANGLEZ #define USE_FTRANSFORM_MIRROR @@ -134,14 +132,14 @@ typedef struct { FLOAT x,y,z; // position #ifdef USE_FTRANSFORM_ANGLEZ - FLOAT anglex,angley,anglez; // aimingangle / viewangle - FLOAT anglex2,anglez2; // secondaries + FLOAT anglex, angley, anglez; // aimingangle / viewangle + FLOAT anglex2, anglez2; // secondaries #else - FLOAT anglex,angley; // aimingangle / viewangle + FLOAT anglex, angley; // aimingangle / viewangle FLOAT anglex2; // secondaries #endif - FLOAT scalex,scaley,scalez; - FLOAT spritexscale,spriteyscale; + FLOAT scalex, scaley, scalez; + FLOAT spritexscale, spriteyscale; FLOAT fovxangle, fovyangle; UINT8 splitscreen; boolean flip; // screenflip @@ -166,6 +164,41 @@ typedef struct FLOAT s,t; } FOutVector; +typedef struct vbo_vertex_s +{ + float x, y, z; + float u, v; + unsigned char r, g, b, a; +} gl_skyvertex_t; + +typedef enum gl_skyloopmode_e +{ + HWD_SKYLOOP_FAN, + HWD_SKYLOOP_STRIP +} gl_skyloopmode_t; + +typedef struct +{ + gl_skyloopmode_t mode; + int vertexcount; + int vertexindex; + boolean use_texture; +} gl_skyloopdef_t; + +typedef struct +{ + unsigned int vbo; + int rows, columns; + int loopcount; + + int detail, vertex_count; + int texture, width, height; + boolean rebuild; // VBO needs to be rebuilt + + gl_skyloopdef_t *loops; + gl_skyvertex_t *data; +} gl_sky_t; + // Shader targets used to render specific types of geometry. // A shader target is resolved to an actual shader with HWR_GetShaderFromTarget. // The shader returned may be a base shader or a custom shader. @@ -173,7 +206,6 @@ enum { SHADER_NONE = -1, SHADER_FLOOR = 0, - SHADER_SHADOW, SHADER_WALL, SHADER_SPRITE, SHADER_MODEL, @@ -204,7 +236,6 @@ enum hwdshaderstage typedef enum hwdshaderstage hwdshaderstage_t; - // ========================================================================== // RENDER MODES // ========================================================================== @@ -289,9 +320,6 @@ typedef struct FSurfaceInfo FSurfaceInfo; enum hwdsetspecialstate { -#ifdef USE_FBO_OGL - HWD_SET_FRAMEBUFFER, -#endif HWD_SET_SHADERS, HWD_SET_TEXTUREFILTERMODE, @@ -346,6 +374,7 @@ enum hwdscreentexture HWD_SCREENTEXTURE_WIPE_END, // destination image for the wipe/fade effect HWD_SCREENTEXTURE_GENERIC1, // underwater/heat effect, intermission background HWD_SCREENTEXTURE_GENERIC2, // palette-based colormap fade, final screen texture + HWD_SCREENTEXTURE_VHS, NUMSCREENTEXTURES, // (generic3 is unused if palette rendering is disabled) }; typedef enum hwdscreentexture hwdscreentexture_t; diff --git a/src/hardware/hw_draw.c b/src/hardware/hw_draw.c index ee0fd0b85..e38300309 100644 --- a/src/hardware/hw_draw.c +++ b/src/hardware/hw_draw.c @@ -18,9 +18,10 @@ #include "../doomdef.h" #ifdef HWRENDER + #include "hw_main.h" #include "hw_glob.h" -#include "hw_drv.h" +#include "hw_gl.h" #include "../m_misc.h" //FIL_WriteFile() #include "../r_draw.h" //viewborderlump @@ -122,7 +123,7 @@ void HWR_DrawPatch(GLPatch_t *gpatch, INT32 x, INT32 y, INT32 option) flags |= PF_ForceWrapY; // clip it since it is used for bunny scroll in doom I - HWD.pfnDrawPolygon(NULL, v, 4, flags); + GL_DrawPolygon(NULL, v, 4, flags); } void HWR_DrawStretchyFixedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, fixed_t vscale, INT32 option, const UINT8 *colormap) @@ -303,10 +304,10 @@ void HWR_DrawStretchyFixedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[hudtrans]; else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; flags |= PF_Modulated; - HWD.pfnDrawPolygon(&Surf, v, 4, flags); + GL_DrawPolygon(&Surf, v, 4, flags); } else - HWD.pfnDrawPolygon(NULL, v, 4, flags); + GL_DrawPolygon(NULL, v, 4, flags); } void HWR_DrawCroppedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, INT32 option, fixed_t sx, fixed_t sy, fixed_t w, fixed_t h) @@ -460,10 +461,10 @@ void HWR_DrawCroppedPatch(GLPatch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscal else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[cv_translucenthud.value]; else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; flags |= PF_Modulated; - HWD.pfnDrawPolygon(&Surf, v, 4, flags); + GL_DrawPolygon(&Surf, v, 4, flags); } else - HWD.pfnDrawPolygon(NULL, v, 4, flags); + GL_DrawPolygon(NULL, v, 4, flags); } // ========================================================================== @@ -539,7 +540,7 @@ void HWR_DrawFlatFill (INT32 x, INT32 y, INT32 w, INT32 h, lumpnum_t flatlumpnum // BTW, I see we put 0 for PFs, and If I'm right, that // means we take the previous PFs as default // how can we be sure they are ok? - HWD.pfnDrawPolygon(NULL, v, 4, PF_NoDepthTest); //PF_Translucent); + GL_DrawPolygon(NULL, v, 4, PF_NoDepthTest); //PF_Translucent); } @@ -552,33 +553,33 @@ void HWR_DrawFlatFill (INT32 x, INT32 y, INT32 w, INT32 h, lumpnum_t flatlumpnum // 0--1 void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) { - FOutVector v[4]; - FSurfaceInfo Surf; + FOutVector v[4]; + FSurfaceInfo Surf; FBITFIELD poly_flags = PF_NoTexture|PF_Modulated|PF_NoDepthTest; - v[0].x = v[3].x = -1.0f; - v[2].x = v[1].x = 1.0f; - v[0].y = v[1].y = -1.0f; - v[2].y = v[3].y = 1.0f; - v[0].z = v[1].z = v[2].z = v[3].z = 1.0f; + v[0].x = v[3].x = -1.0f; + v[2].x = v[1].x = 1.0f; + v[0].y = v[1].y = -1.0f; + v[2].y = v[3].y = 1.0f; + v[0].z = v[1].z = v[2].z = v[3].z = 1.0f; - v[0].s = v[3].s = 0.0f; - v[2].s = v[1].s = 1.0f; - v[0].t = v[1].t = 1.0f; - v[2].t = v[3].t = 0.0f; + v[0].s = v[3].s = 0.0f; + v[2].s = v[1].s = 1.0f; + v[0].t = v[1].t = 1.0f; + v[2].t = v[3].t = 0.0f; - if (color & 0xFF00) // Do COLORMAP fade. - { - if (HWR_ShouldUsePaletteRendering() && cv_grscreentextures.value) + if (color & 0xFF00) // Do COLORMAP fade. + { + if (HWR_ShouldUsePaletteRendering() && cv_glscreentextures.value) { const hwdscreentexture_t scr_tex = HWD_SCREENTEXTURE_GENERIC2; Surf.LightTableId = HWR_GetLightTableID(NULL); Surf.LightInfo.light_level = strength; - HWD.pfnMakeScreenTexture(scr_tex); - HWD.pfnSetShader(HWR_GetShaderFromTarget(SHADER_UI_COLORMAP_FADE)); - HWD.pfnDrawScreenTexture(scr_tex, &Surf, PF_ColorMapped|PF_NoDepthTest); - HWD.pfnUnSetShader(); + GL_MakeScreenTexture(scr_tex); + GL_SetShader(HWR_GetShaderFromTarget(SHADER_UI_COLORMAP_FADE)); + GL_DrawScreenTexture(scr_tex, &Surf, PF_ColorMapped|PF_NoDepthTest); + GL_UnSetShader(); return; } @@ -588,21 +589,21 @@ void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) Surf.PolyColor.s.alpha = (strength*8); poly_flags |= PF_Translucent; } - } - else // Do TRANSMAP** fade. - { + } + else // Do TRANSMAP** fade. + { RGBA_t *palette = HWR_GetTexturePalette(); Surf.PolyColor.rgba = palette[color&0xFF].rgba; - + if (HWR_ShouldUsePaletteRendering()) Surf.PolyColor.s.alpha = softwaretranstogl[strength]; else Surf.PolyColor.s.alpha = (UINT8)(strength*25.5f); - - poly_flags |= PF_Translucent; - } - HWD.pfnDrawPolygon(&Surf, v, 4, poly_flags); + poly_flags |= PF_Translucent; + } + + GL_DrawPolygon(&Surf, v, 4, poly_flags); } // Draw the console background with translucency support @@ -629,7 +630,7 @@ void HWR_DrawConsoleBack(UINT32 color, INT32 height) Surf.PolyColor.rgba = UINT2RGBA(color); Surf.PolyColor.s.alpha = 0x80; - HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); + GL_DrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); } @@ -652,17 +653,17 @@ void HWR_DrawViewBorder(INT32 clearlines) INT32 basewindowx, basewindowy; GLPatch_t *patch; -// if (gr_viewwidth == vid.width) +// if (gl_viewwidth == vid.width) // return; if (!clearlines) clearlines = BASEVIDHEIGHT; // refresh all // calc view size based on original game resolution - baseviewwidth = FixedInt(FixedDiv(FLOAT_TO_FIXED(gr_viewwidth), vid.fdupx)); //(cv_viewsize.value * BASEVIDWIDTH/10)&~7; - baseviewheight = FixedInt(FixedDiv(FLOAT_TO_FIXED(gr_viewheight), vid.fdupy)); - top = FixedInt(FixedDiv(FLOAT_TO_FIXED(gr_baseviewwindowy), vid.fdupy)); - side = FixedInt(FixedDiv(FLOAT_TO_FIXED(gr_baseviewwindowx), vid.fdupx)); + baseviewwidth = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_viewwidth), vid.fdupx)); //(cv_viewsize.value * BASEVIDWIDTH/10)&~7; + baseviewheight = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_viewheight), vid.fdupy)); + top = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_baseviewwindowy), vid.fdupy)); + side = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_baseviewwindowx), vid.fdupx)); // top HWR_DrawFlatFill(0, 0, @@ -776,16 +777,16 @@ void HWR_drawAMline(const fline_t *fl, INT32 color) F2DCoord v1, v2; RGBA_t color_rgba; RGBA_t *palette = HWR_GetTexturePalette(); - + color_rgba = palette[color&0xFF]; - + v1.x = ((float)fl->a.x-(vid.width/2.0f))*(2.0f/vid.width); v1.y = ((float)fl->a.y-(vid.height/2.0f))*(2.0f/vid.height); v2.x = ((float)fl->b.x-(vid.width/2.0f))*(2.0f/vid.width); v2.y = ((float)fl->b.y-(vid.height/2.0f))*(2.0f/vid.height); - HWD.pfnDraw2DLine(&v1, &v2, color_rgba); + GL_Draw2DLine(&v1, &v2, color_rgba); } // -----------------+ @@ -879,7 +880,7 @@ void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color) Surf.PolyColor = palette[color&0xFF]; - HWD.pfnDrawPolygon(&Surf, v, 4, + GL_DrawPolygon(&Surf, v, 4, PF_Modulated|PF_NoTexture|PF_NoDepthTest); } @@ -918,7 +919,7 @@ void HWR_DrawConsoleFill(INT32 x, INT32 y, INT32 w, INT32 h, UINT32 color, INT32 clearColour.green = (float)rgbaColour.s.green / 255; clearColour.blue = (float)rgbaColour.s.blue / 255; clearColour.alpha = 1; - HWD.pfnClearBuffer(true, false, false, &clearColour); + GL_ClearBuffer(true, false, false, &clearColour); return; } @@ -989,7 +990,7 @@ void HWR_DrawConsoleFill(INT32 x, INT32 y, INT32 w, INT32 h, UINT32 color, INT32 Surf.PolyColor.rgba = UINT2RGBA(color); Surf.PolyColor.s.alpha = 0x80; - HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); + GL_DrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); } // -----------------+ @@ -1029,7 +1030,7 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) clearColour.green = (float)rgbaColour.s.green / 255; clearColour.blue = (float)rgbaColour.s.blue / 255; clearColour.alpha = 1; - HWD.pfnClearBuffer(true, false, false, &clearColour); + GL_ClearBuffer(true, false, false, &clearColour); return; } @@ -1107,7 +1108,7 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; } - HWD.pfnDrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); + GL_DrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest); } #ifdef HAVE_PNG @@ -1191,7 +1192,7 @@ UINT8 *HWR_GetScreenshot(void) return NULL; // returns 24bit 888 RGB - HWD.pfnReadScreenTexture(HWD_SCREENTEXTURE_GENERIC2, (void *)buf); + GL_ReadScreenTexture(HWD_SCREENTEXTURE_GENERIC2, (void *)buf); return buf; } @@ -1207,7 +1208,7 @@ boolean HWR_Screenshot(const char *pathname) } // returns 24bit 888 RGB - HWD.pfnReadScreenTexture(HWD_SCREENTEXTURE_GENERIC2, (void *)buf); + GL_ReadScreenTexture(HWD_SCREENTEXTURE_GENERIC2, (void *)buf); #ifdef USE_PNG ret = M_SavePNG(pathname, buf, vid.width, vid.height, NULL); diff --git a/src/hardware/hw_drv.h b/src/hardware/hw_drv.h deleted file mode 100644 index 8376ab405..000000000 --- a/src/hardware/hw_drv.h +++ /dev/null @@ -1,142 +0,0 @@ -// SONIC ROBO BLAST 2 -//----------------------------------------------------------------------------- -// Copyright (C) 1993-1996 by id Software, Inc. -// Copyright (C) 1998-2000 by DooM Legacy Team. -// Copyright (C) 1999-2019 by Sonic Team Junior. -// -// This program is free software distributed under the -// terms of the GNU General Public License, version 2. -// See the 'LICENSE' file for more details. -//----------------------------------------------------------------------------- -/// \file -/// \brief imports/exports for the GPU hardware low-level interface API - -#ifndef __HWR_DRV_H__ -#define __HWR_DRV_H__ - -// this must be here 19991024 by Kin -#include "../screen.h" -#include "hw_data.h" -#include "hw_defs.h" -#include "hw_md2.h" - -#include "hw_dll.h" -#include "../doomdef.h" - -// ========================================================================== -// STANDARD DLL EXPORTS -// ========================================================================== - -EXPORT boolean HWRAPI(Init) (void); -EXPORT void HWRAPI(SetupGLInfo) (void); -EXPORT void HWRAPI(SetTexturePalette) (RGBA_t *ppal); -EXPORT void HWRAPI(FinishUpdate) (INT32 waitvbl); -EXPORT void HWRAPI(Draw2DLine) (F2DCoord *v1, F2DCoord *v2, RGBA_t Color); -EXPORT void HWRAPI(DrawPolygon) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags); -EXPORT void HWRAPI(DrawIndexedTriangles) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, unsigned int *IndexArray); -EXPORT void HWRAPI(SetBlend) (FBITFIELD PolyFlags); -EXPORT void HWRAPI(ClearBuffer) (FBOOLEAN ColorMask, FBOOLEAN DepthMask, FBOOLEAN StencilMask, FRGBAFloat *ClearColor); -EXPORT void HWRAPI(SetTexture) (GLMipmap_t *TexInfo); -EXPORT void HWRAPI(UpdateTexture) (GLMipmap_t *TexInfo); -EXPORT void HWRAPI(DeleteTexture) (GLMipmap_t *TexInfo); -EXPORT void HWRAPI(ReadScreenTexture) (int tex, UINT16 *dst_data); -EXPORT void HWRAPI(GClipRect) (INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, float nearclip, float farclip); -EXPORT void HWRAPI(ClearMipMapCache) (void); - -//Hurdler: added for backward compatibility -EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value); - -//Hurdler: added for new development - -EXPORT void HWRAPI(DrawModel) (model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface); - -EXPORT void HWRAPI(CreateModelVBOs) (model_t *model); -EXPORT void HWRAPI(SetTransform) (FTransform *stransform); -EXPORT INT32 HWRAPI(GetTextureUsed) (void); - -EXPORT void HWRAPI(RenderSkyDome) (INT32 tex, INT32 texture_width, INT32 texture_height, FTransform transform); - -EXPORT void HWRAPI(FlushScreenTextures) (void); -EXPORT void HWRAPI(DoScreenWipe) (int wipeStart, int wipeEnd); -EXPORT void HWRAPI(DrawScreenTexture) (int tex, FSurfaceInfo *surf, FBITFIELD polyflags); -EXPORT void HWRAPI(MakeScreenTexture) (int tex); -EXPORT void HWRAPI(DrawScreenFinalTexture) (int tex, INT32 width, INT32 height); - -EXPORT void HWRAPI(RenderVhsEffect) (fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize); - -#define SCREENVERTS 10 -EXPORT void HWRAPI(PostImgRedraw) (float points[SCREENVERTS][SCREENVERTS][2]); - -// jimita -EXPORT boolean HWRAPI(InitShaders) (void); -EXPORT void HWRAPI(LoadShader) (int slot, char *code, hwdshaderstage_t stage); -EXPORT boolean HWRAPI(CompileShader) (int slot); -EXPORT void HWRAPI(SetShader) (int slot); -EXPORT void HWRAPI(UnSetShader) (void); - -EXPORT void HWRAPI(SetShaderInfo) (hwdshaderinfo_t info, INT32 value); - -EXPORT void HWRAPI(SetPaletteLookup)(UINT8 *lut); -EXPORT UINT32 HWRAPI(CreateLightTable)(RGBA_t *hw_lighttable); -EXPORT void HWRAPI(ClearLightTables)(void); -EXPORT void HWRAPI(SetScreenPalette)(RGBA_t *palette); - -// ========================================================================== -// HWR DRIVER OBJECT, FOR CLIENT PROGRAM -// ========================================================================== - -#if !defined (_CREATE_DLL_) - -struct hwdriver_s -{ - Init pfnInit; - SetupGLInfo pfnSetupGLInfo; - SetTexturePalette pfnSetTexturePalette; - FinishUpdate pfnFinishUpdate; - Draw2DLine pfnDraw2DLine; - DrawPolygon pfnDrawPolygon; - DrawIndexedTriangles pfnDrawIndexedTriangles; - SetBlend pfnSetBlend; - ClearBuffer pfnClearBuffer; - SetTexture pfnSetTexture; - UpdateTexture pfnUpdateTexture; - DeleteTexture pfnDeleteTexture; - ReadScreenTexture pfnReadScreenTexture; - GClipRect pfnGClipRect; - ClearMipMapCache pfnClearMipMapCache; - SetSpecialState pfnSetSpecialState; - DrawModel pfnDrawModel; - CreateModelVBOs pfnCreateModelVBOs; - SetTransform pfnSetTransform; - GetTextureUsed pfnGetTextureUsed; - PostImgRedraw pfnPostImgRedraw; - FlushScreenTextures pfnFlushScreenTextures; - DoScreenWipe pfnDoScreenWipe; - DrawScreenTexture pfnDrawScreenTexture; - MakeScreenTexture pfnMakeScreenTexture; - RenderVhsEffect pfnRenderVhsEffect; - DrawScreenFinalTexture pfnDrawScreenFinalTexture; - - RenderSkyDome pfnRenderSkyDome; - - InitShaders pfnInitShaders; - LoadShader pfnLoadShader; - CompileShader pfnCompileShader; - SetShader pfnSetShader; - UnSetShader pfnUnSetShader; - - SetShaderInfo pfnSetShaderInfo; - - SetPaletteLookup pfnSetPaletteLookup; - CreateLightTable pfnCreateLightTable; - ClearLightTables pfnClearLightTables; - SetScreenPalette pfnSetScreenPalette; -}; - -extern struct hwdriver_s hwdriver; - -#define HWD hwdriver - -#endif //not defined _CREATE_DLL_ - -#endif //__HWR_DRV_H__ diff --git a/src/hardware/hw_gl.h b/src/hardware/hw_gl.h new file mode 100644 index 000000000..c2a88854f --- /dev/null +++ b/src/hardware/hw_gl.h @@ -0,0 +1,79 @@ +// SONIC ROBO BLAST 2 Kart +//----------------------------------------------------------------------------- +// Copyright (C) 2020 by Jaime "Lactozilla" Passos. +// Copyright (C) 2020 by Sonic Team Junior. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file hw_gl.h +/// \brief OpenGL low-level interface API + +#ifndef __HWR_GL_H__ +#define __HWR_GL_H__ + +#include "../screen.h" + +#include "hw_data.h" +#include "hw_defs.h" +#include "hw_md2.h" + +#define SCREENVERTS 10 + +boolean GL_Init(void); +void GL_FinishUpdate(INT32 waitvbl); +void SetupGLInfo(void); + +void GL_SetSpecialState(hwdspecialstate_t IdState, INT32 Value); +void GL_SetTransform(FTransform *stransform); +void GL_SetBlend(FBITFIELD PolyFlags); +void GL_SetPalette(RGBA_t *palette); +void GL_ClearBuffer(FBOOLEAN ColorMask, FBOOLEAN DepthMask, FBOOLEAN StencilMask, FRGBAFloat * ClearColor); + +void GL_DrawPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags); +void GL_DrawIndexedTriangles(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, unsigned int *IndexArray); +void GL_Draw2DLine(F2DCoord *v1, F2DCoord *v2, RGBA_t Color); + +void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface); +#define GL_DrawModel(model, frameIndex, duration, tics, nextFrameIndex, pos, hscale, vscale, flipped, hflipped, Surface) GL_DrawModelEx(model, frameIndex, duration, tics, nextFrameIndex, pos, hscale, vscale, flipped, hflipped, Surface) + +void GL_RenderSkyDome(gl_sky_t *sky); + +void GL_SetTexture(GLMipmap_t *pTexInfo); +void GL_DeleteTexture(GLMipmap_t *pTexInfo); + +void GL_Flush(void); +#define GL_ClearMipMapCache GL_Flush + +INT32 GL_GetTextureUsed(void); + +void GL_CreateModelVBOs(model_t *model); + +void GL_ReadScreenTexture(int tex, UINT16 *dst_data); +void GL_GClipRect(INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, float nearclip, float farclip); + +void GL_MakeScreenTexture(int tex); +void GL_FlushScreenTextures(void); + +void GL_DrawScreenTexture(int tex, FSurfaceInfo *surf, FBITFIELD polyflags); +void GL_DoScreenWipe(int wipeStart, int wipeEnd); +void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize); +void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean useshader); + +void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2]); + +boolean GL_InitShaders(void); +void GL_LoadShader(int slot, char *code, hwdshaderstage_t stage); +boolean GL_CompileShader(int slot); +void GL_SetShader(int slot); +void GL_UnSetShader(void); + +void GL_SetShaderInfo(hwdshaderinfo_t info, INT32 value); + +void GL_SetPaletteLookup(UINT8 *lut); +UINT32 GL_CreateLightTable(RGBA_t *hw_lighttable); +void GL_ClearLightTables(void); +void GL_SetScreenPalette(RGBA_t *palette); + +#endif // __HWR_GL_H__ diff --git a/src/hardware/hw_glob.h b/src/hardware/hw_glob.h index 4a8a5dd9c..fe346f4c9 100644 --- a/src/hardware/hw_glob.h +++ b/src/hardware/hw_glob.h @@ -23,7 +23,7 @@ // needed for sprite rendering // equivalent of the software renderer's vissprites -typedef struct gr_vissprite_s +typedef struct gl_vissprite_s { float x1, x2; float z1, z2; @@ -32,7 +32,6 @@ typedef struct gr_vissprite_s float scale; float spritexscale, spriteyscale; float spritexoffset, spriteyoffset; - UINT32 renderflags; GLPatch_t *gpatch; boolean flip; UINT8 translucency; //alpha level 0-255 @@ -42,7 +41,7 @@ typedef struct gr_vissprite_s //Hurdler: 25/04/2000: now support colormap in hardware mode UINT8 *colormap; INT32 dispoffset; // copy of info->dispoffset, affects ordering but not drawing -} gr_vissprite_t; +} gl_vissprite_t; // -------- // hw_bsp.c @@ -64,7 +63,7 @@ void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap); GLMapTexture_t *HWR_GetTexture(INT32 tex, boolean noencore); void HWR_GetPatch(GLPatch_t *gpatch); void HWR_GetMappedPatch(GLPatch_t *gpatch, const UINT8 *colormap); -void HWR_MakePatch(patch_t *patch, GLPatch_t *grPatch, GLMipmap_t *grMipmap, boolean makebitmap); +void HWR_MakePatch(patch_t *patch, GLPatch_t *glPatch, GLMipmap_t *glMipmap, boolean makebitmap); void HWR_UnlockCachedPatch(GLPatch_t *gpatch); void HWR_SetPalette(RGBA_t *palette); @@ -82,14 +81,6 @@ void HWR_GetFadeMask(lumpnum_t fademasklumpnum); extern INT32 patchformat; extern INT32 textureformat; -// -------- -// hw_main.c // originally hw_drawnodes.c from HWPortal branch -// -------- -void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, INT32 texnum, boolean noencore, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap); -void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, boolean fogplane, extracolormap_t *planecolormap); -void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, - INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, extracolormap_t *planecolormap); - // -------- // hw_shaders.c // -------- diff --git a/src/hardware/hw_main.c b/src/hardware/hw_main.c index 741e29814..5eefc9c7e 100644 --- a/src/hardware/hw_main.c +++ b/src/hardware/hw_main.c @@ -14,113 +14,85 @@ #include #include "../doomstat.h" - -#include "../qs22j.h" +#include "../doomdef.h" #ifdef HWRENDER + #include "hw_main.h" #include "hw_glob.h" -#include "hw_drv.h" +#include "hw_gl.h" #include "hw_batching.h" #include "hw_md2.h" #include "hw_clip.h" +#include "hw_portal.h" #include "r_opengl/r_opengl.h" -#include "../i_video.h" // for rendermode == render_glide -#include "../v_video.h" +#include "../d_clisrv.h" +#include "../g_game.h" +#include "../m_argv.h" // parm functions for msaa +#include "../m_cheat.h" +#include "../m_menu.h" // ogl menu updating + +#include "../r_bsp.h" // R_NoEncore +#include "../r_data.h" +#include "../r_fps.h" +#include "../r_local.h" +#include "../r_main.h" // cv_fov +#include "../r_patch.h" // a mystery as to what this is for +#include "../r_portal.h" +#ifdef WALLSPLATS +#include "../r_splats.h" +#endif +#include "../r_state.h" + +#include "../i_system.h" +#include "../i_video.h" #include "../p_local.h" #include "../p_setup.h" -#include "../r_fps.h" -#include "../r_state.h" -#include "../r_local.h" -#include "../r_data.h" -#include "../r_patch.h" // a mystery as to what this is for -#include "../r_bsp.h" // R_NoEncore -#include "../r_main.h" // cv_fov -#include "../d_clisrv.h" +#include "../p_slopes.h" +#include "../st_stuff.h" +#include "../v_video.h" #include "../w_wad.h" #include "../z_zone.h" -#include "../r_splats.h" -#include "../g_game.h" -#include "../st_stuff.h" -#include "../i_system.h" -#include "../m_cheat.h" -#include "../m_argv.h" // parm functions for msaa -#include "../p_slopes.h" + +#include "../qs22j.h" // fast qsort + +// ========================================================================== +// Globals +// ========================================================================== #define ABS(x) ((x) < 0 ? -(x) : (x)) - #define SOFTLIGHT(llevel) HWR_ShouldUsePaletteRendering() ? ((llevel) >> LIGHTSEGSHIFT) << LIGHTSEGSHIFT : (llevel) -// ========================================================================== -// the hardware driver object -// ========================================================================== -struct hwdriver_s hwdriver; - // false if shaders have not been initialized yet, or if shaders are not available -boolean gr_shadersavailable = false; +boolean gl_shadersavailable = false; // Whether the internal state is set to palette rendering or not. -static boolean gr_palette_rendering_state = false; +static boolean gl_palette_rendering_state = false; -// ========================================================================== -// Commands and console variables -// ========================================================================== +boolean gl_drawing_stencil = false; -static void HWR_RollTransform(FTransform *tr, angle_t roll); +static INT32 current_bsp_culling_distance = 0; -#ifdef USE_FBO_OGL -static void CV_grframebuffer_OnChange(void); -#endif -static void CV_filtermode_ONChange(void); -static void CV_anisotropic_ONChange(void); -static void CV_screentextures_ONChange(void); -static void CV_grshaders_OnChange(void); -static void CV_grpaletterendering_OnChange(void); -static void CV_grpalettedepth_OnChange(void); +// base values set at SetViewSize +float gl_baseviewwindowy, gl_baseviewwindowx; +static float gl_viewwindowy, gl_viewwindowx; // top left corner of view window +float gl_viewwidth, gl_viewheight; // viewport clipping boundaries (screen coords) -static void CV_grlightdithering_OnChange(void); +FTransform atransform; -static CV_PossibleValue_t grfakecontrast_cons_t[] = {{0, "Off"}, {1, "Standard"}, {2, "Smooth"}, {0, NULL}}; +// Float variants of viewx, viewy, viewz, etc. +static float gl_viewx, gl_viewy, gl_viewz; +float gl_viewsin, gl_viewcos; +static float gl_viewludsin, gl_viewludcos; +static angle_t gl_aimingangle; -static CV_PossibleValue_t grfiltermode_cons_t[]= {{HWD_SET_TEXTUREFILTER_POINTSAMPLED, "Nearest"}, - {HWD_SET_TEXTUREFILTER_BILINEAR, "Bilinear"}, {HWD_SET_TEXTUREFILTER_TRILINEAR, "Trilinear"}, - {HWD_SET_TEXTUREFILTER_MIXED1, "Linear_Nearest"}, - {HWD_SET_TEXTUREFILTER_MIXED2, "Nearest_Linear"}, - {HWD_SET_TEXTUREFILTER_MIXED3, "Nearest_Mipmap"}, - {0, NULL}}; -CV_PossibleValue_t granisotropicmode_cons_t[] = {{1, "MIN"}, {16, "MAX"}, {0, NULL}}; - -consvar_t cv_grfiltermode = {"gr_filtermode", "Nearest", CV_CALL|CV_SAVE, grfiltermode_cons_t, - CV_filtermode_ONChange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_granisotropicmode = {"gr_anisotropicmode", "1", CV_CALL|CV_SAVE, granisotropicmode_cons_t, - CV_anisotropic_ONChange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grsolvetjoin = {"gr_solvetjoin", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grbatching = {"gr_batching", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -#ifdef USE_FBO_OGL -consvar_t cv_grframebuffer = {"gr_framebuffer", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, CV_grframebuffer_OnChange, 0, NULL, NULL, 0, 0, NULL}; -#endif - -consvar_t cv_splitwallfix = {"splitwallfix", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -static CV_PossibleValue_t grrenderdistance_cons_t[] = { - {0, "Max"}, {1, "1024"}, {2, "2048"}, {3, "4096"}, {4, "6144"}, {5, "8192"}, - {6, "12288"}, {7, "16384"}, {0, NULL}}; -consvar_t cv_grrenderdistance = {"gr_renderdistance", "Max", CV_SAVE, grrenderdistance_cons_t, - NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grportals = {"gr_portals", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -CV_PossibleValue_t secbright_cons_t[] = {{0, "MIN"}, {255, "MAX"}, {0, NULL}}; -consvar_t cv_secbright = {"secbright", "0", CV_SAVE, secbright_cons_t, - NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grfovchange = {"gr_fovchange", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +seg_t *gl_curline; +side_t *gl_sidedef; +line_t *gl_linedef; +sector_t *gl_frontsector; +sector_t *gl_backsector; // values for the far clipping plane static float clipping_distances[] = {1024.0f, 2048.0f, 4096.0f, 6144.0f, 8192.0f, 12288.0f, 16384.0f}; @@ -129,157 +101,6 @@ static float clipping_distances[] = {1024.0f, 2048.0f, 4096.0f, 6144.0f, 8192.0f static INT32 bsp_culling_distances[] = {(1024+512)*FRACUNIT, (2048+512)*FRACUNIT, (4096+512)*FRACUNIT, (6144+512)*FRACUNIT, (8192+512)*FRACUNIT, (12288+512)*FRACUNIT, (16384+512)*FRACUNIT}; -static INT32 current_bsp_culling_distance = 0; - -// The current screen texture implementation is inefficient and disabling it can result in significant -// performance gains on lower end hardware. The game is still quite playable without this functionality. -// Features that break when disabling this: -// - water and heat wave effects -// - intermission background -// - full screen scaling (use native resolution or windowed mode to avoid this) -static CV_PossibleValue_t grscreentextures_cons_t[] = {{0, "Off"}, {1, "Wipes Only"}, {2, "All"}, {0, NULL}}; -consvar_t cv_grscreentextures = {"gr_screentextures", "All", CV_CALL|CV_SAVE, grscreentextures_cons_t, - CV_screentextures_ONChange, 0, NULL, NULL, 0, 0, NULL}; - -static CV_PossibleValue_t grshaders_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Ignore custom shaders"}, {0, NULL}}; -consvar_t cv_grshaders = {"gr_shaders", "On", CV_CALL|CV_SAVE, grshaders_cons_t, CV_grshaders_OnChange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grpaletterendering = {"gr_paletteshader", "Off", CV_CALL|CV_SAVE, CV_OnOff, CV_grpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; - -static CV_PossibleValue_t glpalettedepth_cons_t[] = {{16, "16 bits"}, {24, "24 bits"}, {0, NULL}}; -consvar_t cv_grpalettedepth = {"gr_palettedepth", "16 bits", CV_SAVE|CV_CALL, glpalettedepth_cons_t, CV_grpalettedepth_OnChange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_lightdither = {"gr_lightdithering", "Off", CV_CALL|CV_SAVE, CV_OnOff, CV_grlightdithering_OnChange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grflashpal = {"gr_flashpal", "On", CV_CALL|CV_SAVE, CV_OnOff, CV_grpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grmdls = {"gr_mdls", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grfallbackplayermodel = {"gr_fallbackplayermodel", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grshearing = {"gr_shearing", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grspritebillboarding = {"gr_spritebillboarding", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grfakecontrast = {"gr_fakecontrast", "Standard", CV_SAVE, grfakecontrast_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grslopecontrast = {"gr_slopecontrast", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -consvar_t cv_grhorizonlines = {"gr_horizonlines", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -#define ONLY_IF_GL_LOADED if (vid.glstate != VID_GL_LIBRARY_LOADED) return; - -static void CV_filtermode_ONChange(void) -{ - ONLY_IF_GL_LOADED - HWD.pfnSetSpecialState(HWD_SET_TEXTUREFILTERMODE, cv_grfiltermode.value); -} - -static void CV_anisotropic_ONChange(void) -{ - ONLY_IF_GL_LOADED - HWD.pfnSetSpecialState(HWD_SET_TEXTUREANISOTROPICMODE, cv_granisotropicmode.value); -} - -static void CV_screentextures_ONChange(void) -{ - ONLY_IF_GL_LOADED - if (cv_grscreentextures.value != 2) - { -#ifdef USE_FBO_OGL - CV_Set(&cv_grframebuffer, "Off"); -#endif - CV_Set(&cv_grpaletterendering, "Off"); - } - HWD.pfnSetSpecialState(HWD_SET_SCREEN_TEXTURES, cv_grscreentextures.value); -} - -static void CV_grshaders_OnChange(void) -{ - ONLY_IF_GL_LOADED - HWR_SetShaderState(); - if (cv_grpaletterendering.value) - { - // can't do palette rendering without shaders, so update the state if needed - HWR_TogglePaletteRendering(); - } -} - -static void CV_grpaletterendering_OnChange(void) -{ - ONLY_IF_GL_LOADED - if (cv_grscreentextures.value != 2) // can't do palette rendering without screen textures - CV_Set(&cv_grpaletterendering, "Off"); - - if (gr_shadersavailable) - { - HWR_CompileShaders(); - HWR_TogglePaletteRendering(); - } -} - -static void CV_grlightdithering_OnChange(void) -{ - ONLY_IF_GL_LOADED - if (gr_shadersavailable) - { - HWR_CompileShaders(); - } -} - -static void CV_grpalettedepth_OnChange(void) -{ - ONLY_IF_GL_LOADED - if (HWR_ShouldUsePaletteRendering()) - HWR_SetPalette(pLocalPalette); -} - -#ifdef USE_FBO_OGL -static void CV_grframebuffer_OnChange(void) -{ - ONLY_IF_GL_LOADED - if (cv_grscreentextures.value != 2) // screen FBO needs screen textures - CV_Set(&cv_grframebuffer, "Off"); - HWD.pfnSetSpecialState(HWD_SET_FRAMEBUFFER, cv_grframebuffer.value); - I_DownSample(); - RefreshOGLSDLSurface(); -} -#endif - -// -// Sets the shader state. -// -void HWR_SetShaderState(void) -{ - HWD.pfnSetSpecialState(HWD_SET_SHADERS, HWR_UseShader() ? 1 : 0); -} - -// ========================================================================== -// Globals -// ========================================================================== - -// base values set at SetViewSize -static float gr_basecentery; -static float gr_basecenterx; - -float gr_baseviewwindowy, gr_basewindowcentery; -float gr_baseviewwindowx, gr_basewindowcenterx; -float gr_viewwidth, gr_viewheight; // viewport clipping boundaries (screen coords) - -static float gr_centerx; -static float gr_viewwindowx; -static float gr_windowcenterx; // center of view window, for projection - -static float gr_centery; -static float gr_viewwindowy; // top left corner of view window -static float gr_windowcentery; - -static float gr_pspritexscale, gr_pspriteyscale; - -static seg_t *gr_curline; -static side_t *gr_sidedef; -static line_t *gr_linedef; -static sector_t *gr_frontsector; -static sector_t *gr_backsector; - -static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, boolean noencore, FSurfaceInfo* Surf, INT32 cutflag, ffloor_t *pfloor, FBITFIELD polyflags); - // Performance stats ps_metric_t ps_hw_nodesorttime = {0}; ps_metric_t ps_hw_nodedrawtime = {0}; @@ -297,200 +118,201 @@ ps_metric_t ps_hw_numcolors = {0}; ps_metric_t ps_hw_batchsorttime = {0}; ps_metric_t ps_hw_batchdrawtime = {0}; +static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, boolean noencore, FSurfaceInfo* Surf, INT32 cutflag, ffloor_t *pfloor, FBITFIELD polyflags); +static void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap); + +static void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, boolean fogplane, extracolormap_t *planecolormap); +static void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, INT32 texnum, boolean noencore, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap); +static void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, extracolormap_t *planecolormap); + +static void HWR_AddSprites(sector_t *sec); +static void HWR_ProjectSprite(mobj_t *thing); static void HWR_AddPrecipitationSprites(void); static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing); -// ========================================================================== -// View position -// ========================================================================== - -FTransform atransform; - -// Float variants of viewx, viewy, viewz, etc. -static float gr_viewx, gr_viewy, gr_viewz; -float gr_viewsin, gr_viewcos; -static float gr_viewludsin, gr_viewludcos; - -static angle_t gr_aimingangle; static void HWR_SetTransformAiming(FTransform *trans); +static void HWR_RollTransform(FTransform *tr, angle_t roll); + +static void HWR_DoPostProcessor(player_t *player); + +static void HWR_SetShaderState(void); +static void HWR_TogglePaletteRendering(void); // ========================================================================== -// Visual portals (attr. Hannu Hanhi) +// Commands and console variables // ========================================================================== +static void HWR_RegisterCommands(void); +static void COM_HWR_glinfo(void); -static boolean HWR_PortalCheckPointSide(fixed_t x, fixed_t y); -static boolean HWR_PortalCheckBBox(const fixed_t *bspcoord); +// +// Onchanges +// -enum +static void CV_screentextures_OnChange(void); +#ifdef USE_FBO_OGL +static void CV_glframebuffer_OnChange(void); +#endif +static void CV_glshaders_OnChange(void); +static void CV_gllightdithering_OnChange(void); +static void CV_filtermode_OnChange(void); +static void CV_anisotropic_OnChange(void); +static void CV_glpaletterendering_OnChange(void); +static void CV_glpalettedepth_OnChange(void); + +// +// CV_PossibleValue_t +// + +static CV_PossibleValue_t glscreentextures_cons_t[] = {{0, "Off"}, {1, "Wipes Only"}, {2, "All"}, {0, NULL}}; +static CV_PossibleValue_t glfakecontrast_cons_t[] = {{0, "Off"}, {1, "Standard"}, {2, "Smooth"}, {0, NULL}}; +static CV_PossibleValue_t glshaders_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Ignore custom shaders"}, {0, NULL}}; +static CV_PossibleValue_t secbright_cons_t[] = {{0, "MIN"}, {255, "MAX"}, {0, NULL}}; + +static CV_PossibleValue_t glfiltermode_cons_t[]= {{HWD_SET_TEXTUREFILTER_POINTSAMPLED, "Nearest"}, + {HWD_SET_TEXTUREFILTER_BILINEAR, "Bilinear"}, {HWD_SET_TEXTUREFILTER_TRILINEAR, "Trilinear"}, + {HWD_SET_TEXTUREFILTER_MIXED1, "Linear_Nearest"}, {HWD_SET_TEXTUREFILTER_MIXED2, "Nearest_Linear"}, + {HWD_SET_TEXTUREFILTER_MIXED3, "Nearest_Mipmap"}, {0, NULL}}; +CV_PossibleValue_t glanisotropicmode_cons_t[] = {{1, "MIN"}, {16, "MAX"}, {0, NULL}}; + +static CV_PossibleValue_t glrenderdistance_cons_t[] = { + {0, "Max"}, {1, "1024"}, {2, "2048"}, {3, "4096"}, {4, "6144"}, {5, "8192"}, + {6, "12288"}, {7, "16384"}, {0, NULL}}; + +static CV_PossibleValue_t glpalettedepth_cons_t[] = {{16, "16 bits"}, {24, "24 bits"}, {0, NULL}}; + +// +// console variables +// + +// The current screen texture implementation is inefficient and disabling it can result in significant +// performance gains on lower end hardware. The game is still quite playable without this functionality. +// Features that break when disabling this: +// - water and heat wave effects +// - intermission background +// - full screen scaling (use native resolution or windowed mode to avoid this) +consvar_t cv_glscreentextures = {"gr_screentextures", "All", CV_CALL|CV_SAVE, glscreentextures_cons_t, CV_screentextures_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +#ifdef USE_FBO_OGL +consvar_t cv_glframebuffer = {"gr_framebuffer", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, CV_glframebuffer_OnChange, 0, NULL, NULL, 0, 0, NULL}; +#endif + +consvar_t cv_glmdls = {"gr_mdls", "Off", CV_SAVE|CV_CALL, CV_OnOff, M_UpdateOGLMenu, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_glfallbackplayermodel = {"gr_fallbackplayermodel", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glspritebillboarding = {"gr_spritebillboarding", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glshearing = {"gr_shearing", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glfakecontrast = {"gr_fakecontrast", "Standard", CV_SAVE, glfakecontrast_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_glslopecontrast = {"gr_slopecontrast", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glshaders = {"gr_shaders", "On", CV_CALL|CV_SAVE, glshaders_cons_t, CV_glshaders_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_gllightdither = {"gr_lightdithering", "Off", CV_CALL|CV_SAVE, CV_OnOff, CV_gllightdithering_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_glsecbright = {"secbright", "0", CV_SAVE, secbright_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glfiltermode = {"gr_filtermode", "Nearest", CV_CALL|CV_SAVE, glfiltermode_cons_t, CV_filtermode_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_glanisotropicmode = {"gr_anisotropicmode", "1", CV_CALL|CV_SAVE, glanisotropicmode_cons_t, CV_anisotropic_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glsolvetjoin = {"gr_solvetjoin", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glbatching = {"gr_batching", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glrenderdistance = {"gr_renderdistance", "Max", CV_SAVE, glrenderdistance_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glhorizonlines = {"gr_horizonlines", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_glportals = {"gr_portals", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glfovchange = {"gr_fovchange", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_glpaletterendering = {"gr_paletteshader", "Off", CV_CALL|CV_SAVE, CV_OnOff, CV_glpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_glpalettedepth = {"gr_palettedepth", "16 bits", CV_SAVE|CV_CALL, glpalettedepth_cons_t, CV_glpalettedepth_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_glflashpal = {"gr_flashpal", "On", CV_CALL|CV_SAVE, CV_OnOff, CV_glpaletterendering_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +#define ONLY_IF_GL_LOADED if (vid.glstate != VID_GL_LIBRARY_LOADED) return; + +static void CV_screentextures_OnChange(void) { - GRPORTAL_OFF, - GRPORTAL_SEARCH, - GRPORTAL_STENCIL, - GRPORTAL_DEPTH, - GRPORTAL_INSIDE, -}; + ONLY_IF_GL_LOADED + if (cv_glscreentextures.value != 2) + { + if (cv_glpaletterendering.value != 0) + CV_SetValue(&cv_glpaletterendering, 0); -static int gr_portal = GRPORTAL_OFF; -static boolean gl_drawing_stencil = false; -typedef struct gl_portal_s -{ - struct gl_portal_s *next; - - // Viewport. - fixed_t viewx; - fixed_t viewy; - fixed_t viewz; - angle_t viewangle; - - UINT8 pass; /**< Keeps track of the portal's recursion depth. */ - INT32 startline; - INT32 clipline; /**< Optional clipline for line-based portals. */ - INT32 drawcount; /**< For OpenGL. */ - - seg_t *seg; -} gl_portal_t; - -typedef struct gl_portallist_s -{ - gl_portal_t *base; - gl_portal_t *cap; -} gl_portallist_t; - -// new thing -gl_portallist_t *currentportallist; - -// More precise version of R_PointToAngle2 using floats and atan2. -static angle_t R_PointToAngle2Precise(fixed_t pviewx, fixed_t pviewy, fixed_t x, fixed_t y) -{ - fixed_t dx = x - pviewx; - fixed_t dy = y - pviewy; - float radians; - - if (!dx && !dy) - return 0; - - // no need for correct scale with FIXED_TO_FLOAT here - // since we're just calculating the angle - radians = atan2(dy, dx); - - return (angle_t)(radians / M_PI * ANGLE_180); +#ifdef USE_FBO_OGL + if (cv_glframebuffer.value != 0) + CV_SetValue(&cv_glframebuffer, 0); +#endif + } + GL_SetSpecialState(HWD_SET_SCREEN_TEXTURES, cv_glscreentextures.value); + M_UpdateOGLMenu(); } -// More precise version of R_PointToDist2 using floats and sqrt. -static fixed_t R_PointToDist2Precise(fixed_t px2, fixed_t py2, fixed_t px1, fixed_t py1) +#ifdef USE_FBO_OGL +static void CV_glframebuffer_OnChange(void) { - // float-fixed conversions can be omitted here - // because they cancel each other out in this case + ONLY_IF_GL_LOADED + if ((cv_glframebuffer.value != 0 && cv_glscreentextures.value != 2) || (!supportFBO && cv_glframebuffer.value != 0)) // screen FBO needs screen textures + CV_SetValue(&cv_glframebuffer, 0); - float dx = px1 - px2; - float dy = py1 - py2; - double result = sqrt(dx*dx + dy*dy); + I_DownSample(); + RefreshOGLSDLSurface(); + M_UpdateOGLMenu(); +} +#endif - return (fixed_t)result; +static void CV_glshaders_OnChange(void) +{ + ONLY_IF_GL_LOADED + HWR_SetShaderState(); + if (cv_glpaletterendering.value) + { + // can't do palette rendering without shaders, so update the state if needed + HWR_TogglePaletteRendering(); + } + M_UpdateOGLMenu(); } -static void HWR_Portal_Add2Lines(const INT32 line1, const INT32 line2, seg_t *seg) +static void CV_gllightdithering_OnChange(void) { - line_t *start, *dest; - - angle_t dangle; - - fixed_t disttopoint; - angle_t angtopoint; - - vertex_t dest_c, start_c; - - gl_portal_t *portal; - - portal = Z_Malloc(sizeof(gl_portal_t), PU_STATIC, NULL); - - // Linked list. - if (!currentportallist->base) + ONLY_IF_GL_LOADED + if (gl_shadersavailable) { - currentportallist->base = portal; - currentportallist->cap = portal; + HWR_CompileShaders(); } - else - { - currentportallist->cap->next = portal; - currentportallist->cap = portal; - } - portal->next = NULL; - - // Increase recursion level. - portal->pass = portalrender+1; - - portal->seg = seg; - - // Offset the portal view by the linedef centers - start = &lines[line1]; - dest = &lines[line2]; - - // Most fixed-point calculations and trigonometric function tables are replaced by - // floats and cmath library calls in this part to improve the precision of the - // location and angle of the new viewpoint. - // - // This reduces artefacts on the edges of portals, showing thin lines/pixels - // of the underlying graphics. (for example the sky texture) It's not 100% - // perfectly aligned and artefact-free, but looks noticeably - // better than the original code. I'm not even sure if it's this - // code or the nodebuilder or hw_map or something else causing the remaining issues.. - - dangle = R_PointToAngle2Precise(0,0,dest->dx,dest->dy) - R_PointToAngle2Precise(start->dx,start->dy,0,0); - - // looking glass center - start_c.x = start->v1->x/2 + start->v2->x/2; - start_c.y = start->v1->y/2 + start->v2->y/2; - - // other side center - dest_c.x = dest->v1->x/2 + dest->v2->x/2; - dest_c.y = dest->v1->y/2 + dest->v2->y/2; - - disttopoint = R_PointToDist2Precise(start_c.x, start_c.y, viewx, viewy); - angtopoint = R_PointToAngle2Precise(start_c.x, start_c.y, viewx, viewy); - angtopoint += dangle; - - float fang = ((float)angtopoint / 4294967296.0f) * 2.0f * M_PI; - - if (dangle == 0) - { - portal->viewx = viewx + dest_c.x - start_c.x; - portal->viewy = viewy + dest_c.y - start_c.y; - } - else - { - portal->viewx = dest_c.x + (fixed_t)(cos(fang) * disttopoint); - portal->viewy = dest_c.y + (fixed_t)(sin(fang) * disttopoint); - } - portal->viewz = viewz + dest->frontsector->floorheight - start->frontsector->floorheight; - portal->viewangle = viewangle + dangle; - - portal->startline = line1; - portal->clipline = line2; } -static void HWR_PortalFrame(gl_portal_t* portal) +static void CV_filtermode_OnChange(void) { - viewx = portal->viewx; - viewy = portal->viewy; - viewz = portal->viewz; + ONLY_IF_GL_LOADED + GL_SetSpecialState(HWD_SET_TEXTUREFILTERMODE, cv_glfiltermode.value); +} - viewangle = portal->viewangle; - viewsin = FINESINE(viewangle>>ANGLETOFINESHIFT); - viewcos = FINECOSINE(viewangle>>ANGLETOFINESHIFT); +static void CV_anisotropic_OnChange(void) +{ + ONLY_IF_GL_LOADED + GL_SetSpecialState(HWD_SET_TEXTUREANISOTROPICMODE, cv_glanisotropicmode.value); +} - if (portal->clipline != -1) +static void CV_glpaletterendering_OnChange(void) +{ + ONLY_IF_GL_LOADED + if (cv_glpaletterendering.value != 0 && cv_glscreentextures.value != 2) // can't do palette rendering without screen textures + CV_SetValue(&cv_glpaletterendering, 0); + + if (gl_shadersavailable) { - portalclipline = &lines[portal->clipline]; - portalcullsector = portalclipline->frontsector; - viewsector = portalclipline->frontsector; - } - else - { - portalclipline = NULL; - portalcullsector = NULL; - viewsector = R_PointInSubsector(viewx, viewy)->sector; + HWR_CompileShaders(); + HWR_TogglePaletteRendering(); } + M_UpdateOGLMenu(); +} + +static void CV_glpalettedepth_OnChange(void) +{ + ONLY_IF_GL_LOADED + if (HWR_ShouldUsePaletteRendering()) + HWR_SetPalette(pLocalPalette); } // ========================================================================== @@ -499,17 +321,22 @@ static void HWR_PortalFrame(gl_portal_t* portal) boolean HWR_UseShader(void) { - return (cv_grshaders.value && gr_shadersavailable); + return (cv_glshaders.value && gl_shadersavailable); +} + +static void HWR_SetShaderState(void) +{ + GL_SetSpecialState(HWD_SET_SHADERS, HWR_UseShader() ? 1 : 0); } boolean HWR_ShouldUsePaletteRendering(void) { - return (cv_grpaletterendering.value && HWR_UseShader()); + return (cv_glpaletterendering.value && (pLocalPalette != NULL) && HWR_UseShader()); } boolean HWR_PalRenderFlashpal(void) { - return (HWR_ShouldUsePaletteRendering() && cv_grflashpal.value); + return (HWR_ShouldUsePaletteRendering() && cv_glflashpal.value); } void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *colormap) @@ -558,7 +385,7 @@ void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *col } // Clamp the light level, since it can sometimes go out of the 0-255 range from animations - light_level = CLAMP(SOFTLIGHT(light_level), cv_secbright.value, 255); + light_level = CLAMP(SOFTLIGHT(light_level), cv_glsecbright.value, 255); // in palette rendering mode, this is not needed since it properly takes the changes to the palette itself if (!HWR_ShouldUsePaletteRendering()) @@ -575,7 +402,7 @@ void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *col Surface->LightTableId = HWR_ShouldUsePaletteRendering() ? HWR_GetLightTableID(colormap) : 0; } -UINT8 HWR_FogBlockAlpha(INT32 light, extracolormap_t *colormap) // Let's see if this can work +static UINT8 HWR_FogBlockAlpha(INT32 light, extracolormap_t *colormap) // Let's see if this can work { RGBA_t realcolor, surfcolor; INT32 alpha; @@ -604,11 +431,11 @@ static FUINT HWR_CalcWallLight(FUINT lightnum, seg_t *seg) { INT16 finallight = lightnum; - if (seg != NULL && cv_grfakecontrast.value != 0) + if (seg != NULL && cv_glfakecontrast.value != 0) { fixed_t extralight = 0; - if (cv_grfakecontrast.value == 2) // Smooth setting + if (cv_glfakecontrast.value == 2) // Smooth setting extralight += seg->hwLightOffset; else extralight += seg->lightOffset * 8; @@ -627,11 +454,11 @@ static FUINT HWR_CalcSlopeLight(FUINT lightnum, pslope_t *slope) { INT16 finallight = lightnum; - if (slope != NULL && cv_grfakecontrast.value != 0 && cv_grslopecontrast.value != 0) + if (slope != NULL && cv_glfakecontrast.value != 0 && cv_glslopecontrast.value != 0) { fixed_t extralight = 0; - if (cv_grfakecontrast.value == 2) // Smooth setting + if (cv_glfakecontrast.value == 2) // Smooth setting extralight += slope->hwLightOffset; else extralight += slope->lightOffset * 8; @@ -679,8 +506,7 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool // no convex poly were generated for this subsector if (!xsub->planepoly) return; - - pv = xsub->planepoly->pts; + nrPlaneVerts = xsub->planepoly->numpts; if (nrPlaneVerts < 3) //not even a triangle ? @@ -696,10 +522,10 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool } else { - if (gr_frontsector->f_slope && !isceiling) - slope = gr_frontsector->f_slope; - else if (gr_frontsector->c_slope && isceiling) - slope = gr_frontsector->c_slope; + if (gl_frontsector->f_slope && !isceiling) + slope = gl_frontsector->f_slope; + else if (gl_frontsector->c_slope && isceiling) + slope = gl_frontsector->c_slope; } // Set fixedheight to the slope's height from our viewpoint, if we have a slope @@ -750,6 +576,8 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool break; } + pv = xsub->planepoly->pts; + // reference point for flat texture coord for each vertex around the polygon flatxref = (float)(((fixed_t)pv->x & (~flatflag)) / fflatsize); flatyref = (float)(((fixed_t)pv->y & (~flatflag)) / fflatsize); @@ -769,19 +597,19 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool angle = FOFsector->ceilingpic_angle; } } - else if (gr_frontsector) + else if (gl_frontsector) { if (!isceiling) // it's a floor { - scrollx = FIXED_TO_FLOAT(gr_frontsector->floor_xoffs)/fflatsize; - scrolly = FIXED_TO_FLOAT(gr_frontsector->floor_yoffs)/fflatsize; - angle = gr_frontsector->floorpic_angle; + scrollx = FIXED_TO_FLOAT(gl_frontsector->floor_xoffs)/fflatsize; + scrolly = FIXED_TO_FLOAT(gl_frontsector->floor_yoffs)/fflatsize; + angle = gl_frontsector->floorpic_angle; } else // it's a ceiling { - scrollx = FIXED_TO_FLOAT(gr_frontsector->ceiling_xoffs)/fflatsize; - scrolly = FIXED_TO_FLOAT(gr_frontsector->ceiling_yoffs)/fflatsize; - angle = gr_frontsector->ceilingpic_angle; + scrollx = FIXED_TO_FLOAT(gl_frontsector->ceiling_xoffs)/fflatsize; + scrolly = FIXED_TO_FLOAT(gl_frontsector->ceiling_yoffs)/fflatsize; + angle = gl_frontsector->ceilingpic_angle; } } @@ -838,20 +666,20 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool PolyFlags |= PF_Masked|PF_Modulated; if (HWR_UseShader()) - { + { if (PolyFlags & PF_Fog) shader = SHADER_FOG; else if (cv_ripplewater.value && (PolyFlags & PF_Ripple)) shader = SHADER_WATER; else shader = SHADER_FLOOR; - + PolyFlags |= PF_ColorMapped; } HWR_ProcessPolygon(&Surf, planeVerts, nrPlaneVerts, PolyFlags, shader, false); - if (subsector && cv_grhorizonlines.value) + if (subsector && cv_glhorizonlines.value) { // Horizon lines FOutVector horizonpts[6]; @@ -908,9 +736,9 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool vy = y1 + yd * j / numplanes; SETUP3DVERT((&horizonpts[1]), vx, vy); - dist = sqrtf(powf(vx - gr_viewx, 2) + powf(vy - gr_viewy, 2)); - vx = (vx - gr_viewx) * renderdist / dist + gr_viewx; - vy = (vy - gr_viewy) * renderdist / dist + gr_viewy; + dist = sqrtf(powf(vx - gl_viewx, 2) + powf(vy - gl_viewy, 2)); + vx = (vx - gl_viewx) * renderdist / dist + gl_viewx; + vy = (vy - gl_viewy) * renderdist / dist + gl_viewy; SETUP3DVERT((&horizonpts[0]), vx, vy); // Right side @@ -918,21 +746,21 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool vy = y1 + yd * (j+1) / numplanes; SETUP3DVERT((&horizonpts[2]), vx, vy); - dist = sqrtf(powf(vx - gr_viewx, 2) + powf(vy - gr_viewy, 2)); - vx = (vx - gr_viewx) * renderdist / dist + gr_viewx; - vy = (vy - gr_viewy) * renderdist / dist + gr_viewy; + dist = sqrtf(powf(vx - gl_viewx, 2) + powf(vy - gl_viewy, 2)); + vx = (vx - gl_viewx) * renderdist / dist + gl_viewx; + vy = (vy - gl_viewy) * renderdist / dist + gl_viewy; SETUP3DVERT((&horizonpts[3]), vx, vy); // Horizon fills - vx = (horizonpts[0].x - gr_viewx) * farrenderdist / renderdist + gr_viewx; - vy = (horizonpts[0].z - gr_viewy) * farrenderdist / renderdist + gr_viewy; + vx = (horizonpts[0].x - gl_viewx) * farrenderdist / renderdist + gl_viewx; + vy = (horizonpts[0].z - gl_viewy) * farrenderdist / renderdist + gl_viewy; SETUP3DVERT((&horizonpts[5]), vx, vy); - horizonpts[5].y = gr_viewz; + horizonpts[5].y = gl_viewz; - vx = (horizonpts[3].x - gr_viewx) * farrenderdist / renderdist + gr_viewx; - vy = (horizonpts[3].z - gr_viewy) * farrenderdist / renderdist + gr_viewy; + vx = (horizonpts[3].x - gl_viewx) * farrenderdist / renderdist + gl_viewx; + vy = (horizonpts[3].z - gl_viewy) * farrenderdist / renderdist + gl_viewy; SETUP3DVERT((&horizonpts[4]), vx, vy); - horizonpts[4].y = gr_viewz; + horizonpts[4].y = gl_viewz; // Draw HWR_ProcessPolygon(&Surf, horizonpts, 6, PolyFlags, shader, true); @@ -950,18 +778,18 @@ static void HWR_DrawSegsSplats(FSurfaceInfo * pSurf) fixed_t i; // seg bbox fixed_t segbbox[4]; - + INT32 shader = SHADER_NONE; M_ClearBox(segbbox); M_AddToBox(segbbox, - FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv1)->x), - FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv1)->y)); + FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv1)->x), + FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv1)->y)); M_AddToBox(segbbox, - FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv2)->x), - FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv2)->y)); + FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv2)->x), + FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv2)->y)); - splat = (wallsplat_t *)gr_curline->linedef->splats; + splat = (wallsplat_t *)gl_curline->linedef->splats; for (; splat; splat = splat->next) { //BP: don't draw splat extern to this seg @@ -1005,7 +833,7 @@ static void HWR_DrawSegsSplats(FSurfaceInfo * pSurf) if (HWR_UseShader()) shader = SHADER_WALL; - + HWR_ProcessPolygon(&pSurf, wallVerts, 4, i|PF_Modulated|PF_Decal, shader, false); } } @@ -1035,10 +863,10 @@ FBITFIELD HWR_TranstableToAlpha(INT32 transtablenum, FSurfaceInfo *pSurf) // // HWR_ProjectWall // -void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blendmode, INT32 lightlevel, extracolormap_t *wallcolormap) +static void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blendmode, INT32 lightlevel, extracolormap_t *wallcolormap) { INT32 shader = SHADER_NONE; - + HWR_Lighting(pSurf, lightlevel, wallcolormap); if (HWR_UseShader()) @@ -1057,7 +885,7 @@ void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend HWR_ProcessPolygon(pSurf, wallVerts, 4, blendmode|PF_Modulated|PF_Occlude, shader, false); #ifdef WALLSPLATS - if (gr_curline->linedef->splats && cv_splats.value) + if (gl_curline->linedef->splats && cv_splats.value) HWR_DrawSegsSplats(pSurf); #endif } @@ -1077,43 +905,49 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, float endpegt, endpegb, endpegmul; float endheight = 0.0f, endbheight = 0.0f; + float diff; + fixed_t v1x = FloatToFixed(wallVerts[0].x); fixed_t v1y = FloatToFixed(wallVerts[0].z); fixed_t v2x = FloatToFixed(wallVerts[1].x); fixed_t v2y = FloatToFixed(wallVerts[1].z); const UINT8 alpha = Surf->PolyColor.s.alpha; - FUINT lightnum = HWR_CalcWallLight(sector->lightlevel, gr_curline); + FUINT lightnum = HWR_CalcWallLight(sector->lightlevel, gl_curline); extracolormap_t *colormap = NULL; realtop = top = wallVerts[3].y; realbot = bot = wallVerts[0].y; + diff = top - bot; + pegt = wallVerts[3].t; pegb = wallVerts[0].t; // Lactozilla: If both heights of a side lay on the same position, then this wall is a triangle. // To avoid division by zero, which would result in a NaN, we check if the vertical difference // between the two vertices is not zero. - if (fpclassify(top - bot) == FP_ZERO && cv_splitwallfix.value) + if (fpclassify(diff) == FP_ZERO) pegmul = 0.0; else - pegmul = (pegb - pegt) / (top - bot); + pegmul = (pegb - pegt) / diff; endrealtop = endtop = wallVerts[2].y; endrealbot = endbot = wallVerts[1].y; + diff = endtop - endbot; + endpegt = wallVerts[2].t; endpegb = wallVerts[1].t; - if (fpclassify(endtop - endbot) == FP_ZERO && cv_splitwallfix.value) + if (fpclassify(diff) == FP_ZERO) endpegmul = 0.0; else - endpegmul = (endpegb - endpegt) / (endtop - endbot); + endpegmul = (endpegb - endpegt) / diff; for (INT32 i = 0; i < sector->numlights; i++) { - if (endtop < endrealbot && top < realbot) + if ((endtop < endrealbot) && (top < realbot)) return; - + lightlist_t *list = sector->lightlist; if (!(list[i].flags & FF_NOSHADE)) @@ -1122,13 +956,13 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, { lightnum = pfloor->master->frontsector->lightlevel; colormap = pfloor->master->frontsector->extra_colormap; - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gr_curline); + lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); } else { lightnum = *list[i].lightlevel; colormap = list[i].extra_colormap; - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gr_curline); + lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); } } @@ -1176,32 +1010,17 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, bheight = realbot; endbheight = endrealbot; } - - if (cv_splitwallfix.value) - { - if (endbheight > endtop) - endbot = endtop; - } - if ((endbheight >= endtop && bheight >= top && !cv_splitwallfix.value) || (bheight >= top && cv_splitwallfix.value)) + if (endbheight >= endtop) + continue; + + if (bheight >= top) continue; // Found a break // The heights are clamped to ensure the polygon doesn't cross itself. - bot = bheight; - - if (bot < realbot) - bot = realbot; - - if (cv_splitwallfix.value) - endbot = min(max(endbheight, endrealbot), endtop); - else - { - endbot = endbheight; - - if (endbot < endrealbot) - endbot = endrealbot; - } + bot = CLAMP(bheight, realbot, top); + endbot = CLAMP(endbheight, endrealbot, endtop); Surf->PolyColor.s.alpha = alpha; @@ -1229,7 +1048,7 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, bot = realbot; endbot = endrealbot; - if (endtop <= endrealbot && top <= realbot) + if ((endtop <= endrealbot) && (top <= realbot)) return; Surf->PolyColor.s.alpha = alpha; @@ -1263,7 +1082,7 @@ FOutVector* skyWallVertexArray = NULL; int skyWallVertexArraySize = 0; int skyWallVertexArrayAllocSize = 65536;// what a mouthful -boolean gr_collect_skywalls = false; +boolean gl_collect_skywalls = false; static void HWR_SkyWallList_Clear(void) { @@ -1297,16 +1116,16 @@ static void HWR_DrawSkyWallList(void) surf.PolyColor.rgba = 0xFFFFFFFF; HWR_SetCurrentTexture(NULL); - HWD.pfnUnSetShader(); + GL_UnSetShader(); for (i = 0; i < skyWallVertexArraySize; i++) { - HWD.pfnDrawPolygon(&surf, skyWallVertexArray + i * 4, 4, PF_Occlude|PF_Invisible|PF_NoTexture); + GL_DrawPolygon(&surf, skyWallVertexArray + i * 4, 4, PF_Occlude|PF_Invisible|PF_NoTexture); } } // HWR_DrawSkyWalls // Draw walls into the depth buffer so that anything behind is culled properly -void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) +static void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) { //HWR_SetCurrentTexture(NULL); // no texture @@ -1315,7 +1134,7 @@ void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) wallVerts[0].s = wallVerts[3].s = 0; wallVerts[2].s = wallVerts[1].s = 0; - if (gr_collect_skywalls) + if (gl_collect_skywalls) { HWR_SkyWallList_Add(wallVerts); } @@ -1330,16 +1149,16 @@ void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) } // Returns true if the midtexture is visible, and false if... it isn't... -static boolean HWR_BlendMidtextureSurface(FSurfaceInfo *pSurf) +static inline boolean HWR_BlendMidtextureSurface(FSurfaceInfo *pSurf) { FUINT blendmode = PF_Masked; pSurf->PolyColor.s.alpha = 0xFF; - if (!gr_curline->polyseg) + if (!gl_curline->polyseg) { // set alpha for transparent walls - switch (gr_linedef->special) + switch (gl_linedef->special) { case 900: blendmode = HWR_TranstableToAlpha(tr_trans10, pSurf); @@ -1368,23 +1187,16 @@ static boolean HWR_BlendMidtextureSurface(FSurfaceInfo *pSurf) case 908: blendmode = HWR_TranstableToAlpha(tr_trans90, pSurf); break; - // Translucent + // Translucent linedef types case 102: - case 121: - case 123: - case 124: - case 125: - case 141: - case 142: - case 144: - case 145: + case 121 ... 125: + case 141 ... 145: case 174: case 175: case 192: case 195: case 221: - case 253: - case 256: + case 253 ... 256: blendmode = PF_Translucent; break; default: @@ -1392,15 +1204,16 @@ static boolean HWR_BlendMidtextureSurface(FSurfaceInfo *pSurf) break; } } - else if (gr_curline->polyseg->translucency > 0) + else if (gl_curline->polyseg->translucency > 0) { // Polyobject translucency is shared between all of its lines - if (gr_curline->polyseg->translucency >= NUMTRANSMAPS) // wall not drawn + if (gl_curline->polyseg->translucency >= NUMTRANSMAPS) // wall not drawn + { + pSurf->PolyColor.s.alpha = 0x00; // This shouldn't draw anything regardless of blendmode return false; - //Surf.PolyColor.s.alpha = 0x00; // This shouldn't draw anything regardless of blendmode - //blendmode = PF_Masked; + } else - blendmode = HWR_TranstableToAlpha(gr_curline->polyseg->translucency, pSurf); + blendmode = HWR_TranstableToAlpha(gl_curline->polyseg->translucency, pSurf); } if (blendmode != PF_Masked && pSurf->PolyColor.s.alpha == 0x00) @@ -1429,38 +1242,33 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom fixed_t worldhighslope = 0, worldlowslope = 0; fixed_t v1x, v1y, v2x, v2y; - float cliplow = 0.0f, cliphigh = 0.0f; fixed_t h, l; // 3D sides and 2s middle textures fixed_t hS, lS; - FUINT lightnum = 0; // shut up compiler - extracolormap_t *colormap; - FSurfaceInfo Surf; + gl_sidedef = gl_curline->sidedef; + gl_linedef = gl_curline->linedef; - boolean noencore = false; + const boolean noencore = (gl_linedef->flags & ML_TFERLINE); - gr_sidedef = gr_curline->sidedef; - gr_linedef = gr_curline->linedef; - - if (gr_curline->pv1) + if (gl_curline->pv1) { - vs.x = ((polyvertex_t *)gr_curline->pv1)->x; - vs.y = ((polyvertex_t *)gr_curline->pv1)->y; + vs.x = ((polyvertex_t *)gl_curline->pv1)->x; + vs.y = ((polyvertex_t *)gl_curline->pv1)->y; } else { - vs.x = FIXED_TO_FLOAT(gr_curline->v1->x); - vs.y = FIXED_TO_FLOAT(gr_curline->v1->y); + vs.x = FIXED_TO_FLOAT(gl_curline->v1->x); + vs.y = FIXED_TO_FLOAT(gl_curline->v1->y); } - if (gr_curline->pv2) + if (gl_curline->pv2) { - ve.x = ((polyvertex_t *)gr_curline->pv2)->x; - ve.y = ((polyvertex_t *)gr_curline->pv2)->y; + ve.x = ((polyvertex_t *)gl_curline->pv2)->x; + ve.y = ((polyvertex_t *)gl_curline->pv2)->y; } else { - ve.x = FIXED_TO_FLOAT(gr_curline->v2->x); - ve.y = FIXED_TO_FLOAT(gr_curline->v2->y); + ve.x = FIXED_TO_FLOAT(gl_curline->v2->x); + ve.y = FIXED_TO_FLOAT(gl_curline->v2->y); } v1x = FLOAT_TO_FIXED(vs.x); @@ -1475,8 +1283,8 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom } else \ end1 = end2 = normalheight; - SLOPEPARAMS(gr_frontsector->c_slope, worldtop, worldtopslope, gr_frontsector->ceilingheight) - SLOPEPARAMS(gr_frontsector->f_slope, worldbottom, worldbottomslope, gr_frontsector->floorheight) + SLOPEPARAMS(gl_frontsector->c_slope, worldtop, worldtopslope, gl_frontsector->ceilingheight) + SLOPEPARAMS(gl_frontsector->f_slope, worldbottom, worldbottomslope, gl_frontsector->floorheight) // remember vertices ordering // 3--2 @@ -1491,44 +1299,46 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom wallVerts[2].z = wallVerts[1].z = ve.y; // x offset the texture - fixed_t texturehpeg = gr_sidedef->textureoffset + gr_curline->offset; - cliplow = (float)texturehpeg; - cliphigh = (float)(texturehpeg + (gr_curline->flength*FRACUNIT)); + fixed_t texturehpeg = gl_sidedef->textureoffset + gl_curline->offset; + float cliplow = (float)texturehpeg; + float cliphigh = (float)(texturehpeg + (gl_curline->flength*FRACUNIT)); - lightnum = gr_frontsector->lightlevel; - colormap = gr_frontsector->extra_colormap; - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gr_curline); + FUINT lightnum = gl_frontsector->lightlevel; + extracolormap_t *colormap = gl_frontsector->extra_colormap; + lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); - if (gr_linedef->flags & ML_TFERLINE) - noencore = true; + FSurfaceInfo Surf; - Surf.PolyColor.s.alpha = 255; - - INT32 gr_midtexture = R_GetTextureNum(gr_sidedef->midtexture); - GLMapTexture_t *grTex = NULL; + if (gl_frontsector) + Surf.PolyColor.s.alpha = 255; + + INT32 gl_midtexture = R_GetTextureNum(gl_sidedef->midtexture); + GLMapTexture_t *glTex = NULL; // two sided line - if (gr_backsector) + if (gl_backsector) { - INT32 gr_toptexture = 0, gr_bottomtexture = 0; + INT32 gl_toptexture = 0, gl_bottomtexture = 0; - SLOPEPARAMS(gr_backsector->c_slope, worldhigh, worldhighslope, gr_backsector->ceilingheight) - SLOPEPARAMS(gr_backsector->f_slope, worldlow, worldlowslope, gr_backsector->floorheight) + fixed_t texturevpeg; + + SLOPEPARAMS(gl_backsector->c_slope, worldhigh, worldhighslope, gl_backsector->ceilingheight) + SLOPEPARAMS(gl_backsector->f_slope, worldlow, worldlowslope, gl_backsector->floorheight) // Sky culling - if (!gr_curline->polyseg) // Don't do it for polyobjects + if (!gl_curline->polyseg) // Don't do it for polyobjects { // Sky Ceilings wallVerts[3].y = wallVerts[2].y = FIXED_TO_FLOAT(INT32_MAX); - if (gr_frontsector->ceilingpic == skyflatnum) + if (gl_frontsector->ceilingpic == skyflatnum) { - if (gr_backsector->ceilingpic == skyflatnum) + if (gl_backsector->ceilingpic == skyflatnum) { // Both front and back sectors are sky, needs skywall from the frontsector's ceiling, but only if the // backsector is lower - if ((worldhigh <= worldtop && worldhighslope <= worldtopslope)// Assuming ESLOPE is always on with my changes - && (worldhigh != worldtop || worldhighslope != worldtopslope)) + if ((worldhigh <= worldtop && worldhighslope <= worldtopslope) // Assuming ESLOPE is always on with my changes + && (worldhigh != worldtop || worldhighslope != worldtopslope)) // Removing the second line above will render more rarely visible skywalls. Example: Cave garden ceiling in Dark race { wallVerts[0].y = FIXED_TO_FLOAT(worldhigh); @@ -1544,7 +1354,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom HWR_DrawSkyWall(wallVerts, &Surf); } } - else if (gr_backsector->ceilingpic == skyflatnum) + else if (gl_backsector->ceilingpic == skyflatnum) { // Only the backsector is sky, just draw a skywall from the front ceiling wallVerts[0].y = FIXED_TO_FLOAT(worldtop); @@ -1555,9 +1365,9 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom // Sky Floors wallVerts[0].y = wallVerts[1].y = FIXED_TO_FLOAT(INT32_MIN); - if (gr_frontsector->floorpic == skyflatnum) + if (gl_frontsector->floorpic == skyflatnum) { - if (gr_backsector->floorpic == skyflatnum) + if (gl_backsector->floorpic == skyflatnum) { // Both front and back sectors are sky, needs skywall from the backsector's floor, but only if the // it's higher, also needs to check for bottomtexture as the floors don't usually move down @@ -1565,7 +1375,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom if ((worldlow >= worldbottom && worldlowslope >= worldbottomslope) && (worldlow != worldbottom || worldlowslope != worldbottomslope) // Removing the second line above will render more rarely visible skywalls. Example: Cave garden ceiling in Dark race - && !(gr_sidedef->bottomtexture)) + && !(gl_sidedef->bottomtexture)) { wallVerts[3].y = FIXED_TO_FLOAT(worldlow); wallVerts[2].y = FIXED_TO_FLOAT(worldlowslope); @@ -1580,7 +1390,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom HWR_DrawSkyWall(wallVerts, &Surf); } } - else if ((gr_backsector->floorpic == skyflatnum) && !(gr_sidedef->bottomtexture)) + else if ((gl_backsector->floorpic == skyflatnum) && !(gl_sidedef->bottomtexture)) { // Only the backsector has sky, just draw a skywall from the back floor if there's no bottomtexture wallVerts[3].y = FIXED_TO_FLOAT(worldlow); @@ -1591,64 +1401,60 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom // hack to allow height changes in outdoor areas // This is what gets rid of the upper textures if there should be sky - if (gr_frontsector->ceilingpic == skyflatnum - && gr_backsector->ceilingpic == skyflatnum) + if (gl_frontsector->ceilingpic == skyflatnum + && gl_backsector->ceilingpic == skyflatnum) { worldtop = worldhigh; worldtopslope = worldhighslope; } - gr_toptexture = R_GetTextureNum(gr_sidedef->toptexture); - gr_bottomtexture = R_GetTextureNum(gr_sidedef->bottomtexture); + gl_toptexture = R_GetTextureNum(gl_sidedef->toptexture); + gl_bottomtexture = R_GetTextureNum(gl_sidedef->bottomtexture); // check TOP TEXTURE - if ((worldhighslope < worldtopslope || worldhigh < worldtop) && gr_toptexture) + if ((worldhighslope < worldtopslope || worldhigh < worldtop) && gl_toptexture) { + // PEGGING + if (gl_linedef->flags & ML_DONTPEGTOP) + texturevpeg = 0; + else if (gl_linedef->flags & ML_EFFECT1) + texturevpeg = worldhigh + textureheight[gl_toptexture] - worldtop; + else + texturevpeg = gl_backsector->ceilingheight + textureheight[gl_toptexture] - gl_frontsector->ceilingheight; + + texturevpeg += gl_sidedef->rowoffset; + + // This is so that it doesn't overflow and screw up the wall, it doesn't need to go higher than the texture's height anyway + texturevpeg %= textureheight[gl_toptexture]; + + glTex = HWR_GetTexture(gl_toptexture, noencore); + + wallVerts[3].t = wallVerts[2].t = texturevpeg * glTex->scaleY; + wallVerts[0].t = wallVerts[1].t = (texturevpeg + gl_frontsector->ceilingheight - gl_backsector->ceilingheight) * glTex->scaleY; + wallVerts[0].s = wallVerts[3].s = cliplow * glTex->scaleX; + wallVerts[2].s = wallVerts[1].s = cliphigh * glTex->scaleX; + + // Adjust t value for sloped walls + if (!(gl_linedef->flags & ML_EFFECT1)) { - fixed_t texturevpegtop; // top - - grTex = HWR_GetTexture(gr_toptexture, gr_linedef->flags & ML_TFERLINE); - - // PEGGING - if (gr_linedef->flags & ML_DONTPEGTOP) - texturevpegtop = 0; - else if (gr_linedef->flags & ML_EFFECT1) - texturevpegtop = worldhigh + textureheight[gr_sidedef->toptexture] - worldtop; - else - texturevpegtop = gr_backsector->ceilingheight + textureheight[gr_sidedef->toptexture] - gr_frontsector->ceilingheight; - - texturevpegtop += gr_sidedef->rowoffset; - - // This is so that it doesn't overflow and screw up the wall, it doesn't need to go higher than the texture's height anyway - texturevpegtop %= SHORT(textures[gr_toptexture]->height)<scaleY; - wallVerts[0].t = wallVerts[1].t = (texturevpegtop + gr_frontsector->ceilingheight - gr_backsector->ceilingheight) * grTex->scaleY; - wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; - - // Adjust t value for sloped walls - if (!(gr_linedef->flags & ML_EFFECT1)) - { - // Unskewed - wallVerts[3].t -= (worldtop - gr_frontsector->ceilingheight) * grTex->scaleY; - wallVerts[2].t -= (worldtopslope - gr_frontsector->ceilingheight) * grTex->scaleY; - wallVerts[0].t -= (worldhigh - gr_backsector->ceilingheight) * grTex->scaleY; - wallVerts[1].t -= (worldhighslope - gr_backsector->ceilingheight) * grTex->scaleY; - } - else if (gr_linedef->flags & ML_DONTPEGTOP) - { - // Skewed by top - wallVerts[0].t = (texturevpegtop + worldtop - worldhigh) * grTex->scaleY; - wallVerts[1].t = (texturevpegtop + worldtopslope - worldhighslope) * grTex->scaleY; - } - else - { - // Skewed by bottom - wallVerts[0].t = wallVerts[1].t = (texturevpegtop + worldtop - worldhigh) * grTex->scaleY; - wallVerts[3].t = wallVerts[0].t - (worldtop - worldhigh) * grTex->scaleY; - wallVerts[2].t = wallVerts[1].t - (worldtopslope - worldhighslope) * grTex->scaleY; - } + // Unskewed + wallVerts[3].t -= (worldtop - gl_frontsector->ceilingheight) * glTex->scaleY; + wallVerts[2].t -= (worldtopslope - gl_frontsector->ceilingheight) * glTex->scaleY; + wallVerts[0].t -= (worldhigh - gl_backsector->ceilingheight) * glTex->scaleY; + wallVerts[1].t -= (worldhighslope - gl_backsector->ceilingheight) * glTex->scaleY; + } + else if (gl_linedef->flags & ML_DONTPEGTOP) + { + // Skewed by top + wallVerts[0].t = (texturevpeg + worldtop - worldhigh) * glTex->scaleY; + wallVerts[1].t = (texturevpeg + worldtopslope - worldhighslope) * glTex->scaleY; + } + else + { + // Skewed by bottom + wallVerts[0].t = wallVerts[1].t = (texturevpeg + worldtop - worldhigh) * glTex->scaleY; + wallVerts[3].t = wallVerts[0].t - (worldtop - worldhigh) * glTex->scaleY; + wallVerts[2].t = wallVerts[1].t - (worldtopslope - worldhighslope) * glTex->scaleY; } // set top/bottom coords @@ -1657,60 +1463,57 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom wallVerts[2].y = FIXED_TO_FLOAT(worldtopslope); wallVerts[1].y = FIXED_TO_FLOAT(worldhighslope); - if (!gl_drawing_stencil && gr_frontsector->numlights) - HWR_SplitWall(gr_frontsector, wallVerts, gr_toptexture, gr_linedef->flags & ML_TFERLINE, &Surf, FF_CUTLEVEL, NULL, 0); - else if (!gl_drawing_stencil && grTex->mipmap.flags & TF_TRANSPARENT) - HWR_AddTransparentWall(wallVerts, &Surf, gr_toptexture, gr_linedef->flags & ML_TFERLINE, PF_Environment, false, lightnum, colormap); + if (!gl_drawing_stencil && gl_frontsector->numlights) + HWR_SplitWall(gl_frontsector, wallVerts, gl_toptexture, noencore, &Surf, FF_CUTLEVEL, NULL, 0); + else if (!gl_drawing_stencil && glTex->mipmap.flags & TF_TRANSPARENT) + HWR_AddTransparentWall(wallVerts, &Surf, gl_toptexture, noencore, PF_Environment, false, lightnum, colormap); else HWR_ProjectWall(wallVerts, &Surf, PF_Masked, lightnum, colormap); } // check BOTTOM TEXTURE - if ((worldlowslope > worldbottomslope || worldlow > worldbottom) && gr_bottomtexture) //only if VISIBLE!!! + if ((worldlowslope > worldbottomslope || worldlow > worldbottom) && gl_bottomtexture) { - fixed_t texturevpegbottom = 0; // bottom - - grTex = HWR_GetTexture(gr_bottomtexture, gr_linedef->flags & ML_TFERLINE); - // PEGGING - if (!(gr_linedef->flags & ML_DONTPEGBOTTOM)) - texturevpegbottom = 0; - else if (gr_linedef->flags & ML_EFFECT1) - texturevpegbottom = worldbottom - worldlow; + if (!(gl_linedef->flags & ML_DONTPEGBOTTOM)) + texturevpeg = 0; + else if (gl_linedef->flags & ML_EFFECT1) + texturevpeg = worldbottom - worldlow; else - texturevpegbottom = gr_frontsector->floorheight - gr_backsector->floorheight; + texturevpeg = gl_frontsector->floorheight - gl_backsector->floorheight; - texturevpegbottom += gr_sidedef->rowoffset; + texturevpeg += gl_sidedef->rowoffset; // This is so that it doesn't overflow and screw up the wall, it doesn't need to go higher than the texture's height anyway - texturevpegbottom %= SHORT(textures[gr_bottomtexture]->height)<scaleY; - wallVerts[0].t = wallVerts[1].t = (texturevpegbottom + gr_backsector->floorheight - gr_frontsector->floorheight) * grTex->scaleY; - wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; + glTex = HWR_GetTexture(gl_bottomtexture, noencore); + + wallVerts[3].t = wallVerts[2].t = texturevpeg * glTex->scaleY; + wallVerts[0].t = wallVerts[1].t = (texturevpeg + gl_backsector->floorheight - gl_frontsector->floorheight) * glTex->scaleY; + wallVerts[0].s = wallVerts[3].s = cliplow * glTex->scaleX; + wallVerts[2].s = wallVerts[1].s = cliphigh * glTex->scaleX; // Adjust t value for sloped walls - if (!(gr_linedef->flags & ML_EFFECT1)) + if (!(gl_linedef->flags & ML_EFFECT1)) { // Unskewed - wallVerts[0].t -= (worldbottom - gr_frontsector->floorheight) * grTex->scaleY; - wallVerts[1].t -= (worldbottomslope - gr_frontsector->floorheight) * grTex->scaleY; - wallVerts[3].t -= (worldlow - gr_backsector->floorheight) * grTex->scaleY; - wallVerts[2].t -= (worldlowslope - gr_backsector->floorheight) * grTex->scaleY; + wallVerts[0].t -= (worldbottom - gl_frontsector->floorheight) * glTex->scaleY; + wallVerts[1].t -= (worldbottomslope - gl_frontsector->floorheight) * glTex->scaleY; + wallVerts[3].t -= (worldlow - gl_backsector->floorheight) * glTex->scaleY; + wallVerts[2].t -= (worldlowslope - gl_backsector->floorheight) * glTex->scaleY; } - else if (gr_linedef->flags & ML_DONTPEGBOTTOM) + else if (gl_linedef->flags & ML_DONTPEGBOTTOM) { // Skewed by bottom - wallVerts[0].t = wallVerts[1].t = (texturevpegbottom + worldlow - worldbottom) * grTex->scaleY; - //wallVerts[3].t = wallVerts[0].t - (worldlow - worldbottom) * grTex->scaleY; // no need, [3] is already this - wallVerts[2].t = wallVerts[1].t - (worldlowslope - worldbottomslope) * grTex->scaleY; + wallVerts[0].t = wallVerts[1].t = (texturevpeg + worldlow - worldbottom) * glTex->scaleY; + wallVerts[2].t = wallVerts[1].t - (worldlowslope - worldbottomslope) * glTex->scaleY; } else { // Skewed by top - wallVerts[0].t = (texturevpegbottom + worldlow - worldbottom) * grTex->scaleY; - wallVerts[1].t = (texturevpegbottom + worldlowslope - worldbottomslope) * grTex->scaleY; + wallVerts[0].t = (texturevpeg + worldlow - worldbottom) * glTex->scaleY; + wallVerts[1].t = (texturevpeg + worldlowslope - worldbottomslope) * glTex->scaleY; } // set top/bottom coords @@ -1719,32 +1522,32 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom wallVerts[2].y = FIXED_TO_FLOAT(worldlowslope); wallVerts[1].y = FIXED_TO_FLOAT(worldbottomslope); - if (!gl_drawing_stencil && gr_frontsector->numlights) - HWR_SplitWall(gr_frontsector, wallVerts, gr_bottomtexture, gr_linedef->flags & ML_TFERLINE, &Surf, FF_CUTLEVEL, NULL, 0); - else if (!gl_drawing_stencil && grTex->mipmap.flags & TF_TRANSPARENT) - HWR_AddTransparentWall(wallVerts, &Surf, gr_bottomtexture, gr_linedef->flags & ML_TFERLINE, PF_Environment, false, lightnum, colormap); + if (!gl_drawing_stencil && gl_frontsector->numlights) + HWR_SplitWall(gl_frontsector, wallVerts, gl_bottomtexture, noencore, &Surf, FF_CUTLEVEL, NULL, 0); + else if (!gl_drawing_stencil && glTex->mipmap.flags & TF_TRANSPARENT) + HWR_AddTransparentWall(wallVerts, &Surf, gl_bottomtexture, noencore, PF_Environment, false, lightnum, colormap); else HWR_ProjectWall(wallVerts, &Surf, PF_Masked, lightnum, colormap); } - if ((gr_midtexture && HWR_BlendMidtextureSurface(&Surf)) || gr_portal == GRPORTAL_STENCIL || gr_portal == GRPORTAL_DEPTH || gl_drawing_stencil) + if ((gl_midtexture && HWR_BlendMidtextureSurface(&Surf)) || gl_portal_state == GLPORTAL_STENCIL || gl_portal_state == GLPORTAL_DEPTH || gl_drawing_stencil) { sector_t *front, *back; INT32 repeats; - if (gr_linedef->frontsector->heightsec != -1) - front = §ors[gr_linedef->frontsector->heightsec]; + if (gl_linedef->frontsector->heightsec != -1) + front = §ors[gl_linedef->frontsector->heightsec]; else - front = gr_linedef->frontsector; + front = gl_linedef->frontsector; - if (gr_linedef->backsector->heightsec != -1) - back = §ors[gr_linedef->backsector->heightsec]; + if (gl_linedef->backsector->heightsec != -1) + back = §ors[gl_linedef->backsector->heightsec]; else - back = gr_linedef->backsector; + back = gl_linedef->backsector; - if (gr_sidedef->repeatcnt) - repeats = 1 + gr_sidedef->repeatcnt; - else if (gr_linedef->flags & ML_EFFECT5 || gr_portal == GRPORTAL_STENCIL || gr_portal == GRPORTAL_DEPTH) + if (gl_sidedef->repeatcnt) + repeats = 1 + gl_sidedef->repeatcnt; + else if (gl_linedef->flags & ML_EFFECT5 || gl_portal_state == GLPORTAL_STENCIL || gl_portal_state == GLPORTAL_DEPTH) { fixed_t high, low; @@ -1758,28 +1561,26 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom else low = back->floorheight; - repeats = (high - low)/textureheight[gr_sidedef->midtexture]; - if ((high-low)%textureheight[gr_sidedef->midtexture]) + repeats = (high - low) / textureheight[gl_midtexture]; + if ((high - low) % textureheight[gl_midtexture]) repeats++; // tile an extra time to fill the gap -- Monster Iestyn } else repeats = 1; - fixed_t midtexheight = textureheight[gr_midtexture] * repeats; - fixed_t popentop, popenbottom, polytop, polybottom, lowcut, highcut; - fixed_t popentopslope, popenbottomslope, polytopslope, polybottomslope, lowcutslope, highcutslope; - // SoM: a little note: This code re-arranging will // fix the bug in Nimrod map02. popentop and popenbottom // record the limits the texture can be displayed in. // polytop and polybottom, are the ideal (i.e. unclipped) // heights of the polygon, and h & l, are the final (clipped) // poly coords. + fixed_t popentop, popenbottom, polytop, polybottom, lowcut, highcut; + fixed_t popentopslope, popenbottomslope, polytopslope, polybottomslope, lowcutslope, highcutslope; // NOTE: With polyobjects, whenever you need to check the properties of the polyobject sector it belongs to, // you must use the linedef's backsector to be correct // From CB - if (gr_curline->polyseg) + if (gl_curline->polyseg) { popentop = popentopslope = back->ceilingheight; popenbottom = popenbottomslope = back->floorheight; @@ -1788,48 +1589,49 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom { popentop = min(worldtop, worldhigh); popenbottom = max(worldbottom, worldlow); - popentopslope = min(worldtopslope, worldhighslope); popenbottomslope = max(worldbottomslope, worldlowslope); } - if (gr_linedef->flags & ML_EFFECT2) + // Find the wall's coordinates + fixed_t midtexheight = textureheight[gl_midtexture] * repeats; + + if (gl_linedef->flags & ML_EFFECT2) { - if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) + if (!!(gl_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gl_linedef->flags & ML_EFFECT3)) // Peg it to the floor { - polybottom = max(front->floorheight, back->floorheight) + gr_sidedef->rowoffset; - polybottomslope = polybottom; + polybottom = max(front->floorheight, back->floorheight) + gl_sidedef->rowoffset; polytop = polybottom + midtexheight; - polytopslope = polytop; } - else + else // Peg it to the ceiling { - polytop = min(front->ceilingheight, back->ceilingheight) + gr_sidedef->rowoffset; - polytopslope = polytop; + polytop = min(front->ceilingheight, back->ceilingheight) + gl_sidedef->rowoffset; polybottom = polytop - midtexheight; - polybottomslope = polybottom; } + + // The right side's coordinates are the the same as the left side + polytopslope = polytop; + polybottomslope = polybottom; } - else if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) + else if (!!(gl_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gl_linedef->flags & ML_EFFECT3)) // Skew the texture, but peg it to the floor { - polybottom = popenbottom + gr_sidedef->rowoffset; + polybottom = popenbottom + gl_sidedef->rowoffset; polytop = polybottom + midtexheight; - polybottomslope = popenbottomslope + gr_sidedef->rowoffset; + polybottomslope = popenbottomslope + gl_sidedef->rowoffset; polytopslope = polybottomslope + midtexheight; } - else + else // Skew it according to the ceiling's slope { - polytop = popentop + gr_sidedef->rowoffset; - polybottom = polytop - textureheight[gr_midtexture]*repeats; + polytop = popentop + gl_sidedef->rowoffset; polybottom = polytop - midtexheight; - polytopslope = popentopslope + gr_sidedef->rowoffset; + polytopslope = popentopslope + gl_sidedef->rowoffset; polybottomslope = polytopslope - midtexheight; } // CB // NOTE: With polyobjects, whenever you need to check the properties of the polyobject sector it belongs to, // you must use the linedef's backsector to be correct - if (gr_curline->polyseg) + if (gl_curline->polyseg) { lowcut = polybottom; highcut = polytop; @@ -1851,11 +1653,9 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom lS = max(polybottomslope, lowcutslope); // PEGGING - fixed_t texturevpeg, texturevpegslope; + fixed_t texturevpegslope; - grTex = HWR_GetTexture(gr_midtexture, gr_linedef->flags & ML_TFERLINE); - - if (!!(gr_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gr_linedef->flags & ML_EFFECT3)) + if (!!(gl_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gl_linedef->flags & ML_EFFECT3)) { texturevpeg = midtexheight - h + polybottom; texturevpegslope = midtexheight - hS + polybottomslope; @@ -1866,12 +1666,17 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom texturevpegslope = polytopslope - hS; } - wallVerts[3].t = texturevpeg * grTex->scaleY; - wallVerts[0].t = (h - l + texturevpeg) * grTex->scaleY; - wallVerts[2].t = texturevpegslope * grTex->scaleY; - wallVerts[1].t = (hS - lS + texturevpegslope) * grTex->scaleY; - wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; + glTex = HWR_GetTexture(gl_midtexture, noencore); + + // Left side + wallVerts[3].t = texturevpeg * glTex->scaleY; + wallVerts[0].t = (h - l + texturevpeg) * glTex->scaleY; + wallVerts[0].s = wallVerts[3].s = cliplow * glTex->scaleX; + + // Right side + wallVerts[2].t = texturevpegslope * glTex->scaleY; + wallVerts[1].t = (hS - lS + texturevpegslope) * glTex->scaleY; + wallVerts[2].s = wallVerts[1].s = cliphigh * glTex->scaleX; // set top/bottom coords // Take the texture peg into account, rather than changing the offsets past @@ -1888,10 +1693,10 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom // This will cause the midtexture appear on top, if a FOF overlaps with it. blendmode |= PF_Decal; - if (!gl_drawing_stencil && gr_frontsector->numlights) - HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, gr_linedef->flags & ML_TFERLINE, &Surf, (!(blendmode & PF_Masked)) ? FF_TRANSLUCENT : FF_CUTLEVEL, NULL, PF_Decal); + if (!gl_drawing_stencil && gl_frontsector->numlights) + HWR_SplitWall(gl_frontsector, wallVerts, gl_midtexture, noencore, &Surf, (!(blendmode & PF_Masked)) ? FF_TRANSLUCENT : FF_CUTLEVEL, NULL, PF_Decal); else if (!gl_drawing_stencil && !(blendmode & PF_Masked)) - HWR_AddTransparentWall(wallVerts, &Surf, gr_midtexture, gr_linedef->flags & ML_TFERLINE, blendmode, false, lightnum, colormap); + HWR_AddTransparentWall(wallVerts, &Surf, gl_midtexture, noencore, blendmode, false, lightnum, colormap); else HWR_ProjectWall(wallVerts, &Surf, blendmode, lightnum, colormap); } @@ -1899,42 +1704,42 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom else { // Single sided line... Deal only with the middletexture (if one exists) - if (gr_midtexture && gr_linedef->special != HORIZONSPECIAL) // Ignore horizon line for OGL + if (gl_midtexture && gl_linedef->special != HORIZONSPECIAL) // Ignore horizon line for OGL { + glTex = HWR_GetTexture(gl_midtexture, noencore); + fixed_t texturevpeg; // PEGGING - if ((gr_linedef->flags & (ML_DONTPEGBOTTOM|ML_EFFECT2)) == (ML_DONTPEGBOTTOM|ML_EFFECT2)) - texturevpeg = gr_frontsector->floorheight + textureheight[gr_sidedef->midtexture] - gr_frontsector->ceilingheight + gr_sidedef->rowoffset; - else if (gr_linedef->flags & ML_DONTPEGBOTTOM) - texturevpeg = worldbottom + textureheight[gr_sidedef->midtexture] - worldtop + gr_sidedef->rowoffset; + if ((gl_linedef->flags & (ML_DONTPEGBOTTOM|ML_EFFECT2)) == (ML_DONTPEGBOTTOM|ML_EFFECT2)) + texturevpeg = gl_frontsector->floorheight + textureheight[gl_sidedef->midtexture] - gl_frontsector->ceilingheight + gl_sidedef->rowoffset; + else if (gl_linedef->flags & ML_DONTPEGBOTTOM) + texturevpeg = worldbottom + textureheight[gl_sidedef->midtexture] - worldtop + gl_sidedef->rowoffset; else - texturevpeg = gr_sidedef->rowoffset; // top of texture at top + texturevpeg = gl_sidedef->rowoffset; // top of texture at top - grTex = HWR_GetTexture(gr_midtexture, gr_linedef->flags & ML_TFERLINE); - - wallVerts[3].t = wallVerts[2].t = texturevpeg * grTex->scaleY; - wallVerts[0].t = wallVerts[1].t = (texturevpeg + gr_frontsector->ceilingheight - gr_frontsector->floorheight) * grTex->scaleY; - wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; + wallVerts[3].t = wallVerts[2].t = texturevpeg * glTex->scaleY; + wallVerts[0].t = wallVerts[1].t = (texturevpeg + gl_frontsector->ceilingheight - gl_frontsector->floorheight) * glTex->scaleY; + wallVerts[0].s = wallVerts[3].s = cliplow * glTex->scaleX; + wallVerts[2].s = wallVerts[1].s = cliphigh * glTex->scaleX; // Texture correction for slopes - if (gr_linedef->flags & ML_EFFECT2) + if (gl_linedef->flags & ML_EFFECT2) { - wallVerts[3].t += (gr_frontsector->ceilingheight - worldtop) * grTex->scaleY; - wallVerts[2].t += (gr_frontsector->ceilingheight - worldtopslope) * grTex->scaleY; - wallVerts[0].t += (gr_frontsector->floorheight - worldbottom) * grTex->scaleY; - wallVerts[1].t += (gr_frontsector->floorheight - worldbottomslope) * grTex->scaleY; + wallVerts[3].t += (gl_frontsector->ceilingheight - worldtop) * glTex->scaleY; + wallVerts[2].t += (gl_frontsector->ceilingheight - worldtopslope) * glTex->scaleY; + wallVerts[0].t += (gl_frontsector->floorheight - worldbottom) * glTex->scaleY; + wallVerts[1].t += (gl_frontsector->floorheight - worldbottomslope) * glTex->scaleY; } - else if (gr_linedef->flags & ML_DONTPEGBOTTOM) + else if (gl_linedef->flags & ML_DONTPEGBOTTOM) { - wallVerts[3].t = wallVerts[0].t + (worldbottom-worldtop) * grTex->scaleY; - wallVerts[2].t = wallVerts[1].t + (worldbottomslope-worldtopslope) * grTex->scaleY; + wallVerts[3].t = wallVerts[0].t + (worldbottom-worldtop) * glTex->scaleY; + wallVerts[2].t = wallVerts[1].t + (worldbottomslope-worldtopslope) * glTex->scaleY; } else { - wallVerts[0].t = wallVerts[3].t - (worldbottom-worldtop) * grTex->scaleY; - wallVerts[1].t = wallVerts[2].t - (worldbottomslope-worldtopslope) * grTex->scaleY; + wallVerts[0].t = wallVerts[3].t - (worldbottom-worldtop) * glTex->scaleY; + wallVerts[1].t = wallVerts[2].t - (worldbottomslope-worldtopslope) * glTex->scaleY; } //Set textures properly on single sided walls that are sloped @@ -1943,12 +1748,12 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom wallVerts[2].y = FIXED_TO_FLOAT(worldtopslope); wallVerts[1].y = FIXED_TO_FLOAT(worldbottomslope); - if (gr_frontsector->numlights) - HWR_SplitWall(gr_frontsector, wallVerts, gr_midtexture, gr_linedef->flags & ML_TFERLINE, &Surf, FF_CUTLEVEL, NULL, 0); + if (gl_frontsector->numlights) + HWR_SplitWall(gl_frontsector, wallVerts, gl_midtexture, noencore, &Surf, FF_CUTLEVEL, NULL, 0); else // I don't think that solid walls can use translucent linedef types... { - if (grTex->mipmap.flags & TF_TRANSPARENT) - HWR_AddTransparentWall(wallVerts, &Surf, gr_midtexture, gr_linedef->flags & ML_TFERLINE, PF_Environment, false, lightnum, colormap); + if (glTex->mipmap.flags & TF_TRANSPARENT) + HWR_AddTransparentWall(wallVerts, &Surf, gl_midtexture, noencore, PF_Environment, false, lightnum, colormap); else HWR_ProjectWall(wallVerts, &Surf, PF_Masked, lightnum, colormap); } @@ -1965,22 +1770,21 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom HWR_DrawSkyWall(wallVerts, &Surf); } - // Single sided lines are simple for skywalls, just need to draw from the top or bottom of the sector if there's - // a sky flat - if (!gr_curline->polyseg) + if (!gl_curline->polyseg) { - if (gr_frontsector->ceilingpic == skyflatnum) // It's a single-sided line with sky for its sector + if (gl_frontsector->ceilingpic == skyflatnum) // It's a single-sided line with sky for its sector { - wallVerts[3].y = wallVerts[2].y = FIXED_TO_FLOAT(INT32_MAX); + wallVerts[2].y = wallVerts[3].y = FIXED_TO_FLOAT(INT32_MAX); // draw to top of map space wallVerts[0].y = FIXED_TO_FLOAT(worldtop); wallVerts[1].y = FIXED_TO_FLOAT(worldtopslope); + HWR_DrawSkyWall(wallVerts, &Surf); } - if (gr_frontsector->floorpic == skyflatnum) + if (gl_frontsector->floorpic == skyflatnum) { wallVerts[3].y = FIXED_TO_FLOAT(worldbottom); wallVerts[2].y = FIXED_TO_FLOAT(worldbottomslope); - wallVerts[0].y = wallVerts[1].y = FIXED_TO_FLOAT(INT32_MIN); + wallVerts[0].y = wallVerts[1].y = FIXED_TO_FLOAT(INT32_MIN); // draw to bottom of map space HWR_DrawSkyWall(wallVerts, &Surf); } @@ -1988,7 +1792,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom } //Hurdler: 3d-floors test - if (!gl_drawing_stencil && gr_frontsector && gr_backsector && gr_frontsector->tag != gr_backsector->tag && (gr_backsector->ffloors || gr_frontsector->ffloors)) + if (!gl_drawing_stencil && gl_backsector && gl_frontsector->tag != gl_backsector->tag && (gl_backsector->ffloors || gl_frontsector->ffloors)) { ffloor_t * rover; fixed_t highcut = 0, lowcut = 0; @@ -2005,9 +1809,9 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom lowcutslope = max(worldbottomslope, worldlowslope); highcutslope = min(worldtopslope, worldhighslope); - if (gr_backsector->ffloors) + if (gl_backsector->ffloors) { - for (rover = gr_backsector->ffloors; rover; rover = rover->next) + for (rover = gl_backsector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERSIDES) || (rover->flags & FF_INVERTSIDES)) continue; @@ -2022,7 +1826,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom if (rover->master->flags & ML_TFERLINE) { - size_t linenum = min((size_t)(gr_curline->linedef-gr_backsector->lines[0]), rover->master->frontsector->linecount); + size_t linenum = min((size_t)(gl_curline->linedef-gl_backsector->lines[0]), rover->master->frontsector->linecount); newline = rover->master->frontsector->lines[0] + linenum; texnum = R_GetTextureNum(sides[newline->sidenum[0]].midtexture); } @@ -2078,39 +1882,39 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom else { texturevpeg = sides[rover->master->sidenum[0]].rowoffset; - attachtobottom = !!(gr_linedef->flags & ML_DONTPEGBOTTOM); + attachtobottom = !!(gl_linedef->flags & ML_DONTPEGBOTTOM); slopeskew = !!(rover->master->flags & ML_DONTPEGTOP); } - grTex = HWR_GetTexture(texnum, noencore); + glTex = HWR_GetTexture(texnum, noencore); if (!slopeskew) // no skewing { if (attachtobottom) texturevpeg -= *rover->topheight - *rover->bottomheight; - wallVerts[3].t = (*rover->topheight - h + texturevpeg) * grTex->scaleY; - wallVerts[2].t = (*rover->topheight - hS + texturevpeg) * grTex->scaleY; - wallVerts[0].t = (*rover->topheight - l + texturevpeg) * grTex->scaleY; - wallVerts[1].t = (*rover->topheight - lS + texturevpeg) * grTex->scaleY; + wallVerts[3].t = (*rover->topheight - h + texturevpeg) * glTex->scaleY; + wallVerts[2].t = (*rover->topheight - hS + texturevpeg) * glTex->scaleY; + wallVerts[0].t = (*rover->topheight - l + texturevpeg) * glTex->scaleY; + wallVerts[1].t = (*rover->topheight - lS + texturevpeg) * glTex->scaleY; } else { if (!attachtobottom) // skew by top { - wallVerts[3].t = wallVerts[2].t = texturevpeg * grTex->scaleY; - wallVerts[0].t = (h - l + texturevpeg) * grTex->scaleY; - wallVerts[1].t = (hS - lS + texturevpeg) * grTex->scaleY; + wallVerts[3].t = wallVerts[2].t = texturevpeg * glTex->scaleY; + wallVerts[0].t = (h - l + texturevpeg) * glTex->scaleY; + wallVerts[1].t = (hS - lS + texturevpeg) * glTex->scaleY; } else // skew by bottom { - wallVerts[0].t = wallVerts[1].t = texturevpeg * grTex->scaleY; - wallVerts[3].t = wallVerts[0].t - (h - l) * grTex->scaleY; - wallVerts[2].t = wallVerts[1].t - (hS - lS) * grTex->scaleY; + wallVerts[0].t = wallVerts[1].t = texturevpeg * glTex->scaleY; + wallVerts[3].t = wallVerts[0].t - (h - l) * glTex->scaleY; + wallVerts[2].t = wallVerts[1].t - (hS - lS) * glTex->scaleY; } } - wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; + wallVerts[0].s = wallVerts[3].s = cliplow * glTex->scaleX; + wallVerts[2].s = wallVerts[1].s = cliphigh * glTex->scaleX; } if (rover->flags & FF_FOG) { @@ -2120,12 +1924,13 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom lightnum = rover->master->frontsector->lightlevel; colormap = rover->master->frontsector->extra_colormap; - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gr_curline); - Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(rover->master->frontsector->lightlevel, rover->master->frontsector->extra_colormap); + Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(lightnum, colormap); - if (gr_frontsector->numlights) - HWR_SplitWall(gr_frontsector, wallVerts, 0, false, &Surf, rover->flags, rover, 0); + lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); + + if (gl_frontsector->numlights) + HWR_SplitWall(gl_frontsector, wallVerts, 0, false, &Surf, rover->flags, rover, 0); else HWR_AddTransparentWall(wallVerts, &Surf, 0, false, blendmode, true, lightnum, colormap); } @@ -2139,12 +1944,12 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom Surf.PolyColor.s.alpha = CLAMP(rover->alpha, 0, 255); } - if (gr_frontsector->numlights) - HWR_SplitWall(gr_frontsector, wallVerts, texnum, noencore, &Surf, rover->flags, rover, 0); + if (gl_frontsector->numlights) + HWR_SplitWall(gl_frontsector, wallVerts, texnum, noencore, &Surf, rover->flags, rover, 0); else { if (blendmode != PF_Masked) - HWR_AddTransparentWall(wallVerts, &Surf, texnum, gr_linedef->flags & ML_TFERLINE, blendmode, false, lightnum, colormap); + HWR_AddTransparentWall(wallVerts, &Surf, texnum, noencore, blendmode, false, lightnum, colormap); else HWR_ProjectWall(wallVerts, &Surf, PF_Masked, lightnum, colormap); } @@ -2152,9 +1957,9 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom } } - if (gr_frontsector->ffloors) // Putting this seperate should allow 2 FOF sectors to be connected without too many errors? I think? + if (gl_frontsector->ffloors) // Putting this seperate should allow 2 FOF sectors to be connected without too many errors? I think? { - for (rover = gr_frontsector->ffloors; rover; rover = rover->next) + for (rover = gl_frontsector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERSIDES) || !(rover->flags & FF_ALLSIDES)) continue; @@ -2169,7 +1974,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom if (rover->master->flags & ML_TFERLINE) { - size_t linenum = min((size_t)(gr_curline->linedef-gr_backsector->lines[0]), rover->master->frontsector->linecount); + size_t linenum = min((size_t)(gl_curline->linedef-gl_backsector->lines[0]), rover->master->frontsector->linecount); newline = rover->master->frontsector->lines[0] + linenum; texnum = R_GetTextureNum(sides[newline->sidenum[0]].midtexture); } @@ -2190,7 +1995,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom l = lowcut; lS = lowcutslope; } - + //Hurdler: HW code starts here //FIXME: check if peging is correct // set top/bottom coords @@ -2209,21 +2014,21 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom } else { - grTex = HWR_GetTexture(texnum, noencore); + glTex = HWR_GetTexture(texnum, noencore); if (newline) { - wallVerts[3].t = wallVerts[2].t = (*rover->topheight - h + sides[newline->sidenum[0]].rowoffset) * grTex->scaleY; - wallVerts[0].t = wallVerts[1].t = (h - l + (*rover->topheight - h + sides[newline->sidenum[0]].rowoffset)) * grTex->scaleY; + wallVerts[3].t = wallVerts[2].t = (*rover->topheight - h + sides[newline->sidenum[0]].rowoffset) * glTex->scaleY; + wallVerts[0].t = wallVerts[1].t = (h - l + (*rover->topheight - h + sides[newline->sidenum[0]].rowoffset)) * glTex->scaleY; } else { - wallVerts[3].t = wallVerts[2].t = (*rover->topheight - h + sides[rover->master->sidenum[0]].rowoffset) * grTex->scaleY; - wallVerts[0].t = wallVerts[1].t = (h - l + (*rover->topheight - h + sides[rover->master->sidenum[0]].rowoffset)) * grTex->scaleY; + wallVerts[3].t = wallVerts[2].t = (*rover->topheight - h + sides[rover->master->sidenum[0]].rowoffset) * glTex->scaleY; + wallVerts[0].t = wallVerts[1].t = (h - l + (*rover->topheight - h + sides[rover->master->sidenum[0]].rowoffset)) * glTex->scaleY; } - wallVerts[0].s = wallVerts[3].s = cliplow * grTex->scaleX; - wallVerts[2].s = wallVerts[1].s = cliphigh * grTex->scaleX; + wallVerts[0].s = wallVerts[3].s = cliplow * glTex->scaleX; + wallVerts[2].s = wallVerts[1].s = cliphigh * glTex->scaleX; } if (rover->flags & FF_FOG) @@ -2234,12 +2039,13 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom lightnum = rover->master->frontsector->lightlevel; colormap = rover->master->frontsector->extra_colormap; - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gr_curline); - Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(rover->master->frontsector->lightlevel, rover->master->frontsector->extra_colormap); + Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(lightnum, colormap); - if (gr_backsector->numlights) - HWR_SplitWall(gr_backsector, wallVerts, 0, false, &Surf, rover->flags, rover, 0); + lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); + + if (gl_backsector->numlights) + HWR_SplitWall(gl_backsector, wallVerts, 0, false, &Surf, rover->flags, rover, 0); else HWR_AddTransparentWall(wallVerts, &Surf, 0, false, blendmode, true, lightnum, colormap); } @@ -2253,8 +2059,8 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom Surf.PolyColor.s.alpha = CLAMP(rover->alpha, 0, 255); } - if (gr_backsector->numlights) - HWR_SplitWall(gr_backsector, wallVerts, texnum, noencore, &Surf, rover->flags, rover, 0); + if (gl_backsector->numlights) + HWR_SplitWall(gl_backsector, wallVerts, texnum, noencore, &Surf, rover->flags, rover, 0); else { if (blendmode != PF_Masked) @@ -2288,28 +2094,28 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector) if (afrontsector->f_slope || afrontsector->c_slope || abacksector->f_slope || abacksector->c_slope) { fixed_t v1x, v1y, v2x, v2y; // the seg's vertexes as fixed_t - - if (gr_curline->pv1) + + if (gl_curline->pv1) { - v1x = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv1)->x); - v1y = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv1)->y); + v1x = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv1)->x); + v1y = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv1)->y); } else { - v1x = gr_curline->v1->x; - v1y = gr_curline->v1->y; + v1x = gl_curline->v1->x; + v1y = gl_curline->v1->y; } - if (gr_curline->pv2) + if (gl_curline->pv2) { - v2x = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv2)->x); - v2y = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv2)->y); + v2x = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv2)->x); + v2y = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv2)->y); } else { - v2x = gr_curline->v2->x; - v2y = gr_curline->v2->y; + v2x = gl_curline->v2->x; + v2y = gl_curline->v2->y; } - + #define SLOPEPARAMS(slope, end1, end2, normalheight) \ if (slope) { \ end1 = P_GetZAt(slope, v1x, v1y); \ @@ -2337,8 +2143,6 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector) fixed_t viewf1, viewf2, viewc1, viewc2; if (afrontsector == viewsector) { - //if (printportals) - // CONS_Printf("CheckClip frontsector is viewsector\n"); viewf1 = frontf1; viewf2 = frontf2; viewc1 = frontc1; @@ -2346,8 +2150,6 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector) } else { - //if (printportals) - // CONS_Printf("CheckClip backsector is viewsector\n"); viewf1 = backf1; viewf2 = backf2; viewc1 = backc1; @@ -2432,27 +2234,27 @@ static void HWR_AddLine(seg_t *line) if (line->polyseg && !(line->polyseg->flags & POF_RENDERSIDES)) return; - gr_curline = line; + gl_curline = line; - if (gr_curline->pv1) + if (gl_curline->pv1) { - v1x = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv1)->x); - v1y = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv1)->y); + v1x = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv1)->x); + v1y = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv1)->y); } else { - v1x = gr_curline->v1->x; - v1y = gr_curline->v1->y; + v1x = gl_curline->v1->x; + v1y = gl_curline->v1->y; } - if (gr_curline->pv2) + if (gl_curline->pv2) { - v2x = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv2)->x); - v2y = FLOAT_TO_FIXED(((polyvertex_t *)gr_curline->pv2)->y); + v2x = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv2)->x); + v2y = FLOAT_TO_FIXED(((polyvertex_t *)gl_curline->pv2)->y); } else { - v2x = gr_curline->v2->x; - v2y = gr_curline->v2->y; + v2x = gl_curline->v2->x; + v2y = gl_curline->v2->y; } // OPTIMIZE: quickly reject orthogonal back sides. @@ -2460,7 +2262,7 @@ static void HWR_AddLine(seg_t *line) angle2 = R_PointToAngle64(v2x, v2y); // PrBoom: Back side, i.e. backface culling - read: endAngle >= startAngle! - if (angle2 - angle1 < ANGLE_180 || !gr_curline->linedef) + if (angle2 - angle1 < ANGLE_180 || !gl_curline->linedef) return; // PrBoom: use REAL clipping math YAYYYYYYY!!! @@ -2469,7 +2271,7 @@ static void HWR_AddLine(seg_t *line) checkforemptylines = true; - gr_backsector = line->backsector; + gl_backsector = line->backsector; // do extra checks on the seg when rendering portals: // don't render segs that are behind the portal destination line @@ -2480,7 +2282,7 @@ static void HWR_AddLine(seg_t *line) return; } - if (gr_portal == GRPORTAL_STENCIL || gr_portal == GRPORTAL_DEPTH) + if (gl_portal_state == GLPORTAL_STENCIL || gl_portal_state == GLPORTAL_DEPTH) goto doaddline; if (line->linedef->special == 40) @@ -2489,13 +2291,15 @@ static void HWR_AddLine(seg_t *line) { // Find the other side! INT32 line2 = P_FindSpecialLineFromTag(40, line->linedef->tag, -1); + if (line->linedef == &lines[line2]) line2 = P_FindSpecialLineFromTag(40, line->linedef->tag, line2); + if (line2 >= 0) // found it! { - if (gr_portal == GRPORTAL_SEARCH) + if (gl_portal_state == GLPORTAL_SEARCH) HWR_Portal_Add2Lines(line->linedef-lines, line2, line); - else if (gr_portal == GRPORTAL_INSIDE) + else if (gl_portal_state == GLPORTAL_INSIDE) dont_draw = true; } } @@ -2511,9 +2315,9 @@ doaddline: } else { - gr_backsector = R_FakeFlat(gr_backsector, &tempsec, NULL, NULL, true); + gl_backsector = R_FakeFlat(gl_backsector, &tempsec, NULL, NULL, true); - if (CheckClip(gr_frontsector, gr_backsector)) + if (CheckClip(gl_frontsector, gl_backsector)) { gld_clipper_SafeAddClipRange(angle2, angle1); checkforemptylines = false; @@ -2523,11 +2327,11 @@ doaddline: // Identical floor and ceiling on both sides, // identical light levels on both sides, // and no middle texture. - if (checkforemptylines && R_IsEmptyLine(line, gr_frontsector, gr_backsector)) + if (checkforemptylines && R_IsEmptyLine(line, gl_frontsector, gl_backsector)) return; } - if (gr_portal != GRPORTAL_SEARCH && !dont_draw)// no need to do this during the portal check + if (gl_portal_state != GLPORTAL_SEARCH && !dont_draw)// no need to do this during the portal check HWR_ProcessSeg(); // Doesn't need arguments because they're defined globally :D return; @@ -2663,30 +2467,28 @@ static inline void HWR_AddPolyObjectSegs(void) } } -void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, FBITFIELD blendmode, UINT8 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap) +static void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, FBITFIELD blendmode, UINT8 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap) { float height; //constant y for all points on the convex flat polygon FOutVector *v3d; - INT32 i; + INT32 i; float flatxref,flatyref; - float fflatsize; - INT32 flatflag; - size_t len; - float scrollx = 0.0f, scrolly = 0.0f; - angle_t angle = 0; + float fflatsize; + INT32 flatflag; + size_t len; + float scrollx = 0.0f, scrolly = 0.0f; + angle_t angle = 0; FSurfaceInfo Surf; - fixed_t tempxsow, tempytow; - size_t nrPlaneVerts; + fixed_t tempxsow, tempytow; + size_t nrPlaneVerts; static FOutVector *planeVerts = NULL; static UINT16 numAllocedPlaneVerts = 0; - + INT32 shader = SHADER_NONE; nrPlaneVerts = polysector->numVertices; - height = FIXED_TO_FLOAT(fixedheight); - if (nrPlaneVerts < 3) //not even a triangle ? return; @@ -2704,6 +2506,8 @@ void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t Z_Malloc(numAllocedPlaneVerts * sizeof (FOutVector), PU_LEVEL, &planeVerts); } + height = FIXED_TO_FLOAT(fixedheight); + len = W_LumpLength(lumpnum); switch (len) @@ -2763,19 +2567,19 @@ void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t angle = FOFsector->ceilingpic_angle>>ANGLETOFINESHIFT; } } - else if (gr_frontsector) + else if (gl_frontsector) { if (!isceiling) // it's a floor { - scrollx = FIXED_TO_FLOAT(gr_frontsector->floor_xoffs)/fflatsize; - scrolly = FIXED_TO_FLOAT(gr_frontsector->floor_yoffs)/fflatsize; - angle = gr_frontsector->floorpic_angle>>ANGLETOFINESHIFT; + scrollx = FIXED_TO_FLOAT(gl_frontsector->floor_xoffs)/fflatsize; + scrolly = FIXED_TO_FLOAT(gl_frontsector->floor_yoffs)/fflatsize; + angle = gl_frontsector->floorpic_angle>>ANGLETOFINESHIFT; } else // it's a ceiling { - scrollx = FIXED_TO_FLOAT(gr_frontsector->ceiling_xoffs)/fflatsize; - scrolly = FIXED_TO_FLOAT(gr_frontsector->ceiling_yoffs)/fflatsize; - angle = gr_frontsector->ceilingpic_angle>>ANGLETOFINESHIFT; + scrollx = FIXED_TO_FLOAT(gl_frontsector->ceiling_xoffs)/fflatsize; + scrolly = FIXED_TO_FLOAT(gl_frontsector->ceiling_yoffs)/fflatsize; + angle = gl_frontsector->ceilingpic_angle>>ANGLETOFINESHIFT; } } @@ -2826,11 +2630,11 @@ void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t blendmode |= PF_Masked|PF_Modulated; if (HWR_UseShader()) - { + { shader = SHADER_FLOOR; blendmode |= PF_ColorMapped; } - + HWR_ProcessPolygon(&Surf, planeVerts, nrPlaneVerts, blendmode, shader, false); } @@ -2853,11 +2657,11 @@ static void HWR_AddPolyObjectPlanes(void) if (po_ptrs[i]->translucency >= NUMTRANSMAPS) continue; - if (polyobjsector->floorheight <= gr_frontsector->ceilingheight - && polyobjsector->floorheight >= gr_frontsector->floorheight + if (polyobjsector->floorheight <= gl_frontsector->ceilingheight + && polyobjsector->floorheight >= gl_frontsector->floorheight && (viewz < polyobjsector->floorheight)) { - light = R_GetPlaneLight(gr_frontsector, polyobjsector->floorheight, true); + light = R_GetPlaneLight(gl_frontsector, polyobjsector->floorheight, true); if (po_ptrs[i]->translucency > 0) { FSurfaceInfo Surf; @@ -2865,22 +2669,22 @@ static void HWR_AddPolyObjectPlanes(void) memset(&Surf, 0x00, sizeof(Surf)); blendmode = HWR_TranstableToAlpha(po_ptrs[i]->translucency, &Surf); HWR_AddTransparentPolyobjectFloor(levelflats[polyobjsector->floorpic].lumpnum, po_ptrs[i], false, polyobjsector->floorheight, - (light == -1 ? gr_frontsector->lightlevel : *gr_frontsector->lightlist[light].lightlevel), Surf.PolyColor.s.alpha, polyobjsector, blendmode, (light == -1 ? gr_frontsector->extra_colormap : gr_frontsector->lightlist[light].extra_colormap)); + (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), Surf.PolyColor.s.alpha, polyobjsector, blendmode, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); } else { HWR_GetFlat(levelflats[polyobjsector->floorpic].lumpnum, R_NoEncore(polyobjsector, false)); HWR_RenderPolyObjectPlane(po_ptrs[i], false, polyobjsector->floorheight, PF_Occlude, - (light == -1 ? gr_frontsector->lightlevel : *gr_frontsector->lightlist[light].lightlevel), levelflats[polyobjsector->floorpic].lumpnum, - polyobjsector, 255, (light == -1 ? gr_frontsector->extra_colormap : gr_frontsector->lightlist[light].extra_colormap)); + (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), levelflats[polyobjsector->floorpic].lumpnum, + polyobjsector, 255, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); } } - if (polyobjsector->ceilingheight >= gr_frontsector->floorheight - && polyobjsector->ceilingheight <= gr_frontsector->ceilingheight + if (polyobjsector->ceilingheight >= gl_frontsector->floorheight + && polyobjsector->ceilingheight <= gl_frontsector->ceilingheight && (viewz > polyobjsector->ceilingheight)) { - light = R_GetPlaneLight(gr_frontsector, polyobjsector->ceilingheight, true); + light = R_GetPlaneLight(gl_frontsector, polyobjsector->ceilingheight, true); if (po_ptrs[i]->translucency > 0) { FSurfaceInfo Surf; @@ -2888,20 +2692,19 @@ static void HWR_AddPolyObjectPlanes(void) memset(&Surf, 0x00, sizeof(Surf)); blendmode = HWR_TranstableToAlpha(po_ptrs[i]->translucency, &Surf); HWR_AddTransparentPolyobjectFloor(levelflats[polyobjsector->ceilingpic].lumpnum, po_ptrs[i], true, polyobjsector->ceilingheight, - (light == -1 ? gr_frontsector->lightlevel : *gr_frontsector->lightlist[light].lightlevel), Surf.PolyColor.s.alpha, polyobjsector, blendmode, (light == -1 ? gr_frontsector->extra_colormap : gr_frontsector->lightlist[light].extra_colormap)); + (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), Surf.PolyColor.s.alpha, polyobjsector, blendmode, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); } else { HWR_GetFlat(levelflats[polyobjsector->ceilingpic].lumpnum, R_NoEncore(polyobjsector, true)); HWR_RenderPolyObjectPlane(po_ptrs[i], true, polyobjsector->ceilingheight, PF_Occlude, - (light == -1 ? gr_frontsector->lightlevel : *gr_frontsector->lightlist[light].lightlevel), levelflats[polyobjsector->ceilingpic].lumpnum, - polyobjsector, 255, (light == -1 ? gr_frontsector->extra_colormap : gr_frontsector->lightlist[light].extra_colormap)); + (light == -1 ? gl_frontsector->lightlevel : *gl_frontsector->lightlist[light].lightlevel), levelflats[polyobjsector->ceilingpic].lumpnum, + polyobjsector, 255, (light == -1 ? gl_frontsector->extra_colormap : gl_frontsector->lightlist[light].extra_colormap)); } } } } - // // HWR_DoCulling // Hardware version of R_DoCulling @@ -2914,6 +2717,7 @@ static boolean HWR_DoCulling(line_t *cullheight, line_t *viewcullheight, float v return false; cullplane = FIXED_TO_FLOAT(cullheight->frontsector->floorheight); + if (cullheight->flags & ML_NOCLIMB) // Group culling { if (!viewcullheight) @@ -2942,6 +2746,29 @@ static boolean HWR_DoCulling(line_t *cullheight, line_t *viewcullheight, float v return false; } +static inline void HWR_PortalSubsector(seg_t *line, subsector_t *sub, INT16 count) +{ + if (line) + { + //Hurdler: at this point validcount must be the same, but is not because + // gl_frontsector doesn't point anymore to sub->sector due to + // the call gl_frontsector = R_FakeFlat(...) + // if it's not done, the sprite is drawn more than once, + // what looks really bad with translucency or dynamic light, + // without talking about the overdraw of course. + sub->sector->validcount = validcount;/// \todo fix that in a better way + + while (count--) + { + if (!line->polyseg) // ignore segs that belong to polyobjects + HWR_AddLine(line); + line++; + } + } + + sub->validcount = validcount; +} + // -----------------+ // HWR_Subsector : Determine floor/ceiling planes. // : Add sprites of things in sector. @@ -2961,7 +2788,6 @@ static void HWR_Subsector(size_t num) extracolormap_t *floorcolormap; extracolormap_t *ceilingcolormap; ffloor_t *rover; - boolean skipSprites = false; #ifdef PARANOIA //no risk while developing, enough debugging nights! if (num >= addsubsector) @@ -2974,7 +2800,7 @@ static void HWR_Subsector(size_t num) // subsector sub = &subsectors[num]; // sector - gr_frontsector = sub->sector; + gl_frontsector = sub->sector; // how many linedefs count = sub->numlines; // first line seg @@ -2984,35 +2810,35 @@ static void HWR_Subsector(size_t num) { // there are no segs but only planes sub = &subsectors[0]; - gr_frontsector = sub->sector; + gl_frontsector = sub->sector; count = 0; line = NULL; } //SoM: 4/7/2000: Test to make Boom water work in Hardware mode. - gr_frontsector = R_FakeFlat(gr_frontsector, &tempsec, &floorlightlevel, + gl_frontsector = R_FakeFlat(gl_frontsector, &tempsec, &floorlightlevel, &ceilinglightlevel, false); - if (gr_portal == GRPORTAL_SEARCH) + if (gl_portal_state == GLPORTAL_SEARCH) { - skipSprites = true; - goto skip_stuff_for_portals;// hopefully this goto is okay + HWR_PortalSubsector(line, sub, count); + return; } - floorcolormap = ceilingcolormap = gr_frontsector->extra_colormap; + floorcolormap = ceilingcolormap = gl_frontsector->extra_colormap; - cullFloorHeight = P_GetSectorFloorZAt (gr_frontsector, viewx, viewy); - cullCeilingHeight = P_GetSectorCeilingZAt(gr_frontsector, viewx, viewy); - locFloorHeight = P_GetSectorFloorZAt (gr_frontsector, gr_frontsector->soundorg.x, gr_frontsector->soundorg.y); - locCeilingHeight = P_GetSectorCeilingZAt(gr_frontsector, gr_frontsector->soundorg.x, gr_frontsector->soundorg.y); + cullFloorHeight = P_GetSectorFloorZAt (gl_frontsector, viewx, viewy); + cullCeilingHeight = P_GetSectorCeilingZAt(gl_frontsector, viewx, viewy); + locFloorHeight = P_GetSectorFloorZAt (gl_frontsector, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); + locCeilingHeight = P_GetSectorCeilingZAt(gl_frontsector, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); - if (gr_frontsector->ffloors) + if (gl_frontsector->ffloors) { - boolean anyMoved = gr_frontsector->moved; + boolean anyMoved = gl_frontsector->moved; if (anyMoved == false) { - for (rover = gr_frontsector->ffloors; rover; rover = rover->next) + for (rover = gl_frontsector->ffloors; rover; rover = rover->next) { sector_t *controlSec = §ors[rover->secnum]; @@ -3026,64 +2852,64 @@ static void HWR_Subsector(size_t num) if (anyMoved == true) { - gr_frontsector->numlights = sub->sector->numlights = 0; - R_Prep3DFloors(gr_frontsector); - sub->sector->lightlist = gr_frontsector->lightlist; - sub->sector->numlights = gr_frontsector->numlights; - sub->sector->moved = gr_frontsector->moved = false; + gl_frontsector->numlights = sub->sector->numlights = 0; + R_Prep3DFloors(gl_frontsector); + sub->sector->lightlist = gl_frontsector->lightlist; + sub->sector->numlights = gl_frontsector->numlights; + sub->sector->moved = gl_frontsector->moved = false; } - light = R_GetPlaneLight(gr_frontsector, locFloorHeight, false); - if (gr_frontsector->floorlightsec == -1) - floorlightlevel = *gr_frontsector->lightlist[light].lightlevel; - floorcolormap = gr_frontsector->lightlist[light].extra_colormap; + light = R_GetPlaneLight(gl_frontsector, locFloorHeight, false); + if (gl_frontsector->floorlightsec == -1) + floorlightlevel = *gl_frontsector->lightlist[light].lightlevel; + floorcolormap = gl_frontsector->lightlist[light].extra_colormap; - light = R_GetPlaneLight(gr_frontsector, locCeilingHeight, false); - if (gr_frontsector->ceilinglightsec == -1) - ceilinglightlevel = *gr_frontsector->lightlist[light].lightlevel; - ceilingcolormap = gr_frontsector->lightlist[light].extra_colormap; + light = R_GetPlaneLight(gl_frontsector, locCeilingHeight, false); + if (gl_frontsector->ceilinglightsec == -1) + ceilinglightlevel = *gl_frontsector->lightlist[light].lightlevel; + ceilingcolormap = gl_frontsector->lightlist[light].extra_colormap; } - sub->sector->extra_colormap = gr_frontsector->extra_colormap; + sub->sector->extra_colormap = gl_frontsector->extra_colormap; // render floor ? // yeah, easy backface cull! :) if (cullFloorHeight < viewz) { - if (gr_frontsector->floorpic != skyflatnum) + if (gl_frontsector->floorpic != skyflatnum) { if (sub->validcount != validcount) { - HWR_GetFlat(levelflats[gr_frontsector->floorpic].lumpnum, R_NoEncore(gr_frontsector, false)); + HWR_GetFlat(levelflats[gl_frontsector->floorpic].lumpnum, R_NoEncore(gl_frontsector, false)); HWR_RenderPlane(sub, &extrasubsectors[num], false, // Hack to make things continue to work around slopes. - locFloorHeight == cullFloorHeight ? locFloorHeight : gr_frontsector->floorheight, + locFloorHeight == cullFloorHeight ? locFloorHeight : gl_frontsector->floorheight, // We now return you to your regularly scheduled rendering. - PF_Occlude, floorlightlevel, levelflats[gr_frontsector->floorpic].lumpnum, NULL, 255, floorcolormap); + PF_Occlude, floorlightlevel, levelflats[gl_frontsector->floorpic].lumpnum, NULL, 255, floorcolormap); } } } if (cullCeilingHeight > viewz) { - if (gr_frontsector->ceilingpic != skyflatnum) + if (gl_frontsector->ceilingpic != skyflatnum) { if (sub->validcount != validcount) { - HWR_GetFlat(levelflats[gr_frontsector->ceilingpic].lumpnum, R_NoEncore(gr_frontsector, true)); + HWR_GetFlat(levelflats[gl_frontsector->ceilingpic].lumpnum, R_NoEncore(gl_frontsector, true)); HWR_RenderPlane(sub, &extrasubsectors[num], true, // Hack to make things continue to work around slopes. - locCeilingHeight == cullCeilingHeight ? locCeilingHeight : gr_frontsector->ceilingheight, + locCeilingHeight == cullCeilingHeight ? locCeilingHeight : gl_frontsector->ceilingheight, // We now return you to your regularly scheduled rendering. - PF_Occlude, ceilinglightlevel, levelflats[gr_frontsector->ceilingpic].lumpnum,NULL, 255, ceilingcolormap); + PF_Occlude, ceilinglightlevel, levelflats[gl_frontsector->ceilingpic].lumpnum,NULL, 255, ceilingcolormap); } } } - if (gr_frontsector->ffloors) + if (gl_frontsector->ffloors) { /// \todo fix light, xoffs, yoffs, extracolormap ? - for (rover = gr_frontsector->ffloors; + for (rover = gl_frontsector->ffloors; rover; rover = rover->next) { fixed_t bottomCullHeight, topCullHeight, centerHeight; @@ -3092,20 +2918,20 @@ static void HWR_Subsector(size_t num) continue; if (sub->validcount == validcount) continue; - + // rendering heights for bottom and top planes // yes there were functions for this stuff, no idea why it wasnt used but bleh bottomCullHeight = P_GetFFloorBottomZAt(rover, viewx, viewy); topCullHeight = P_GetFFloorTopZAt(rover, viewx, viewy); - if (gr_frontsector->cullheight) + if (gl_frontsector->cullheight) { - if (HWR_DoCulling(gr_frontsector->cullheight, viewsector->cullheight, gr_viewz, FIXED_TO_FLOAT(*rover->bottomheight), FIXED_TO_FLOAT(*rover->topheight))) + if (HWR_DoCulling(gl_frontsector->cullheight, viewsector->cullheight, gl_viewz, FIXED_TO_FLOAT(*rover->bottomheight), FIXED_TO_FLOAT(*rover->topheight))) continue; } // bottom plane - centerHeight = P_GetFFloorBottomZAt(rover, gr_frontsector->soundorg.x, gr_frontsector->soundorg.y); + centerHeight = P_GetFFloorBottomZAt(rover, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); if (centerHeight <= locCeilingHeight && centerHeight >= locFloorHeight && ((viewz < bottomCullHeight && !(rover->flags & FF_INVERTPLANES)) || @@ -3115,40 +2941,42 @@ static void HWR_Subsector(size_t num) { UINT8 alpha; - light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < bottomCullHeight ? true : false); + light = R_GetPlaneLight(gl_frontsector, centerHeight, viewz < bottomCullHeight ? true : false); - alpha = HWR_FogBlockAlpha(*gr_frontsector->lightlist[light].lightlevel, rover->master->frontsector->extra_colormap); + alpha = HWR_FogBlockAlpha(*gl_frontsector->lightlist[light].lightlevel, rover->master->frontsector->extra_colormap); HWR_AddTransparentFloor(0, &extrasubsectors[num], false, *rover->bottomheight, - *gr_frontsector->lightlist[light].lightlevel, + *gl_frontsector->lightlist[light].lightlevel, alpha, rover->master->frontsector, PF_Fog|PF_NoTexture, true, rover->master->frontsector->extra_colormap); } else if (rover->flags & FF_TRANSLUCENT && rover->alpha < 256) // SoM: Flags are more efficient { - light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < bottomCullHeight ? true : false); + light = R_GetPlaneLight(gl_frontsector, centerHeight, viewz < bottomCullHeight ? true : false); + HWR_AddTransparentFloor(levelflats[*rover->bottompic].lumpnum, &extrasubsectors[num], false, *rover->bottomheight, - *gr_frontsector->lightlist[light].lightlevel, + *gl_frontsector->lightlist[light].lightlevel, CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Translucent, - false, gr_frontsector->lightlist[light].extra_colormap); + false, gl_frontsector->lightlist[light].extra_colormap); } else { - HWR_GetFlat(levelflats[*rover->bottompic].lumpnum, R_NoEncore(gr_frontsector, false)); - light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < bottomCullHeight ? true : false); - HWR_RenderPlane(sub, &extrasubsectors[num], false, *rover->bottomheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gr_frontsector->lightlist[light].lightlevel, levelflats[*rover->bottompic].lumpnum, - rover->master->frontsector, 255, gr_frontsector->lightlist[light].extra_colormap); + HWR_GetFlat(levelflats[*rover->bottompic].lumpnum, R_NoEncore(gl_frontsector, false)); + light = R_GetPlaneLight(gl_frontsector, centerHeight, viewz < bottomCullHeight ? true : false); + + HWR_RenderPlane(sub, &extrasubsectors[num], false, *rover->bottomheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gl_frontsector->lightlist[light].lightlevel, levelflats[*rover->bottompic].lumpnum, + rover->master->frontsector, 255, gl_frontsector->lightlist[light].extra_colormap); } } // top plane - centerHeight = P_GetFFloorTopZAt(rover, gr_frontsector->soundorg.x, gr_frontsector->soundorg.y); + centerHeight = P_GetFFloorTopZAt(rover, gl_frontsector->soundorg.x, gl_frontsector->soundorg.y); if (centerHeight >= locFloorHeight && centerHeight <= locCeilingHeight && @@ -3159,35 +2987,37 @@ static void HWR_Subsector(size_t num) { UINT8 alpha; - light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < topCullHeight ? true : false); + light = R_GetPlaneLight(gl_frontsector, centerHeight, viewz < topCullHeight ? true : false); - alpha = HWR_FogBlockAlpha(*gr_frontsector->lightlist[light].lightlevel, rover->master->frontsector->extra_colormap); + alpha = HWR_FogBlockAlpha(*gl_frontsector->lightlist[light].lightlevel, rover->master->frontsector->extra_colormap); HWR_AddTransparentFloor(0, &extrasubsectors[num], true, *rover->topheight, - *gr_frontsector->lightlist[light].lightlevel, + *gl_frontsector->lightlist[light].lightlevel, alpha, rover->master->frontsector, PF_Fog|PF_NoTexture, true, rover->master->frontsector->extra_colormap); } else if (rover->flags & FF_TRANSLUCENT && rover->alpha < 256) { - light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < topCullHeight ? true : false); + light = R_GetPlaneLight(gl_frontsector, centerHeight, viewz < topCullHeight ? true : false); + HWR_AddTransparentFloor(levelflats[*rover->toppic].lumpnum, &extrasubsectors[num], true, *rover->topheight, - *gr_frontsector->lightlist[light].lightlevel, + *gl_frontsector->lightlist[light].lightlevel, CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Translucent, - false, gr_frontsector->lightlist[light].extra_colormap); + false, gl_frontsector->lightlist[light].extra_colormap); } else { - HWR_GetFlat(levelflats[*rover->toppic].lumpnum, R_NoEncore(gr_frontsector, true)); - light = R_GetPlaneLight(gr_frontsector, centerHeight, viewz < topCullHeight ? true : false); - HWR_RenderPlane(sub, &extrasubsectors[num], true, *rover->topheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gr_frontsector->lightlist[light].lightlevel, levelflats[*rover->toppic].lumpnum, - rover->master->frontsector, 255, gr_frontsector->lightlist[light].extra_colormap); + HWR_GetFlat(levelflats[*rover->toppic].lumpnum, R_NoEncore(gl_frontsector, true)); + light = R_GetPlaneLight(gl_frontsector, centerHeight, viewz < topCullHeight ? true : false); + + HWR_RenderPlane(sub, &extrasubsectors[num], true, *rover->topheight, (rover->flags & FF_RIPPLE ? PF_Ripple : 0)|PF_Occlude, *gl_frontsector->lightlist[light].lightlevel, levelflats[*rover->toppic].lumpnum, + rover->master->frontsector, 255, gl_frontsector->lightlist[light].extra_colormap); } } } @@ -3223,22 +3053,19 @@ static void HWR_Subsector(size_t num) } } -skip_stuff_for_portals: - -// Hurder ici se passe les choses INT32�essantes! -// on vient de tracer le sol et le plafond -// on trace �pr�ent d'abord les sprites et ensuite les murs -// hurdler: faux: on ajoute seulement les sprites, le murs sont trac� d'abord + // Hurdler: here interesting things are happening! + // we have just drawn the floor and ceiling + // we now draw the sprites first and then the walls + // hurdler: false: we only add the sprites, the walls are drawn first if (line) { // draw sprites first, coz they are clipped to the solidsegs of // subsectors more 'in front' - if (!skipSprites) - HWR_AddSprites(gr_frontsector); + HWR_AddSprites(gl_frontsector); //Hurdler: at this point validcount must be the same, but is not because - // gr_frontsector doesn't point anymore to sub->sector due to - // the call gr_frontsector = R_FakeFlat(...) + // gl_frontsector doesn't point anymore to sub->sector due to + // the call gl_frontsector = R_FakeFlat(...) // if it's not done, the sprite is drawn more than once, // what looks really bad with translucency or dynamic light, // without talking about the overdraw of course. @@ -3247,7 +3074,7 @@ skip_stuff_for_portals: while (count--) { if (!line->polyseg) // ignore segs that belong to polyobjects - HWR_AddLine(line); + HWR_AddLine(line); line++; } } @@ -3255,60 +3082,6 @@ skip_stuff_for_portals: sub->validcount = validcount; } -// idea for fixing fakery map: one portal pillar works, 2 pillars have left/right bug wall, 1 pillar has both sides bugged. -// bounding box is probably right on the edge, maybe could check for this with P_ClosestPointOnLine -// so: for each side check, if it passes then also check distance to line, -// if its zero (or very close?) then dont return true, instead continue to next side check -// it helped with center pillars! but other parts still have issues, probably because some of bounding box is on correct side. - -// idea for further clipping improvement: -// have a separate xyz coordinate for portal view side checking: one that is derived by moving the viewxyz forward -// the new coords would be at the intersection of line_a and line_b, where -// line_a = line of view, pointing forward from the center of the camera -// line_b = a line orthogonal to line_a, defined so that the nearest vertex of portalclipline lies within it -// maybe if the seg to be drawn has these new coords on one side and the normal viewxyz on the other side then it can be culled? - -// looks like P_Thrust in p_user.c has code for moving point forward towards a direction -// maybe P_InterceptVector could be used for intersect point -// use returned value as multiplier for the added values from p_thrust thing -// P_InterceptVector needs divlines which need dx and dy, dx=x2-x1 dy=y2-y1 - -// returns true if the point is on the correct (viewable) side of the -// portal destination line -static boolean HWR_PortalCheckPointSide(fixed_t x, fixed_t y) -{ - // we are checking if the point is on the viewable side of the portal exit. - // being exactly on the portal exit line is not enough to pass the test. - // P_PointOnLineSide could behave differently from this expectation on this case, - // so first check if the point is precisely on the line, and then if not, check the side. - - vertex_t closest_point; - P_ClosestPointOnLine(x, y, portalclipline, &closest_point); - if (closest_point.x != x || closest_point.y != y) - { - if (P_PointOnLineSide(x, y, portalclipline) != 1) - return true; - } - return false; -} - -static boolean HWR_PortalCheckBBox(const fixed_t *bspcoord) -{ - if (!portalclipline) - return true; - - if (HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXTOP]) || - HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXBOTTOM]) || - HWR_PortalCheckPointSide(bspcoord[BOXRIGHT], bspcoord[BOXTOP]) || - HWR_PortalCheckPointSide(bspcoord[BOXRIGHT], bspcoord[BOXBOTTOM])) - { - return true; - } - - // we did not find any reason to pass the check, so return failure - return false; -} - // // Renders all subsectors below a given node, // traversing subtree recursively. @@ -3325,15 +3098,15 @@ static void HWR_RenderBSPNode(INT32 bspnum) bsp = &nodes[bspnum]; // Decide which side the view point is on. - side = R_PointOnSide(viewx, viewy, bsp); + side = R_PointOnSideFast(viewx, viewy, bsp); // Recursively divide front space. if (HWR_PortalCheckBBox(bsp->bbox[side])) HWR_RenderBSPNode(bsp->children[side]); - // Possibly divide back space - if (!(HWR_CheckBBox(bsp->bbox[side^1]) && HWR_PortalCheckBBox(bsp->bbox[side^1]))) - return; + // Possibly divide back space + if (!(HWR_CheckBBox(bsp->bbox[side^1]) && HWR_PortalCheckBBox(bsp->bbox[side^1]))) + return; bspnum = bsp->children[side^1]; } @@ -3341,6 +3114,8 @@ static void HWR_RenderBSPNode(INT32 bspnum) // PORTAL CULLING if (portalclipline && portalcullsector) { + // skip all subsectors encountered before the portal + // destination's front sector if (portalcullsector != subsectors[bspnum & ~NF_SUBSECTOR].sector) return; else @@ -3352,14 +3127,14 @@ static void HWR_RenderBSPNode(INT32 bspnum) } // ========================================================================== -// gr_things.c +// gl_things.c // ========================================================================== // sprites are drawn after all wall and planes are rendered, so that // sprite translucency effects apply on the rendered view (instead of the background sky!!) -static UINT32 gr_visspritecount; -static gr_vissprite_t *gr_visspritechunks[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {NULL}; +static UINT32 gl_visspritecount; +static gl_vissprite_t *gl_visspritechunks[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {NULL}; // -------------------------------------------------------------------------- // HWR_ClearSprites @@ -3367,37 +3142,37 @@ static gr_vissprite_t *gr_visspritechunks[MAXVISSPRITES >> VISSPRITECHUNKBITS] = // -------------------------------------------------------------------------- static void HWR_ClearSprites(void) { - gr_visspritecount = 0; + gl_visspritecount = 0; } // -------------------------------------------------------------------------- // HWR_NewVisSprite // -------------------------------------------------------------------------- -static gr_vissprite_t gr_overflowsprite; +static gl_vissprite_t gl_overflowsprite; -static gr_vissprite_t *HWR_GetVisSprite(UINT32 num) +static gl_vissprite_t *HWR_GetVisSprite(UINT32 num) { UINT32 chunk = num >> VISSPRITECHUNKBITS; // Allocate chunk if necessary - if (!gr_visspritechunks[chunk]) - Z_Malloc(sizeof(gr_vissprite_t) * VISSPRITESPERCHUNK, PU_LEVEL, &gr_visspritechunks[chunk]); + if (!gl_visspritechunks[chunk]) + Z_Malloc(sizeof(gl_vissprite_t) * VISSPRITESPERCHUNK, PU_LEVEL, &gl_visspritechunks[chunk]); - return gr_visspritechunks[chunk] + (num & VISSPRITEINDEXMASK); + return gl_visspritechunks[chunk] + (num & VISSPRITEINDEXMASK); } -static gr_vissprite_t *HWR_NewVisSprite(void) +static gl_vissprite_t *HWR_NewVisSprite(void) { - if (gr_visspritecount == MAXVISSPRITES) - return &gr_overflowsprite; + if (gl_visspritecount == MAXVISSPRITES) + return &gl_overflowsprite; - return HWR_GetVisSprite(gr_visspritecount++); + return HWR_GetVisSprite(gl_visspritecount++); } // Finds a floor through which light does not pass. static fixed_t HWR_OpaqueFloorAtPos(fixed_t x, fixed_t y, fixed_t z, fixed_t height) { - const sector_t *sec = R_PointInSubsector(x, y)->sector; + const sector_t *sec = R_PointInSubsectorFast(x, y)->sector; fixed_t floorz = sec->floorheight; if (sec->ffloors) @@ -3428,7 +3203,7 @@ static fixed_t HWR_OpaqueFloorAtPos(fixed_t x, fixed_t y, fixed_t z, fixed_t hei return floorz; } -static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch) +static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, GLPatch_t *gpatch) { float this_scale = 1.0f; FOutVector swallVerts[4]; @@ -3438,8 +3213,6 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch) pslope_t *floorslope; fixed_t slopez; float offset = 0; - - INT32 shader = SHADER_NONE; // technically this_scale gets multiplied and added to sprite y/x scale, but this thing needs it for some crap so ill just throw it in here again const boolean hires = (spr->mobj && spr->mobj->skin && ((skin_t *)( (spr->mobj->localskin) ? spr->mobj->localskin : spr->mobj->skin ))->flags & SF_HIRES); @@ -3447,7 +3220,7 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch) this_scale = FIXED_TO_FLOAT(spr->mobj->scale); if (hires) this_scale = this_scale * FIXED_TO_FLOAT(((skin_t *)( (spr->mobj->localskin) ? spr->mobj->localskin : spr->mobj->skin ))->highresscale); - + R_GetShadowZ(spr->mobj, &floorslope); mobjfloor = HWR_OpaqueFloorAtPos( @@ -3460,13 +3233,13 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch) // Set direction if (splitscreen && stplyr == &players[displayplayers[1]]) - shadowdir = localangle[1] + FixedAngle(cv_cam2_rotate.value); + shadowdir = localangle[1] + FixedAngle(cv_cam_rotate[1].value); else if (splitscreen > 1 && stplyr == &players[displayplayers[2]]) - shadowdir = localangle[2] + FixedAngle(cv_cam3_rotate.value); + shadowdir = localangle[2] + FixedAngle(cv_cam_rotate[2].value); else if (splitscreen > 2 && stplyr == &players[displayplayers[3]]) - shadowdir = localangle[3] + FixedAngle(cv_cam4_rotate.value); + shadowdir = localangle[3] + FixedAngle(cv_cam_rotate[3].value); else - shadowdir = localangle[0] + FixedAngle(cv_cam_rotate.value); + shadowdir = localangle[0] + FixedAngle(cv_cam_rotate[0].value); // Find floorheight floorheight = HWR_OpaqueFloorAtPos( @@ -3518,10 +3291,10 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch) swallVerts[0].y = swallVerts[1].y = swallVerts[2].y = swallVerts[3].y = spr->gzt - gpatch->topoffset * this_scale - (floorheight+3); // Now transform the TOP vertices along the floor in the direction of the camera - swallVerts[3].x = spr->x1 + ((gpatch->height * this_scale) + offset) * gr_viewcos; - swallVerts[2].x = spr->x2 + ((gpatch->height * this_scale) + offset) * gr_viewcos; - swallVerts[3].z = spr->z1 + ((gpatch->height * this_scale) + offset) * gr_viewsin; - swallVerts[2].z = spr->z2 + ((gpatch->height * this_scale) + offset) * gr_viewsin; + swallVerts[3].x = spr->x1 + ((gpatch->height * this_scale) + offset) * gl_viewcos; + swallVerts[2].x = spr->x2 + ((gpatch->height * this_scale) + offset) * gl_viewcos; + swallVerts[3].z = spr->z1 + ((gpatch->height * this_scale) + offset) * gl_viewsin; + swallVerts[2].z = spr->z2 + ((gpatch->height * this_scale) + offset) * gl_viewsin; } else { @@ -3529,21 +3302,21 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch) swallVerts[0].y = swallVerts[1].y = swallVerts[2].y = swallVerts[3].y = spr->gzt - gpatch->topoffset - (floorheight+3); // Now transform the TOP vertices along the floor in the direction of the camera - swallVerts[3].x = spr->x1 + (gpatch->height + offset) * gr_viewcos; - swallVerts[2].x = spr->x2 + (gpatch->height + offset) * gr_viewcos; - swallVerts[3].z = spr->z1 + (gpatch->height + offset) * gr_viewsin; - swallVerts[2].z = spr->z2 + (gpatch->height + offset) * gr_viewsin; + swallVerts[3].x = spr->x1 + (gpatch->height + offset) * gl_viewcos; + swallVerts[2].x = spr->x2 + (gpatch->height + offset) * gl_viewcos; + swallVerts[3].z = spr->z1 + (gpatch->height + offset) * gl_viewsin; + swallVerts[2].z = spr->z2 + (gpatch->height + offset) * gl_viewsin; } // We also need to move the bottom ones away when shadowoffs is on if (cv_shadowoffs.value) { - swallVerts[0].x = spr->x1 + offset * gr_viewcos; - swallVerts[1].x = spr->x2 + offset * gr_viewcos; - swallVerts[0].z = spr->z1 + offset * gr_viewsin; - swallVerts[1].z = spr->z2 + offset * gr_viewsin; + swallVerts[0].x = spr->x1 + offset * gl_viewcos; + swallVerts[1].x = spr->x2 + offset * gl_viewcos; + swallVerts[0].z = spr->z1 + offset * gl_viewsin; + swallVerts[1].z = spr->z2 + offset * gl_viewsin; } - + if (floorslope) { for (int i = 0; i < 4; i++) @@ -3596,86 +3369,97 @@ static void HWR_DrawSpriteShadow(gr_vissprite_t *spr, GLPatch_t *gpatch) if (sSurf.PolyColor.s.alpha > floorheight/4) { sSurf.PolyColor.s.alpha = (UINT8)(sSurf.PolyColor.s.alpha - floorheight/4); - - if (HWR_UseShader()) - { - shader = SHADER_SHADOW; - blendmode |= PF_ColorMapped; - } - - HWR_ProcessPolygon(&sSurf, swallVerts, 4, blendmode|PF_Translucent|PF_Modulated, shader, false); + HWR_ProcessPolygon(&sSurf, swallVerts, 4, blendmode|PF_Translucent|PF_Modulated, SHADER_NONE, false); } } // This is expecting a pointer to an array containing 4 wallVerts for a sprite -static void HWR_RotateSpritePolyToAim(gr_vissprite_t *spr, FOutVector *wallVerts, const boolean precip) +static void HWR_RotateSpritePolyToAim(gl_vissprite_t *spr, FOutVector *wallVerts, const boolean precip, const boolean papersprite) { - if (cv_grspritebillboarding.value && spr && spr->mobj && !(spr->mobj->frame & FF_PAPERSPRITE) && wallVerts) + if (!cv_glspritebillboarding.value || !spr || !spr->mobj || !wallVerts || papersprite) { - // uncapped/interpolation - interpmobjstate_t interp = {0}; - float basey, lowy; - INT32 dist = -1; + return; + } - if (cv_grmaxinterpdist.value) - dist = R_QuickCamDist(spr->mobj->x, spr->mobj->y); + // uncapped/interpolation + interpmobjstate_t interp = {0}; + float basey, lowy; + INT32 dist = -1; - // do interpolation - if (R_UsingFrameInterpolation() && !paused && (!cv_grmaxinterpdist.value || dist < cv_grmaxinterpdist.value)) + if (cv_maxinterpdist.value) + dist = R_QuickCamDist(spr->mobj->x, spr->mobj->y); + + // do interpolation + if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value)) + { + if (precip) { - if (precip) - { - R_InterpolatePrecipMobjState((precipmobj_t *)spr->mobj, rendertimefrac, &interp); - } - else - { - R_InterpolateMobjState(spr->mobj, rendertimefrac, &interp); - } + R_InterpolatePrecipMobjState((precipmobj_t *)spr->mobj, rendertimefrac, &interp); } else { - if (precip) - { - R_InterpolatePrecipMobjState((precipmobj_t *)spr->mobj, FRACUNIT, &interp); - } - else - { - R_InterpolateMobjState(spr->mobj, FRACUNIT, &interp); - } + R_InterpolateMobjState(spr->mobj, rendertimefrac, &interp); } - - if (!precip && P_MobjFlip(spr->mobj) == -1) // precip doesn't have eflags so they can't flip + } + else + { + if (precip) { - basey = FIXED_TO_FLOAT(interp.z + spr->mobj->height); + R_InterpolatePrecipMobjState((precipmobj_t *)spr->mobj, FRACUNIT, &interp); } else { - basey = FIXED_TO_FLOAT(interp.z); + R_InterpolateMobjState(spr->mobj, FRACUNIT, &interp); } - lowy = wallVerts[0].y; + } - // Rotate sprites to fully billboard with the camera - // X, Y, AND Z need to be manipulated for the polys to rotate around the - // origin, because of how the origin setting works I believe that should - // be mobj->z or mobj->z + mobj->height - wallVerts[2].y = wallVerts[3].y = (spr->gzt - basey) * gr_viewludsin + basey; - wallVerts[0].y = wallVerts[1].y = (lowy - basey) * gr_viewludsin + basey; - // translate back to be around 0 before translating back - wallVerts[3].x += ((spr->gzt - basey) * gr_viewludcos) * gr_viewcos; - wallVerts[2].x += ((spr->gzt - basey) * gr_viewludcos) * gr_viewcos; + if (!precip && P_MobjFlip(spr->mobj) == -1) // precip doesn't have eflags so they can't flip + { + basey = FIXED_TO_FLOAT(interp.z + spr->mobj->height); + } + else + { + basey = FIXED_TO_FLOAT(interp.z); + } + lowy = wallVerts[0].y; - wallVerts[0].x += ((lowy - basey) * gr_viewludcos) * gr_viewcos; - wallVerts[1].x += ((lowy - basey) * gr_viewludcos) * gr_viewcos; + // Rotate sprites to fully billboard with the camera + // X, Y, AND Z need to be manipulated for the polys to rotate around the + // origin, because of how the origin setting works I believe that should + // be mobj->z or mobj->z + mobj->height + wallVerts[2].y = wallVerts[3].y = (spr->gzt - basey) * gl_viewludsin + basey; + wallVerts[0].y = wallVerts[1].y = (lowy - basey) * gl_viewludsin + basey; - wallVerts[3].z += ((spr->gzt - basey) * gr_viewludcos) * gr_viewsin; - wallVerts[2].z += ((spr->gzt - basey) * gr_viewludcos) * gr_viewsin; + // translate back to be around 0 before translating back + wallVerts[3].x += ((spr->gzt - basey) * gl_viewludcos) * gl_viewcos; + wallVerts[2].x += ((spr->gzt - basey) * gl_viewludcos) * gl_viewcos; - wallVerts[0].z += ((lowy - basey) * gr_viewludcos) * gr_viewsin; - wallVerts[1].z += ((lowy - basey) * gr_viewludcos) * gr_viewsin; + wallVerts[0].x += ((lowy - basey) * gl_viewludcos) * gl_viewcos; + wallVerts[1].x += ((lowy - basey) * gl_viewludcos) * gl_viewcos; + + wallVerts[3].z += ((spr->gzt - basey) * gl_viewludcos) * gl_viewsin; + wallVerts[2].z += ((spr->gzt - basey) * gl_viewludcos) * gl_viewsin; + + wallVerts[0].z += ((lowy - basey) * gl_viewludcos) * gl_viewsin; + wallVerts[1].z += ((lowy - basey) * gl_viewludcos) * gl_viewsin; +} + +static inline void HWR_ApplyDispoffset(gl_vissprite_t *spr, FOutVector *wallVerts, const boolean papersprite) +{ + HWR_RotateSpritePolyToAim(spr, wallVerts, false, papersprite); + + float sprdist = sqrtf((spr->x1 - gl_viewx)*(spr->x1 - gl_viewx) + (spr->z1 - gl_viewy)*(spr->z1 - gl_viewy) + (spr->gzt - gl_viewz)*(spr->gzt - gl_viewz)); + float distfact = ((2.0f*spr->dispoffset) + 20.0f) / sprdist; + + for (size_t i = 0; i < 4; i++) + { + wallVerts[i].x += (gl_viewx - wallVerts[i].x)*distfact; + wallVerts[i].z += (gl_viewy - wallVerts[i].z)*distfact; + wallVerts[i].y += (gl_viewz - wallVerts[i].y)*distfact; } } -static void HWR_SplitSprite(gr_vissprite_t *spr) +static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite) { FOutVector wallVerts[4]; FOutVector baseWallVerts[4]; // This is what the verts should end up as @@ -3755,18 +3539,8 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) baseWallVerts[0].t = baseWallVerts[1].t = gpatch->max_t; } - // Let dispoffset work first since this adjust each vertex - HWR_RotateSpritePolyToAim(spr, baseWallVerts, false); - // push it toward the camera to mitigate floor-clipping sprites - float sprdist = sqrtf((spr->x1 - gr_viewx)*(spr->x1 - gr_viewx) + (spr->z1 - gr_viewy)*(spr->z1 - gr_viewy) + (spr->gzt - gr_viewz)*(spr->gzt - gr_viewz)); - float distfact = ((2.0f*spr->dispoffset) + 20.0f) / sprdist; - for (i = 0; i < 4; i++) - { - baseWallVerts[i].x += (gr_viewx - baseWallVerts[i].x)*distfact; - baseWallVerts[i].z += (gr_viewy - baseWallVerts[i].z)*distfact; - baseWallVerts[i].y += (gr_viewz - baseWallVerts[i].y)*distfact; - } + HWR_ApplyDispoffset(spr, baseWallVerts, papersprite); realtop = top = baseWallVerts[3].y; realbot = bot = baseWallVerts[0].y; @@ -3811,7 +3585,7 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) } alpha = Surf.PolyColor.s.alpha; - + // Start with the lightlevel and colormap from the top of the sprite lightlevel = *list[sector->numlights - 1].lightlevel; @@ -3836,7 +3610,7 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) for (i = 0; i < sector->numlights; i++) { - if (endtop < endrealbot && top < realbot) + if ((endtop < endrealbot) && (top < realbot)) return; // even if we aren't changing colormap or lightlevel, we still need to continue drawing down the sprite @@ -3860,18 +3634,16 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) endbheight = endrealbot; } - if (endbheight >= endtop && bheight >= top) + if (endbheight >= endtop) continue; - bot = bheight; + if (bheight >= top) + continue; - if (bot < realbot) - bot = realbot; - - endbot = endbheight; - - if (endbot < endrealbot) - endbot = endrealbot; + // Found a break + // The heights are clamped to ensure the polygon doesn't cross itself. + bot = CLAMP(bheight, realbot, top); + endbot = CLAMP(endbheight, endrealbot, endtop); wallVerts[3].t = towtop + ((realtop - top) * towmult); wallVerts[2].t = towtop + ((endrealtop - endtop) * towmult); @@ -3884,7 +3656,7 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) wallVerts[1].y = endbot; // The x and y only need to be adjusted in the case that it's not a papersprite - if (cv_grspritebillboarding.value && spr->mobj && !(spr->mobj->frame & FF_PAPERSPRITE)) + if (cv_glspritebillboarding.value && spr->mobj && !papersprite) { // Get the x and z of the vertices so billboarding draws correctly realheight = realbot - realtop; @@ -3919,7 +3691,7 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) bot = realbot; endbot = endrealbot; - if (endtop <= endrealbot && top <= realbot) + if ((endtop <= endrealbot) && (top <= realbot)) return; // If we're ever down here, somehow the above loop hasn't draw all the light levels of sprite @@ -3945,24 +3717,26 @@ static void HWR_SplitSprite(gr_vissprite_t *spr) // : (monsters, bonuses, weapons, lights, ...) // Returns : // -----------------+ -static void HWR_DrawSprite(gr_vissprite_t *spr) +static void HWR_DrawSprite(gl_vissprite_t *spr) { FOutVector wallVerts[4]; GLPatch_t *gpatch; // sprite patch converted to hardware FSurfaceInfo Surf; FBITFIELD blend = 0; - + INT32 shader = SHADER_NONE; - if (!spr->mobj) + if (P_MobjWasRemoved(spr->mobj)) return; if (!spr->mobj->subsector) return; + const boolean papersprite = (spr->mobj->frame & FF_PAPERSPRITE); + if (spr->mobj->subsector->sector->numlights) { - HWR_SplitSprite(spr); + HWR_SplitSprite(spr, papersprite); return; } @@ -4028,20 +3802,8 @@ static void HWR_DrawSprite(gr_vissprite_t *spr) HWR_DrawSpriteShadow(spr, gpatch); } - // Let dispoffset work first since this adjust each vertex - // ...nah - HWR_RotateSpritePolyToAim(spr, wallVerts, false); - // push it toward the camera to mitigate floor-clipping sprites - float sprdist = sqrtf((spr->x1 - gr_viewx)*(spr->x1 - gr_viewx) + (spr->z1 - gr_viewy)*(spr->z1 - gr_viewy) + (spr->gzt - gr_viewz)*(spr->gzt - gr_viewz)); - float distfact = ((2.0f*spr->dispoffset) + 20.0f) / sprdist; - size_t i; - for (i = 0; i < 4; i++) - { - wallVerts[i].x += (gr_viewx - wallVerts[i].x)*distfact; - wallVerts[i].z += (gr_viewy - wallVerts[i].z)*distfact; - wallVerts[i].y += (gr_viewz - wallVerts[i].y)*distfact; - } + HWR_ApplyDispoffset(spr, wallVerts, papersprite); // This needs to be AFTER the shadows so that the regular sprites aren't drawn completely black. // sprite lighting by modulating the RGB components @@ -4051,8 +3813,9 @@ static void HWR_DrawSprite(gr_vissprite_t *spr) sector_t *sector = spr->mobj->subsector->sector; UINT8 lightlevel = 255; extracolormap_t *colormap = sector->extra_colormap; + const boolean fullbright = (spr->mobj->frame & FF_FULLBRIGHT); - if (!(spr->mobj->frame & FF_FULLBRIGHT)) + if (!fullbright) lightlevel = min(sector->lightlevel, 255); HWR_Lighting(&Surf, lightlevel, colormap); @@ -4089,7 +3852,7 @@ static void HWR_DrawSprite(gr_vissprite_t *spr) } // Sprite drawer for precipitation -static inline void HWR_DrawPrecipitationSprite(gr_vissprite_t *spr) +static inline void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr) { FBITFIELD blend = 0; FOutVector wallVerts[4]; @@ -4123,8 +3886,7 @@ static inline void HWR_DrawPrecipitationSprite(gr_vissprite_t *spr) wallVerts[0].z = wallVerts[3].z = spr->z1; wallVerts[1].z = wallVerts[2].z = spr->z2; - // Let dispoffset work first since this adjust each vertex - HWR_RotateSpritePolyToAim(spr, wallVerts, true); + HWR_RotateSpritePolyToAim(spr, wallVerts, true, false); wallVerts[0].s = wallVerts[3].s = 0; wallVerts[2].s = wallVerts[1].s = gpatch->max_s; @@ -4190,20 +3952,21 @@ static inline void HWR_DrawPrecipitationSprite(gr_vissprite_t *spr) // Sort vissprites by distance // -------------------------------------------------------------------------- -gr_vissprite_t* gr_vsprorder[MAXVISSPRITES]; +gl_vissprite_t* gl_vsprorder[MAXVISSPRITES]; // For more correct transparency the transparent sprites would need to be // sorted and drawn together with transparent surfaces. static int CompareVisSprites(const void *p1, const void *p2) { - gr_vissprite_t* spr1 = *(gr_vissprite_t*const*)p1; - gr_vissprite_t* spr2 = *(gr_vissprite_t*const*)p2; + gl_vissprite_t* spr1 = *(gl_vissprite_t*const*)p1; + gl_vissprite_t* spr2 = *(gl_vissprite_t*const*)p2; int idiff; float fdiff; // make transparent sprites last // "boolean to int" + // check for precip first, because then sprX->mobj is actually a precipmobj_t and does not have flags2 or tracer int transparency1 = (!spr1->precip && (spr1->mobj->flags2 & MF2_SHADOW)) || (spr1->mobj->frame & FF_TRANSMASK); int transparency2 = (!spr2->precip && (spr2->mobj->flags2 & MF2_SHADOW)) || (spr2->mobj->frame & FF_TRANSMASK); @@ -4222,12 +3985,12 @@ static int CompareVisSprites(const void *p1, const void *p2) static void HWR_SortVisSprites(void) { UINT32 i; - for (i = 0; i < gr_visspritecount; i++) + for (i = 0; i < gl_visspritecount; i++) { - gr_vsprorder[i] = HWR_GetVisSprite(i); + gl_vsprorder[i] = HWR_GetVisSprite(i); } - qs22j(gr_vsprorder, gr_visspritecount, sizeof(gr_vissprite_t*), CompareVisSprites); + qs22j(gl_vsprorder, gl_visspritecount, sizeof(gl_vissprite_t*), CompareVisSprites); } // A drawnode is something that points to a 3D floor, 3D side, or masked @@ -4276,37 +4039,37 @@ typedef enum DRAWNODE_PLANE, DRAWNODE_POLYOBJECT_PLANE, DRAWNODE_WALL -} gr_drawnode_type_t; +} gl_drawnode_type_t; typedef struct { - gr_drawnode_type_t type; + gl_drawnode_type_t type; union { planeinfo_t plane; polyplaneinfo_t polyplane; wallinfo_t wall; } u; -} gr_drawnode_t; +} gl_drawnode_t; // initial size of drawnode array #define DRAWNODES_INIT_SIZE 64 -gr_drawnode_t *drawnodes = NULL; +gl_drawnode_t *drawnodes = NULL; INT32 numdrawnodes = 0; INT32 alloceddrawnodes = 0; -static void *HWR_CreateDrawNode(gr_drawnode_type_t type) +static void *HWR_CreateDrawNode(gl_drawnode_type_t type) { - gr_drawnode_t *drawnode; + gl_drawnode_t *drawnode; if (!drawnodes) { alloceddrawnodes = DRAWNODES_INIT_SIZE; - drawnodes = Z_Malloc(alloceddrawnodes * sizeof(gr_drawnode_t), PU_LEVEL, &drawnodes); + drawnodes = Z_Malloc(alloceddrawnodes * sizeof(gl_drawnode_t), PU_LEVEL, &drawnodes); } else if (numdrawnodes >= alloceddrawnodes) { alloceddrawnodes *= 2; - Z_Realloc(drawnodes, alloceddrawnodes * sizeof(gr_drawnode_t), PU_LEVEL, &drawnodes); + Z_Realloc(drawnodes, alloceddrawnodes * sizeof(gl_drawnode_t), PU_LEVEL, &drawnodes); } @@ -4326,7 +4089,7 @@ static void *HWR_CreateDrawNode(gr_drawnode_type_t type) return NULL; } -void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, INT32 texnum, boolean noencore, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap) +static void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, INT32 texnum, boolean noencore, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap) { wallinfo_t *wallinfo = HWR_CreateDrawNode(DRAWNODE_WALL); @@ -4340,7 +4103,7 @@ void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, INT32 te wallinfo->wallcolormap = wallcolormap; } -void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, boolean fogplane, extracolormap_t *planecolormap) +static void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, boolean fogplane, extracolormap_t *planecolormap) { planeinfo_t *planeinfo = HWR_CreateDrawNode(DRAWNODE_PLANE); @@ -4358,7 +4121,7 @@ void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean // Adding this for now until I can create extrasubsector info for polyobjects // When that happens it'll just be done through HWR_AddTransparentFloor and HWR_RenderPlane -void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, extracolormap_t *planecolormap) +static void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, extracolormap_t *planecolormap) { polyplaneinfo_t *polyplaneinfo = HWR_CreateDrawNode(DRAWNODE_POLYOBJECT_PLANE); @@ -4441,18 +4204,18 @@ static void HWR_RenderDrawNodes(void) PS_START_TIMING(ps_hw_nodedrawtime); // Okay! Let's draw it all! Woo! - HWD.pfnSetTransform(&atransform); + GL_SetTransform(&atransform); for (i = 0; i < numdrawnodes; i++) { - gr_drawnode_t *drawnode = &drawnodes[sortindex[i]]; + gl_drawnode_t *drawnode = &drawnodes[sortindex[i]]; if (drawnode->type == DRAWNODE_PLANE) { planeinfo_t *plane = &drawnode->u.plane; - // We aren't traversing the BSP tree, so make gr_frontsector null to avoid crashes. - gr_frontsector = NULL; + // We aren't traversing the BSP tree, so make gl_frontsector null to avoid crashes. + gl_frontsector = NULL; if (!(plane->blend & PF_NoTexture)) HWR_GetFlat(plane->lumpnum, R_NoEncore(plane->FOFSector, plane->isceiling)); @@ -4464,8 +4227,8 @@ static void HWR_RenderDrawNodes(void) { polyplaneinfo_t *polyplane = &drawnode->u.polyplane; - // We aren't traversing the BSP tree, so make gr_frontsector null to avoid crashes. - gr_frontsector = NULL; + // We aren't traversing the BSP tree, so make gl_frontsector null to avoid crashes. + gl_frontsector = NULL; if (!(polyplane->blend & PF_NoTexture)) HWR_GetFlat(polyplane->lumpnum, R_NoEncore(polyplane->FOFSector, polyplane->isceiling)); @@ -4484,7 +4247,7 @@ static void HWR_RenderDrawNodes(void) wall->lightlevel, wall->wallcolormap); } } - + PS_STOP_TIMING(ps_hw_nodedrawtime); numdrawnodes = 0; @@ -4496,12 +4259,13 @@ static void HWR_RenderDrawNodes(void) // -------------------------------------------------------------------------- // Draw all vissprites // -------------------------------------------------------------------------- -void HWR_DrawSprites(void) +static void HWR_DrawSprites(void) { UINT32 i; - for (i = 0; i < gr_visspritecount; i++) + + for (i = 0; i < gl_visspritecount; i++) { - gr_vissprite_t *spr = gr_vsprorder[i]; + gl_vissprite_t *spr = gl_vsprorder[i]; if (spr->precip) { @@ -4512,6 +4276,7 @@ void HWR_DrawSprites(void) if (spr->mobj && spr->mobj->skin && spr->mobj->sprite == SPR_PLAY) { md2_t *md2; + if (spr->mobj->localskin) { if (spr->mobj->skinlocal) @@ -4523,14 +4288,14 @@ void HWR_DrawSprites(void) md2 = &md2_playermodels[(skin_t *)spr->mobj->skin - skins]; // 8/1/19: Only don't display player models if no default SPR_PLAY is found. - if (!cv_grmdls.value || ((md2->notfound || md2->scale < 0.0f) && ((!cv_grfallbackplayermodel.value) || md2_models[SPR_PLAY].notfound || md2_models[SPR_PLAY].scale < 0.0f)) || spr->mobj->state == &states[S_PLAY_SIGN]) + if (!cv_glmdls.value || ((md2->notfound || md2->scale < 0.0f) && ((!cv_glfallbackplayermodel.value) || md2_models[SPR_PLAY].notfound || md2_models[SPR_PLAY].scale < 0.0f)) || spr->mobj->state == &states[S_PLAY_SIGN]) HWR_DrawSprite(spr); else HWR_DrawMD2(spr); } else { - if (!cv_grmdls.value || md2_models[spr->mobj->sprite].notfound || md2_models[spr->mobj->sprite].scale < 0.0f) + if (!cv_glmdls.value || md2_models[spr->mobj->sprite].notfound || md2_models[spr->mobj->sprite].scale < 0.0f) HWR_DrawSprite(spr); else HWR_DrawMD2(spr); @@ -4542,7 +4307,7 @@ void HWR_DrawSprites(void) // HWR_AddSprites // During BSP traversal, this adds sprites by sector. // -------------------------------------------------------------------------- -void HWR_AddSprites(sector_t *sec) +static void HWR_AddSprites(sector_t *sec) { mobj_t *thing; fixed_t limit_dist; @@ -4589,20 +4354,27 @@ void HWR_AddSprites(sector_t *sec) // -------------------------------------------------------------------------- static void HWR_AddPrecipitationSprites(void) { - //const fixed_t drawdist = cv_drawdist_precip.value * mapobjectscale; - fixed_t drawdist; - fixed_t precipscale = cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT; - INT32 xl, xh, yl, yh, bx, by; precipmobj_t *th; - + + fixed_t drawdist; + + // save a little time on invisible weather + if (curWeather == PRECIP_BLANK || curWeather == PRECIP_STORM_NORAIN) + { + return; + } + + const fixed_t precipscale = (cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT); + //const fixed_t drawdist = cv_drawdist_precip.value * mapobjectscale; + if (current_bsp_culling_distance) drawdist = min((fixed_t)current_bsp_culling_distance, (fixed_t)(cv_drawdist_precip.value) * precipscale); else - drawdist = (fixed_t)(cv_drawdist_precip.value) * precipscale; + drawdist = ((fixed_t)(cv_drawdist_precip.value) * precipscale); // No to infinite precipitation draw distance. - if (drawdist == 0 || curWeather == PRECIP_BLANK || curWeather == PRECIP_STORM_NORAIN) + if (drawdist == 0) { return; } @@ -4629,9 +4401,9 @@ static void HWR_AddPrecipitationSprites(void) // Generates a vissprite for a thing if it might be visible. // -------------------------------------------------------------------------- // BP why not use xtoviexangle/viewangletox like in bsp ?.... -void HWR_ProjectSprite(mobj_t *thing) +static void HWR_ProjectSprite(mobj_t *thing) { - gr_vissprite_t *vis; + gl_vissprite_t *vis; float tr_x, tr_y; float tz; float x1, x2; @@ -4648,12 +4420,11 @@ void HWR_ProjectSprite(mobj_t *thing) size_t lumpoff; unsigned rot; UINT8 flip; - boolean vflip; - boolean mirrored; - boolean hflip; - angle_t ang, camang; - boolean papersprite; + angle_t ang = 0; +#ifdef ROTSPRITE + angle_t camang = 0; +#endif INT32 heightsec, phs; INT32 dist = -1; @@ -4662,25 +4433,20 @@ void HWR_ProjectSprite(mobj_t *thing) #ifdef ROTSPRITE patch_t *rotsprite = NULL; INT32 rollangle = 0; - angle_t rollsum = 0; + angle_t pitchnroll = 0; angle_t sliptiderollangle = 0; #endif + if (P_MobjWasRemoved(thing) || thing->subsector == NULL) + return; + // uncapped/interpolation interpmobjstate_t interp = {0}; - if (!thing) - return; - - vflip = (thing->eflags & MFE_VERTICALFLIP); - mirrored = thing->mirrored; - hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); - papersprite = (thing->frame & FF_PAPERSPRITE); - - if (cv_grmaxinterpdist.value) + if (cv_maxinterpdist.value) dist = R_QuickCamDist(thing->x, thing->y); - if (R_UsingFrameInterpolation() && !paused && (!cv_grmaxinterpdist.value || dist < cv_grmaxinterpdist.value)) + if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value)) { R_InterpolateMobjState(thing, rendertimefrac, &interp); } @@ -4692,19 +4458,24 @@ void HWR_ProjectSprite(mobj_t *thing) if (interp.spritexscale < 1 || interp.spriteyscale < 1) return; + const boolean mirrored = thing->mirrored; + const boolean vflip = (thing->eflags & MFE_VERTICALFLIP); + const boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); + const boolean papersprite = (thing->frame & FF_PAPERSPRITE); + this_scale = FIXED_TO_FLOAT(interp.scale); spritexscale = FIXED_TO_FLOAT(interp.spritexscale); spriteyscale = FIXED_TO_FLOAT(interp.spriteyscale); // transform the origin point - tr_x = FIXED_TO_FLOAT(interp.x) - gr_viewx; - tr_y = FIXED_TO_FLOAT(interp.y) - gr_viewy; + tr_x = FIXED_TO_FLOAT(interp.x) - gl_viewx; + tr_y = FIXED_TO_FLOAT(interp.y) - gl_viewy; // rotation around vertical axis - tz = (tr_x * gr_viewcos) + (tr_y * gr_viewsin); + tz = (tr_x * gl_viewcos) + (tr_y * gl_viewsin); // thing is behind view plane? - if (tz < ZCLIP_PLANE && !papersprite && (!cv_grmdls.value || md2_models[thing->sprite].notfound == true)) //Yellow: Only MD2's dont disappear + if (tz < ZCLIP_PLANE && !papersprite && (!cv_glmdls.value || md2_models[thing->sprite].notfound == true)) //Yellow: Only MD2's dont disappear return; // The above can stay as it works for cutting sprites that are too close @@ -4717,7 +4488,13 @@ void HWR_ProjectSprite(mobj_t *thing) I_Error("HWR_ProjectSprite: invalid sprite number %i ", thing->sprite); #endif - rot = thing->frame&FF_FRAMEMASK; + rot = (thing->frame & FF_FRAMEMASK); + +#ifdef ROTSPRITE + // determine here if sprite should rotate for optimization + const boolean sliprollrotate = (cv_sloperoll.value && cv_sliptideroll.value && (thing->player && thing->player->sliproll)); + const boolean shouldrotate = (cv_sloperoll.value && (interp.roll || interp.pitch || interp.sloperoll || interp.slopepitch || thing->rollangle || sliprollrotate)); +#endif //Fab : 02-08-98: 'skin' override spritedef currently used for skin if ((thing->skin || thing->localskin) && thing->sprite == SPR_PLAY) @@ -4745,7 +4522,7 @@ void HWR_ProjectSprite(mobj_t *thing) #ifdef ROTSPRITE sprinfo = &spriteinfo[thing->sprite]; #endif - rot = thing->frame&FF_FRAMEMASK; + rot = (thing->frame & FF_FRAMEMASK); thing->state->sprite = thing->sprite; thing->state->frame = thing->frame; } @@ -4757,11 +4534,23 @@ void HWR_ProjectSprite(mobj_t *thing) I_Error("sprframes NULL for sprite %d\n", thing->sprite); #endif - ang = R_PointToAngle (interp.x, interp.y) - interp.angle; - camang = R_PointToAngle (interp.x, interp.y); + if (sprframe->rotate != SRF_SINGLE || papersprite || +#ifdef ROTSPRITE + (shouldrotate) +#endif + ) + { + ang = R_PointToAngle(interp.x, interp.y); - if (mirrored) - ang = InvAngle(ang); +#ifdef ROTSPRITE + camang = ang; +#endif + + ang -= interp.angle; + + if (mirrored) + ang = InvAngle(ang); + } if (sprframe->rotate == SRF_SINGLE) { @@ -4776,9 +4565,9 @@ void HWR_ProjectSprite(mobj_t *thing) else { // choose a different rotation based on player view - if ((ang < ANGLE_180) && (sprframe->rotate & SRF_RIGHT)) // See from right + if ((sprframe->rotate & SRF_RIGHT) && (ang < ANGLE_180)) // See from right rot = 6; // F7 slot - else if ((ang >= ANGLE_180) && (sprframe->rotate & SRF_LEFT)) // See from left + else if ((sprframe->rotate & SRF_LEFT) && (ang >= ANGLE_180)) // See from left rot = 2; // F3 slot else // Normal behaviour rot = (ang+ANGLE_202h)>>29; @@ -4800,35 +4589,34 @@ void HWR_ProjectSprite(mobj_t *thing) spr_topoffset = spritecachedinfo[lumpoff].topoffset; #ifdef ROTSPRITE - if (cv_spriteroll.value) + if (shouldrotate) { - rollangle = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), interp.roll) - + FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), interp.pitch) - + FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), interp.sloperoll) - + FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), interp.slopepitch) - + thing->rollangle; + // this is very messy, but it on-the-fly calculates rotations for all the + // pitch and roll variables + pitchnroll = R_RotationAngle(ang, camang, &interp); + rollangle = thing->rollangle; - if ((rollangle)||(thing->player && thing->player->sliproll)) + if (rollangle || pitchnroll || sliprollrotate) { - if (thing->player) + if (sliprollrotate) { - sliptiderollangle = cv_sliptideroll.value ? thing->player->sliproll*(thing->player->sliptidemem) : 0; - rollsum = rollangle+FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), sliptiderollangle); + sliptiderollangle = thing->player->sliproll * thing->player->kartstuff[k_aizdriftstrat]; + pitchnroll += rollangle + FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), sliptiderollangle); } else - rollsum = rollangle; + pitchnroll += rollangle; - rollangle = R_GetRollAngle(rollsum); + rollangle = R_GetRollAngle(pitchnroll); rotsprite = Patch_GetRotatedSprite(sprframe, (thing->frame & FF_FRAMEMASK), rot, flip, false, sprinfo, rollangle); if (rotsprite != NULL) { - spr_width = rotsprite->width << FRACBITS; - spr_height = rotsprite->height << FRACBITS; - spr_offset = rotsprite->leftoffset << FRACBITS; - spr_topoffset = rotsprite->topoffset << FRACBITS; + spr_width = SHORT(rotsprite->width) << FRACBITS; + spr_height = SHORT(rotsprite->height) << FRACBITS; + spr_offset = SHORT(rotsprite->leftoffset) << FRACBITS; + spr_topoffset = SHORT(rotsprite->topoffset) << FRACBITS; spr_topoffset += FEETADJUST; - + // flip -> rotate, not rotate -> flip flip = 0; } @@ -4836,21 +4624,8 @@ void HWR_ProjectSprite(mobj_t *thing) } #endif - if (thing->renderflags & RF_ABSOLUTEOFFSETS) - { - spr_offset = interp.spritexoffset; - spr_topoffset = interp.spriteyoffset; - } - else - { - SINT8 flipoffset = 1; - - if ((thing->renderflags & RF_FLIPOFFSETS) && flip) - flipoffset = -1; - - spr_offset += interp.spritexoffset * flipoffset; - spr_topoffset += interp.spriteyoffset * flipoffset; - } + spr_offset += interp.spritexoffset; + spr_topoffset += interp.spriteyoffset; if (papersprite) { @@ -4865,7 +4640,7 @@ void HWR_ProjectSprite(mobj_t *thing) spritexscale *= this_scale; spriteyscale *= this_scale; - + flip = !flip != !hflip; if (flip) @@ -4897,7 +4672,7 @@ void HWR_ProjectSprite(mobj_t *thing) if (thing->subsector->sector->cullheight) { - if (HWR_DoCulling(thing->subsector->sector->cullheight, viewsector->cullheight, gr_viewz, gz, gzt)) + if (HWR_DoCulling(thing->subsector->sector->cullheight, viewsector->cullheight, gl_viewz, gz, gzt)) return; } @@ -4909,14 +4684,13 @@ void HWR_ProjectSprite(mobj_t *thing) if (heightsec != -1 && phs != -1) // only clip things which are in special sectors { - if (gr_viewz < FIXED_TO_FLOAT(sectors[phs].floorheight) ? - FIXED_TO_FLOAT(interp.z) >= FIXED_TO_FLOAT(sectors[heightsec].floorheight) : - gzt < FIXED_TO_FLOAT(sectors[heightsec].floorheight)) + if (gl_viewz < FIXED_TO_FLOAT(sectors[phs].floorheight) ? + FIXED_TO_FLOAT(interp.z) >= FIXED_TO_FLOAT(sectors[heightsec].floorheight) : + gzt < FIXED_TO_FLOAT(sectors[heightsec].floorheight)) return; - - if (gr_viewz > FIXED_TO_FLOAT(sectors[phs].ceilingheight) ? - gzt < FIXED_TO_FLOAT(sectors[heightsec].ceilingheight) && gr_viewz >= FIXED_TO_FLOAT(sectors[heightsec].ceilingheight) : - FIXED_TO_FLOAT(interp.z) >= FIXED_TO_FLOAT(sectors[heightsec].ceilingheight)) + if (gl_viewz > FIXED_TO_FLOAT(sectors[phs].ceilingheight) ? + gzt < FIXED_TO_FLOAT(sectors[heightsec].ceilingheight) && gl_viewz >= FIXED_TO_FLOAT(sectors[heightsec].ceilingheight) : + FIXED_TO_FLOAT(interp.z) >= FIXED_TO_FLOAT(sectors[heightsec].ceilingheight)) return; } @@ -4926,7 +4700,9 @@ void HWR_ProjectSprite(mobj_t *thing) vis->x2 = x2; vis->z1 = z1; vis->z2 = z2; + vis->tz = tz; // Keep tz for the simple sprite sorting that happens + vis->dispoffset = thing->info->dispoffset; // Monster Iestyn: 23/11/15: HARDWARE SUPPORT AT LAST vis->flip = flip; @@ -4937,7 +4713,7 @@ void HWR_ProjectSprite(mobj_t *thing) vis->spriteyoffset = FIXED_TO_FLOAT(spr_topoffset); #ifdef ROTSPRITE - if ((rotsprite) && (cv_spriteroll.value)) + if (rotsprite != NULL) vis->gpatch = (GLPatch_t *)rotsprite; else #endif @@ -4989,7 +4765,7 @@ void HWR_ProjectSprite(mobj_t *thing) // Precipitation projector for hardware mode static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) { - gr_vissprite_t *vis; + gl_vissprite_t *vis; float tr_x, tr_y; float tz; float x1, x2; @@ -5015,11 +4791,11 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) return; } - if (cv_grmaxinterpdist.value) + if (cv_maxinterpdist.value) dist = R_QuickCamDist(thing->x, thing->y); // do interpolation - if (R_UsingFrameInterpolation() && !paused && (!cv_grmaxinterpdist.value || dist < cv_grmaxinterpdist.value)) + if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value)) { R_InterpolatePrecipMobjState(thing, rendertimefrac, &interp); } @@ -5031,11 +4807,11 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) this_scale = FIXED_TO_FLOAT(interp.scale); // transform the origin point - tr_x = FIXED_TO_FLOAT(interp.x) - gr_viewx; - tr_y = FIXED_TO_FLOAT(interp.y) - gr_viewy; + tr_x = FIXED_TO_FLOAT(interp.x) - gl_viewx; + tr_y = FIXED_TO_FLOAT(interp.y) - gl_viewy; // rotation around vertical axis - tz = (tr_x * gr_viewcos) + (tr_y * gr_viewsin); + tz = (tr_x * gl_viewcos) + (tr_y * gl_viewsin); // thing is behind view plane? if (tz < ZCLIP_PLANE) @@ -5063,7 +4839,7 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) return; #endif - sprframe = &sprdef->spriteframes[ thing->frame & FF_FRAMEMASK]; + sprframe = &sprdef->spriteframes[thing->frame & FF_FRAMEMASK]; // use single rotation for all views lumpoff = sprframe->lumpid[0]; @@ -5118,52 +4894,202 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) vis->precip = true; } + +// ========================================================================== +// Sky dome rendering, ported from PrBoom+ +// ========================================================================== + +static gl_sky_t gl_sky; + +#define DEG2RADGL(a) ((a * M_PIl) / 180.0f) + +static void HWR_SkyDomeVertex(gl_sky_t *sky, gl_skyvertex_t *vbo, int r, int c, signed char yflip, float delta, boolean foglayer) +{ + static const float scale = 10000.0f; + static const float maxSideAngle = DEG2RADGL(60.0f); + + float topAngle = DEG2RADGL(c / (float)sky->columns * 360.0f); + float sideAngle = (maxSideAngle * (float)(sky->rows - r) / (float)sky->rows); + float height = (float)(sin(sideAngle)); + float realRadius = (scale * (float)cos(sideAngle)); + float x = (realRadius * (float)cos(topAngle)); + float y = (!yflip) ? scale * height : -scale * height; + float z = (realRadius * (float)sin(topAngle)); + float timesRepeat = (4 * (256.0f / sky->width)); + + if (fpclassify(timesRepeat) == FP_ZERO) + timesRepeat = 1.0f; + + if (!foglayer) + { + vbo->r = 255; + vbo->g = 255; + vbo->b = 255; + vbo->a = (r == 0 ? 0 : 255); + + // And the texture coordinates. + vbo->u = (-timesRepeat * c / (float)sky->columns); + if (!yflip) // Flipped Y is for the lower hemisphere. + vbo->v = (r / (float)sky->rows) + 0.5f; + else + vbo->v = 1.0f + ((sky->rows - r) / (float)sky->rows) + 0.5f; + } + + if (r != 4) + y += 300.0f; + + // And finally the vertex. + vbo->x = x; + vbo->y = y + delta; + vbo->z = z; +} + +// Clears the sky dome. +void HWR_ClearSkyDome(void) +{ + gl_sky_t *sky = &gl_sky; + + if (sky->loops) + free(sky->loops); + if (sky->data) + free(sky->data); + + sky->loops = NULL; + sky->data = NULL; + + sky->vbo = 0; + sky->rows = sky->columns = 0; + sky->loopcount = 0; + + sky->detail = 0; + sky->texture = -1; + sky->width = sky->height = 0; + + sky->rebuild = true; +} + +void HWR_BuildSkyDome(void) +{ + int c, r; + signed char yflip; + int row_count = 4; + int col_count = 4; + float delta; + + gl_sky_t *sky = &gl_sky; + gl_skyvertex_t *vertex_p; + texture_t *texture = textures[texturetranslation[skytexture]]; + + sky->detail = 16; + col_count *= sky->detail; + + if ((sky->columns != col_count) || (sky->rows != row_count)) + HWR_ClearSkyDome(); + + sky->columns = col_count; + sky->rows = row_count; + sky->vertex_count = 2 * sky->rows * (sky->columns * 2 + 2) + sky->columns * 2; + + if (!sky->loops) + sky->loops = malloc((sky->rows * 2 + 2) * sizeof(sky->loops[0])); + + // create vertex array + if (!sky->data) + sky->data = malloc(sky->vertex_count * sizeof(sky->data[0])); + + sky->texture = texturetranslation[skytexture]; + sky->width = texture->width; + sky->height = texture->height; + + vertex_p = &sky->data[0]; + sky->loopcount = 0; + + for (yflip = 0; yflip < 2; yflip++) + { + sky->loops[sky->loopcount].mode = HWD_SKYLOOP_FAN; + sky->loops[sky->loopcount].vertexindex = vertex_p - &sky->data[0]; + sky->loops[sky->loopcount].vertexcount = col_count; + sky->loops[sky->loopcount].use_texture = false; + sky->loopcount++; + + delta = 0.0f; + + for (c = 0; c < col_count; c++) + { + HWR_SkyDomeVertex(sky, vertex_p, 1, c, yflip, 0.0f, true); + vertex_p->r = 255; + vertex_p->g = 255; + vertex_p->b = 255; + vertex_p->a = 255; + vertex_p++; + } + + delta = (yflip ? 5.0f : -5.0f) / 128.0f; + + for (r = 0; r < row_count; r++) + { + sky->loops[sky->loopcount].mode = HWD_SKYLOOP_STRIP; + sky->loops[sky->loopcount].vertexindex = vertex_p - &sky->data[0]; + sky->loops[sky->loopcount].vertexcount = 2 * col_count + 2; + sky->loops[sky->loopcount].use_texture = true; + sky->loopcount++; + + for (c = 0; c <= col_count; c++) + { + HWR_SkyDomeVertex(sky, vertex_p++, r + (yflip ? 1 : 0), (c ? c : 0), yflip, delta, false); + HWR_SkyDomeVertex(sky, vertex_p++, r + (yflip ? 0 : 1), (c ? c : 0), yflip, delta, false); + } + } + } +} + static boolean drewsky = false; -void HWR_DrawSkyBackground(float fpov) +static void HWR_DrawSkyBackground(void) { FTransform dometransform; if (drewsky) return; - memset(&dometransform, 0x00, sizeof(FTransform)); + GL_SetBlend(PF_Translucent|PF_NoDepthTest|PF_Modulated); + + memcpy(&dometransform, &atransform, sizeof(FTransform)); + + dometransform.x = 0.0; + dometransform.y = 0.0; + dometransform.z = 0.0; //04/01/2000: Hurdler: added for T&L - // It should replace all other gr_viewxxx when finished + // It should replace all other gl_viewxxx when finished HWR_SetTransformAiming(&dometransform); dometransform.angley = (float)((viewangle-ANGLE_270)>>ANGLETOFINESHIFT)*(360.0f/(float)FINEANGLES); - dometransform.flip = atransform.flip; - dometransform.mirror = atransform.mirror; - dometransform.mirrorflip = atransform.mirrorflip; - - dometransform.scalex = 1; - dometransform.scaley = (float)vid.width/vid.height; - dometransform.scalez = 1; - dometransform.fovxangle = fpov; // Tails - dometransform.fovyangle = fpov; // Tails - HWR_RollTransform(&dometransform, viewroll); - dometransform.splitscreen = splitscreen; - HWR_GetTexture(texturetranslation[skytexture], false); - if (HWR_UseShader()) - HWD.pfnSetShader(HWR_GetShaderFromTarget(SHADER_SKY));// sky shader - HWD.pfnRenderSkyDome(skytexture, textures[skytexture]->width, textures[skytexture]->height, dometransform); -} + if (gl_sky.texture != texturetranslation[skytexture]) + { + HWR_ClearSkyDome(); + HWR_BuildSkyDome(); + } + + if (HWR_UseShader()) + GL_SetShader(HWR_GetShaderFromTarget(SHADER_SKY)); + GL_SetTransform(&dometransform); + GL_RenderSkyDome(&gl_sky); +} // -----------------+ // HWR_ClearView : clear the viewwindow, with maximum z value. also clears stencil buffer. // -----------------+ static inline void HWR_ClearView(void) { - HWD.pfnGClipRect((INT32)gr_viewwindowx, - (INT32)gr_viewwindowy, - (INT32)(gr_viewwindowx + gr_viewwidth), - (INT32)(gr_viewwindowy + gr_viewheight), - ZCLIP_PLANE, FAR_ZCLIP_DEFAULT); - HWD.pfnClearBuffer(false, true, true, NULL); + GL_GClipRect((INT32)gl_viewwindowx, + (INT32)gl_viewwindowy, + (INT32)(gl_viewwindowx + gl_viewwidth), + (INT32)(gl_viewwindowy + gl_viewheight), + ZCLIP_PLANE, FAR_ZCLIP_DEFAULT); + GL_ClearBuffer(false, true, true, NULL); } @@ -5173,66 +5099,54 @@ static inline void HWR_ClearView(void) void HWR_SetViewSize(void) { // setup view size - gr_viewwidth = (float)vid.width; - gr_viewheight = (float)vid.height; + gl_viewwidth = (float)vid.width; + gl_viewheight = (float)vid.height; if (splitscreen) - gr_viewheight /= 2; + gl_viewheight /= 2; if (splitscreen > 1) - gr_viewwidth /= 2; + gl_viewwidth /= 2; - gr_basecenterx = gr_viewwidth / 2; - gr_basecentery = gr_viewheight / 2; + gl_baseviewwindowy = 0; + gl_baseviewwindowx = 0; - gr_baseviewwindowy = 0; - gr_basewindowcentery = (float)(gr_viewheight / 2); - - gr_baseviewwindowx = 0; - gr_basewindowcenterx = (float)(gr_viewwidth / 2); - - gr_pspritexscale = ((vid.width*gr_pspriteyscale*BASEVIDHEIGHT)/BASEVIDWIDTH)/vid.height; - gr_pspriteyscale = ((vid.height*gr_pspritexscale*BASEVIDWIDTH)/BASEVIDHEIGHT)/vid.width; - - HWD.pfnFlushScreenTextures(); + GL_FlushScreenTextures(); } // Set view aiming, for the sky dome, the skybox, // and the normal view, all with a single function. static void HWR_SetTransformAiming(FTransform *trans) { - if (cv_grshearing.value) + if (cv_glshearing.value) { fixed_t fixedaiming = AIMINGTODY(aimingangle); trans->viewaiming = FIXED_TO_FLOAT(fixedaiming); trans->shearing = true; - gr_aimingangle = 0; + gl_aimingangle = 0; } else { trans->shearing = false; - gr_aimingangle = aimingangle; + gl_aimingangle = aimingangle; } - trans->anglex = (float)(gr_aimingangle>>ANGLETOFINESHIFT)*(360.0f/(float)FINEANGLES); + trans->anglex = (float)(gl_aimingangle>>ANGLETOFINESHIFT)*(360.0f/(float)FINEANGLES); } void HWR_SetTransform(float fpov, player_t *player) { - postimg_t *postprocessor = &postimgtype[0]; - INT32 i; - - gr_viewx = FIXED_TO_FLOAT(viewx); - gr_viewy = FIXED_TO_FLOAT(viewy); - gr_viewz = FIXED_TO_FLOAT(viewz); - gr_viewsin = FIXED_TO_FLOAT(viewsin); - gr_viewcos = FIXED_TO_FLOAT(viewcos); + gl_viewx = FIXED_TO_FLOAT(viewx); + gl_viewy = FIXED_TO_FLOAT(viewy); + gl_viewz = FIXED_TO_FLOAT(viewz); + gl_viewsin = FIXED_TO_FLOAT(viewsin); + gl_viewcos = FIXED_TO_FLOAT(viewcos); memset(&atransform, 0x00, sizeof(FTransform)); // Set T&L transform - atransform.x = gr_viewx; - atransform.y = gr_viewy; - atransform.z = gr_viewz; + atransform.x = gl_viewx; + atransform.y = gl_viewy; + atransform.z = gl_viewz; atransform.scalex = 1; atransform.scaley = (float)vid.width/vid.height; @@ -5241,41 +5155,33 @@ void HWR_SetTransform(float fpov, player_t *player) HWR_SetTransformAiming(&atransform); atransform.angley = (float)(viewangle>>ANGLETOFINESHIFT)*(360.0f/(float)FINEANGLES); - gr_viewludsin = FIXED_TO_FLOAT(FINECOSINE(gr_aimingangle>>ANGLETOFINESHIFT)); - gr_viewludcos = FIXED_TO_FLOAT(-FINESINE(gr_aimingangle>>ANGLETOFINESHIFT)); + gl_viewludsin = FIXED_TO_FLOAT(FINECOSINE(gl_aimingangle>>ANGLETOFINESHIFT)); + gl_viewludcos = FIXED_TO_FLOAT(-FINESINE(gl_aimingangle>>ANGLETOFINESHIFT)); atransform.fovxangle = fpov; // Tails atransform.fovyangle = fpov; // Tails HWR_RollTransform(&atransform, viewroll); atransform.splitscreen = splitscreen; - for (i = 0; i <= splitscreen; i++) - { - if (player != &players[displayplayers[i]]) - continue; - - postprocessor = &postimgtype[i]; - } - atransform.flip = false; - if (*postprocessor == postimg_flip) + if ((player->postimgflags & POSTIMG_FLIP) && !(player->postimgflags & POSTIMG_MIRROR)) atransform.flip = true; atransform.mirror = false; - if (*postprocessor == postimg_mirror) + if ((player->postimgflags & POSTIMG_MIRROR) && !(player->postimgflags & POSTIMG_FLIP)) atransform.mirror = true; atransform.mirrorflip = false; - if (*postprocessor == postimg_mirrorflip) + if ((player->postimgflags & POSTIMG_FLIP) && (player->postimgflags & POSTIMG_MIRROR)) atransform.mirrorflip = true; // Set transform. - HWD.pfnSetTransform(&atransform); + GL_SetTransform(&atransform); } void HWR_ClearClipper(void) { - angle_t a1 = gld_FrustumAngle(gr_aimingangle); + angle_t a1 = gld_FrustumAngle(gl_aimingangle); gld_clipper_Clear(); gld_clipper_SafeAddClipRange(viewangle + a1, viewangle - a1); #ifdef HAVE_SPHEREFRUSTRUM @@ -5283,114 +5189,35 @@ void HWR_ClearClipper(void) #endif } -// Adds an entry to the clipper for portal rendering -static void HWR_PortalClipping(gl_portal_t *portal) -{ - angle_t angle1, angle2; - - line_t *line = &lines[portal->clipline]; - - angle1 = R_PointToAngle64(line->v1->x, line->v1->y); - angle2 = R_PointToAngle64(line->v2->x, line->v2->y); - - // clip things that are not inside the portal window from our viewpoint - gld_clipper_SafeAddClipRange(angle2, angle1); -} - -enum -{ - HWR_STENCIL_NORMAL, - HWR_STENCIL_BEGIN, - HWR_STENCIL_REVERSE, - HWR_STENCIL_DEPTH, - HWR_STENCIL_SKY -}; - // Changes the current stencil state. -static void HWR_SetStencilState(int state, int level) +void HWR_SetStencilState(int state, int level) { if (level > -1) - HWD.pfnSetSpecialState(HWD_SET_STENCIL_LEVEL, level); - HWD.pfnSetSpecialState(HWD_SET_PORTAL_MODE, state); -} - -// Renders a portal segment. -static void HWR_RenderPortalSeg(gl_portal_t* portal, int state) -{ - gl_drawing_stencil = true; // do not draw outside of the stencil buffer, idiot. - // set our portal state and prepare to render the seg - gr_portal = state; - gr_curline = portal->seg; - gr_frontsector = portal->seg->frontsector; - gr_backsector = portal->seg->backsector; - HWR_ProcessSeg(); - gl_drawing_stencil = false; - // need to work around the r_opengl PF_Invisible bug with this call - // similarly as in the linkdraw hack in HWR_DrawSprites - HWD.pfnSetBlend(PF_Translucent|PF_Occlude|PF_Masked); + GL_SetSpecialState(HWD_SET_STENCIL_LEVEL, level); + GL_SetSpecialState(HWD_SET_PORTAL_MODE, state); } // Renders the current viewpoint, though takes portal arguments for recursive portals. -static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals); - -// Renders a single portal from the current viewpoint. -static void HWR_RenderPortal(gl_portal_t* portal, gl_portal_t* rootportal, const float fpov, player_t *player, int stencil_level) -{ - // draw portal seg to stencil buffer with increment - HWR_SetTransform(fpov, player); - HWR_ClearClipper(); - - HWR_SetStencilState(HWR_STENCIL_BEGIN, stencil_level); - HWR_RenderPortalSeg(portal, GRPORTAL_STENCIL); - - // go to portal frame lmao - HWR_PortalFrame(portal); - // call HWR_RenderViewpoint - HWR_RenderViewpoint(portal, fpov, player, stencil_level + 1, true); - // return to current frame - if (rootportal) - HWR_PortalFrame(rootportal); - else // current frame is not a portal frame but the main view! - { - R_SetupFrame(player, false); - portalclipline = NULL; - } - - // remove portal seg from stencil buffer - HWR_SetTransform(fpov, player); - HWR_ClearClipper(); - - HWR_SetStencilState(HWR_STENCIL_REVERSE, stencil_level); - HWR_RenderPortalSeg(portal, GRPORTAL_STENCIL); - - // draw portal seg to depth buffer - HWR_ClearClipper(); - HWR_SetStencilState(HWR_STENCIL_DEPTH, stencil_level); - HWR_RenderPortalSeg(portal, GRPORTAL_DEPTH); -} - -// Renders the current viewpoint, though takes portal arguments for recursive portals. -static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals) +void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals) { gl_portallist_t portallist; - gl_portal_t *portal; - gl_portal_t *gl_portal_temp; + const boolean skybox = (skyboxmo[0] && cv_skybox.value); - const boolean useportals = cv_grportals.value && gr_maphasportals && allow_portals; + const boolean useportals = cv_glportals.value && gl_maphasportals && allow_portals; portallist.base = portallist.cap = NULL; if (useportals && stencil_level < cv_maxportals.value) // if recursion limit is not reached { + gl_portal_t *portal; + // search for portals in current frame currentportallist = &portallist; - gr_portal = GRPORTAL_SEARCH; + HWR_SetPortalState(GLPORTAL_SEARCH); HWR_ClearClipper(); - if (!rootportal) - portalclipline = NULL; - else + if (rootportal) HWR_PortalClipping(rootportal); validcount++; @@ -5403,10 +5230,11 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, playe { HWR_RenderPortal(portal, rootportal, fpov, player, stencil_level); } - gr_portal = GRPORTAL_INSIDE;// when portal walls are encountered in following bsp traversal, nothing should be drawn + + HWR_SetPortalState(GLPORTAL_INSIDE); // when portal walls are encountered in following bsp traversal, nothing should be drawn } else - gr_portal = GRPORTAL_OFF;// there may be portals and they need to be drawn as regural walls + HWR_SetPortalState(GLPORTAL_OFF); // there may be portals and they need to be drawn as regural walls // draw normal things in current frame in current incremented stencil buffer area HWR_SetStencilState(HWR_STENCIL_NORMAL, stencil_level); @@ -5416,21 +5244,14 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, playe HWR_ClearSprites(); HWR_ClearClipper(); - if (useportals) + if (useportals && rootportal) { - if (!rootportal) - portalclipline = NULL; - else - { - HWR_PortalFrame(rootportal);// for portalclipsector, it could have gone null from search - HWR_PortalClipping(rootportal); - } + HWR_PortalFrame(rootportal);// for portalclipsector, it could have gone null from search + HWR_PortalClipping(rootportal); } - else - portalclipline = NULL; - + // Set transform. - HWD.pfnSetTransform(&atransform); + GL_SetTransform(&atransform); validcount++; @@ -5438,31 +5259,31 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, playe ps_numpolyobjects.value.i = 0; PS_START_TIMING(ps_bsptime); - if (cv_grbatching.value) + if (cv_glbatching.value) HWR_StartBatching(); if (useportals && !rootportal && portallist.base && !skybox) // if portals have been drawn in the main view, then render skywalls differently - gr_collect_skywalls = true; + gl_collect_skywalls = true; // HAYA: Save the old portal state, and turn portals off while normally rendering the BSP tree. // This fixes specific effects not working, such as horizon lines. - int oldgl_portal_state = gr_portal; + SINT8 oldgl_portal_state = gl_portal_state; - if (gr_portal != GRPORTAL_OFF) // if we already haven't hit the recursion limit or we already ended our portal shenanigans - gr_portal = GRPORTAL_INSIDE; // TURN IT OFF + if (gl_portal_state != GLPORTAL_OFF) // if we already haven't hit the recursion limit or we already ended our portal shenanigans + HWR_SetPortalState(GLPORTAL_INSIDE); // TURN IT OFF // Recursively "render" the BSP tree. HWR_RenderBSPNode((INT32)numnodes-1); // woo we back - gr_portal = oldgl_portal_state; + HWR_SetPortalState(oldgl_portal_state); if (allow_portals) // looks weird, but this is only true when its not skybox rendering skipping precip in skyboxes like software does HWR_AddPrecipitationSprites(); PS_STOP_TIMING(ps_bsptime); - if (cv_grbatching.value) + if (cv_glbatching.value) HWR_RenderBatches(); if (skyWallVertexArraySize) // if there are skywalls to draw using the alternate method @@ -5472,14 +5293,14 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, playe HWR_SkyWallList_Clear(); HWR_SetStencilState(HWR_STENCIL_NORMAL, 1); drewsky = false; - HWR_DrawSkyBackground(fpov); + HWR_DrawSkyBackground(); HWR_SetStencilState(HWR_STENCIL_NORMAL, 0); - HWD.pfnClearBuffer(false, false, true, 0);// clear skywall markings from the stencil buffer + GL_ClearBuffer(false, false, true, 0);// clear skywall markings from the stencil buffer HWR_SetTransform(fpov, player);// restore transform } - gr_collect_skywalls = false; - - ps_numsprites.value.i = gr_visspritecount; + gl_collect_skywalls = false; + + ps_numsprites.value.i = gl_visspritecount; PS_START_TIMING(ps_hw_spritesorttime); HWR_SortVisSprites(); PS_STOP_TIMING(ps_hw_spritesorttime); @@ -5492,42 +5313,29 @@ static void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, playe ps_hw_nodedrawtime.value.p = 0; HWR_RenderDrawNodes(); - // free memory from portal list allocated by calls to Add2Lines - gl_portal_temp = portallist.base; - while (gl_portal_temp) - { - gl_portal_t *nextportal = gl_portal_temp->next; - Z_Free(gl_portal_temp); - gl_portal_temp = nextportal; - } + HWR_FreePortalList(portallist); } // ========================================================================== // Render the current frame. // ========================================================================== -void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox) +static void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox) { const float fpov = FIXED_TO_FLOAT(cv_fov.value+player->fovadd); // set window position - gr_centerx = gr_basecenterx; - gr_viewwindowx = gr_baseviewwindowx; - gr_windowcenterx = gr_basewindowcenterx; - gr_centery = gr_basecentery; - gr_viewwindowy = gr_baseviewwindowy; - gr_windowcentery = gr_basewindowcentery; + gl_viewwindowx = gl_baseviewwindowx; + gl_viewwindowy = gl_baseviewwindowy; if ((splitscreen == 1 && viewnumber == 1) || (splitscreen > 1 && viewnumber > 1)) { - gr_viewwindowy += gr_viewheight; - gr_windowcentery += gr_viewheight; + gl_viewwindowy += gl_viewheight; } if (splitscreen > 1 && viewnumber & 1) { - gr_viewwindowx += gr_viewwidth; - gr_windowcenterx += gr_viewwidth; + gl_viewwindowx += gl_viewwidth; } if (splitscreen == 2 && player == &players[displayplayers[2]]) @@ -5550,28 +5358,28 @@ void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox) ST_doPaletteStuff(); // Draw the sky background. - HWR_DrawSkyBackground(fpov); + HWR_DrawSkyBackground(); if (skybox) drewsky = true; current_bsp_culling_distance = 0; - if (!skybox && cv_grrenderdistance.value) + if (!skybox && cv_glrenderdistance.value) { - HWD.pfnGClipRect((INT32)gr_viewwindowx, - (INT32)gr_viewwindowy, - (INT32)(gr_viewwindowx + gr_viewwidth), - (INT32)(gr_viewwindowy + gr_viewheight), - ZCLIP_PLANE, clipping_distances[cv_grrenderdistance.value - 1]); - current_bsp_culling_distance = bsp_culling_distances[cv_grrenderdistance.value - 1]; + GL_GClipRect((INT32)gl_viewwindowx, + (INT32)gl_viewwindowy, + (INT32)(gl_viewwindowx + gl_viewwidth), + (INT32)(gl_viewwindowy + gl_viewheight), + ZCLIP_PLANE, clipping_distances[cv_glrenderdistance.value - 1]); + current_bsp_culling_distance = bsp_culling_distances[cv_glrenderdistance.value - 1]; } portalclipline = NULL; HWR_RenderViewpoint(NULL, fpov, player, 0, !skybox); // Unset transform and shader - HWD.pfnSetTransform(NULL); - HWD.pfnUnSetShader(); + GL_SetTransform(NULL); + GL_UnSetShader(); // Run post processor effects if (!skybox) @@ -5579,7 +5387,7 @@ void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox) // added by Hurdler for correct splitscreen // moved here by hurdler so it works with the new near clipping plane - HWD.pfnGClipRect(0, 0, vid.width, vid.height, NZCLIP_PLANE, FAR_ZCLIP_DEFAULT); + GL_GClipRect(0, 0, vid.width, vid.height, NZCLIP_PLANE, FAR_ZCLIP_DEFAULT); } // ========================================================================== @@ -5599,19 +5407,23 @@ void HWR_RenderPlayerView(INT32 viewnumber, player_t *player) { const boolean skybox = (skyboxmo[0] && cv_skybox.value); // True if there's a skybox object and skyboxes are on - FRGBAFloat ClearColor; - - ClearColor.red = 0.0f; - ClearColor.green = 0.0f; - ClearColor.blue = 0.0f; - ClearColor.alpha = 1.0f; - // Clear the color buffer, stops HOMs. Also seems to fix the skybox issue on Intel GPUs. if (viewnumber == 0) // Only do it if it's the first screen being rendered - HWD.pfnClearBuffer(true, false, false, &ClearColor); + { + FRGBAFloat ClearColor; - if (cv_grshaders.value) - HWD.pfnSetShaderInfo(HWD_SHADERINFO_LEVELTIME, (INT32)leveltime); // The water surface shader needs the leveltime. + ClearColor.red = 0.0f; + ClearColor.green = 0.0f; + ClearColor.blue = 0.0f; + ClearColor.alpha = 1.0f; + + GL_ClearBuffer(true, false, false, &ClearColor); + } + + if (HWR_UseShader() && cv_ripplewater.value) + { + GL_SetShaderInfo(HWD_SHADERINFO_LEVELTIME, (INT32)leveltime); // The water surface shader needs the leveltime. + } if (viewnumber > 3) return; @@ -5621,12 +5433,12 @@ void HWR_RenderPlayerView(INT32 viewnumber, player_t *player) drewsky = false; if (skybox) { - R_SkyboxFrame(player); + R_SkyboxFrame(viewssnum); HWR_RenderFrame(viewnumber, player, true); } PS_STOP_TIMING(ps_skyboxtime); - R_SetupFrame(player, false); // This can stay false because it is only used to set viewsky in r_main.c, which isn't used here + R_SetupFrame(viewssnum, false); // This can stay false because it is only used to set viewsky in r_main.c, which isn't used here framecount++; // for timedemo HWR_RenderFrame(viewnumber, player, false); } @@ -5646,6 +5458,10 @@ void HWR_LoadLevel(void) HWR_CreatePlanePolygons((INT32)numnodes - 1); + // Build the sky dome + HWR_ClearSkyDome(); + HWR_BuildSkyDome(); + if (HWR_ShouldUsePaletteRendering()) HWR_SetMapPalette(); } @@ -5653,15 +5469,15 @@ void HWR_LoadLevel(void) // enable or disable palette rendering state depending on settings and availability // called when relevant settings change // shader recompilation is done in the cvar callback -void HWR_TogglePaletteRendering(void) +static void HWR_TogglePaletteRendering(void) { // which state should we go to? if (HWR_ShouldUsePaletteRendering()) { // are we not in that state already? - if (!gr_palette_rendering_state) + if (!gl_palette_rendering_state) { - gr_palette_rendering_state = true; + gl_palette_rendering_state = true; // The textures will still be converted to RGBA by r_opengl. // This however makes hw_cache use paletted blending for composite textures! @@ -5674,21 +5490,21 @@ void HWR_TogglePaletteRendering(void) // If the r_opengl "texture palette" stays the same during this switch, these textures // will not be cleared out. However they are still out of date since the // composite texture blending method has changed. Therefore they need to be cleared. - HWD.pfnClearMipMapCache(); + GL_ClearMipMapCache(); } } else { // are we not in that state already? - if (gr_palette_rendering_state) + if (gl_palette_rendering_state) { - gr_palette_rendering_state = false; + gl_palette_rendering_state = false; textureformat = GL_TEXFMT_RGBA; HWR_SetPalette(pLocalPalette); // If the r_opengl "texture palette" stays the same during this switch, these textures // will not be cleared out. However they are still out of date since the // composite texture blending method has changed. Therefore they need to be cleared. - HWD.pfnClearMipMapCache(); + GL_ClearMipMapCache(); } } } @@ -5696,46 +5512,43 @@ void HWR_TogglePaletteRendering(void) //added by Hurdler: console varibale that are saved void HWR_AddCommands(void) { - CV_RegisterVar(&cv_grfiltermode); - CV_RegisterVar(&cv_granisotropicmode); - CV_RegisterVar(&cv_grsolvetjoin); - - CV_RegisterVar(&cv_grbatching); - - CV_RegisterVar(&cv_splitwallfix); - - CV_RegisterVar(&cv_grrenderdistance); - - CV_RegisterVar(&cv_grfakecontrast); - CV_RegisterVar(&cv_grslopecontrast); - CV_RegisterVar(&cv_grhorizonlines); - - CV_RegisterVar(&cv_grfovchange); - - CV_RegisterVar(&cv_grmdls); - CV_RegisterVar(&cv_grfallbackplayermodel); - - CV_RegisterVar(&cv_grspritebillboarding); - - CV_RegisterVar(&cv_grshearing); - - CV_RegisterVar(&cv_grshaders); - - CV_RegisterVar(&cv_grportals); - - CV_RegisterVar(&cv_secbright); - - CV_RegisterVar(&cv_grpaletterendering); - CV_RegisterVar(&cv_grpalettedepth); - CV_RegisterVar(&cv_grflashpal); - - CV_RegisterVar(&cv_lightdither); + CV_RegisterVar(&cv_glscreentextures); #ifdef USE_FBO_OGL - CV_RegisterVar(&cv_grframebuffer); + CV_RegisterVar(&cv_glframebuffer); #endif - CV_RegisterVar(&cv_grscreentextures); + CV_RegisterVar(&cv_glmdls); + CV_RegisterVar(&cv_glfallbackplayermodel); + + CV_RegisterVar(&cv_glspritebillboarding); + CV_RegisterVar(&cv_glshearing); + + CV_RegisterVar(&cv_glfakecontrast); + CV_RegisterVar(&cv_glslopecontrast); + + CV_RegisterVar(&cv_glshaders); + + CV_RegisterVar(&cv_gllightdither); + CV_RegisterVar(&cv_glsecbright); + + CV_RegisterVar(&cv_glfiltermode); + CV_RegisterVar(&cv_glanisotropicmode); + + CV_RegisterVar(&cv_glsolvetjoin); + + CV_RegisterVar(&cv_glbatching); + + CV_RegisterVar(&cv_glrenderdistance); + + CV_RegisterVar(&cv_glhorizonlines); + CV_RegisterVar(&cv_glportals); + + CV_RegisterVar(&cv_glfovchange); + + CV_RegisterVar(&cv_glpaletterendering); + CV_RegisterVar(&cv_glpalettedepth); + CV_RegisterVar(&cv_glflashpal); } // -------------------------------------------------------------------------- @@ -5750,26 +5563,92 @@ void HWR_Startup(void) { CONS_Printf("HWR_Startup()...\n"); textureformat = patchformat = GL_TEXFMT_RGBA; - + HWR_InitTextureCache(); HWR_InitMD2(); - gr_shadersavailable = HWR_InitShaders(); + gl_shadersavailable = HWR_InitShaders(); HWR_SetShaderState(); HWR_LoadAllCustomShaders(); HWR_TogglePaletteRendering(); -#ifdef USE_FBO_OGL - HWD.pfnSetSpecialState(HWD_SET_FRAMEBUFFER, cv_grframebuffer.value); -#endif - if (msaa) - HWD.pfnSetSpecialState(HWD_SET_MSAA, a2c ? 2 : 1); + GL_SetSpecialState(HWD_SET_MSAA, a2c ? 2 : 1); + + HWR_RegisterCommands(); } startupdone = true; } +/** + * Register renderer commands. + */ +static void HWR_RegisterCommands(void) +{ + COM_AddCommand("gr_glinfo", COM_HWR_glinfo); +} + +static void COM_HWR_glinfo(void) +{ + if (vid.glstate != VID_GL_LIBRARY_LOADED) + { + CONS_Printf("Currently not using the OpenGL renderer.\n"); + return; + } + + int list_extensions = 0; + size_t argc = COM_Argc(); + const char *argv; + for (size_t i = 1; i < argc; i++) + { + argv = COM_Argv(i); + + if (strcmp(argv, "--list-extensions") == 0 || strcmp(argv, "-l") == 0) + { + list_extensions = 1; + } + else + { + CONS_Printf("Unrecognized argument: %s\n", argv); + return; + } + + } + + CONS_Printf("\x88OpenGL %s\x80\n", gl_version); + CONS_Printf("Renderer: %s\n", gl_renderer); + CONS_Printf("Vendor: %s\n", gl_vendor); + + CONS_Printf("%u GL extensions present.\n", gl_num_extensions); + if (list_extensions) + { + // We need this strtok loop because we cannot write the extensions list directly + // to the output buffer, because it will overflow the output buffer of CONS_Printf + // if the GPU is super new and supports a bajillion extensions - xyzzy + + char *copy = strdup((const char*)gl_extensions); + char *ext = strtok(copy, " "); + + if (copy == NULL) + { + CONS_Printf("Ran out of memory listing extensions?!?!"); + return; + } + + do + { + CONS_Printf(" - %s\n", ext); + } while ((ext = strtok(NULL, " ")) != NULL); + + free(copy); + } + else + { + CONS_Printf("Use --list-extensions to view the list of extensions.\n"); + } +} + // -------------------------------------------------------------------------- // Free resources allocated by the hardware renderer // -------------------------------------------------------------------------- @@ -5779,17 +5658,17 @@ void HWR_Shutdown(void) HWR_FreeExtraSubsectors(); HWR_FreeMipmapCache(); HWR_FreeTextureCache(); - HWD.pfnFlushScreenTextures(); + GL_FlushScreenTextures(); #ifdef USE_FBO_OGL - GLFramebuffer_Disable(); + GL_Framebuffer_Disable(); #endif } -void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap) +static void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap) { FBITFIELD blendmode = blend; UINT8 alpha = pSurf->PolyColor.s.alpha; // retain the alpha - + INT32 shader = SHADER_NONE; // Lighting is done here instead so that fog isn't drawn incorrectly on transparent walls after sorting @@ -5809,39 +5688,27 @@ void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, blendmode |= PF_ColorMapped; } - + if (fogwall) blendmode |= PF_Fog; - + blendmode |= PF_Modulated; // No PF_Occlude means overlapping (incorrect) transparency HWR_ProcessPolygon(pSurf, wallVerts, 4, blendmode, shader, false); #ifdef WALLSPLATS - if (gr_curline->linedef->splats && cv_splats.value) + if (gl_curline->linedef->splats && cv_splats.value) HWR_DrawSegsSplats(pSurf); #endif } INT32 HWR_GetTextureUsed(void) { - return HWD.pfnGetTextureUsed(); + return GL_GetTextureUsed(); } -void HWR_DoPostProcessor(player_t *player) +static void HWR_DoPostProcessor(player_t *player) { - postimg_t *type = &postimgtype[0]; - UINT8 i; - - HWD.pfnUnSetShader(); - - for (i = splitscreen; i > 0; i--) - { - if (player != &players[displayplayers[i]]) - continue; - - type = &postimgtype[i]; - break; - } + GL_UnSetShader(); // Armageddon Blast Flash! // Could this even be considered postprocessor? @@ -5865,21 +5732,21 @@ void HWR_DoPostProcessor(player_t *player) Surf.PolyColor.s.alpha = 0xc0; // match software mode - HWD.pfnDrawPolygon(&Surf, v, 4, PF_Modulated|PF_Translucent|PF_NoTexture|PF_NoDepthTest); + GL_DrawPolygon(&Surf, v, 4, PF_Modulated|PF_Translucent|PF_NoTexture|PF_NoDepthTest); } - if (cv_grscreentextures.value != 2) // screen textures are needed for the rest of the effects + if (cv_glscreentextures.value != 2) // screen textures are needed for the rest of the effects return; // Capture the screen for intermission and screen waving if (gamestate != GS_INTERMISSION) - HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); + GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); if (splitscreen) // Not supported in splitscreen - someone want to add support? return; // Drunken vision! WooOOooo~ - if (*type == postimg_water || *type == postimg_heat) + if (player->postimgflags & POSTIMG_WATER || player->postimgflags & POSTIMG_HEAT) { // 10 by 10 grid. 2 coordinates (xy) float v[SCREENVERTS][SCREENVERTS][2]; @@ -5891,7 +5758,7 @@ void HWR_DoPostProcessor(player_t *player) INT32 FREQUENCY; // Modifies the wave. - if (*type == postimg_water) + if (player->postimgflags & POSTIMG_WATER) { WAVELENGTH = 5; AMPLITUDE = 20; @@ -5913,28 +5780,28 @@ void HWR_DoPostProcessor(player_t *player) v[x][y][1] = (y/((float)(SCREENVERTS-1.0f)/9.0f))-4.5f; } } - HWD.pfnPostImgRedraw(v); + GL_PostImgRedraw(v); // Capture the screen again for screen waving on the intermission if (gamestate != GS_INTERMISSION) - HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); + GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1); } // Flipping of the screen isn't done here anymore } void HWR_StartScreenWipe(void) { - HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_WIPE_START); + GL_MakeScreenTexture(HWD_SCREENTEXTURE_WIPE_START); } void HWR_EndScreenWipe(void) { - HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_WIPE_END); + GL_MakeScreenTexture(HWD_SCREENTEXTURE_WIPE_END); } void HWR_DrawIntermissionBG(void) { - HWD.pfnDrawScreenTexture(HWD_SCREENTEXTURE_GENERIC1, NULL, 0); + GL_DrawScreenTexture(HWD_SCREENTEXTURE_GENERIC1, NULL, 0); } void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) @@ -5943,7 +5810,7 @@ void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) lumpnum_t lumpnum; size_t lsize; - if (cv_grscreentextures.value == 0) + if (cv_glscreentextures.value == 0) { V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap return; @@ -5968,22 +5835,22 @@ void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) } HWR_GetFadeMask(lumpnum); - HWD.pfnDoScreenWipe(HWD_SCREENTEXTURE_WIPE_START, HWD_SCREENTEXTURE_WIPE_END); + GL_DoScreenWipe(HWD_SCREENTEXTURE_WIPE_START, HWD_SCREENTEXTURE_WIPE_END); } void HWR_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize) { - HWD.pfnRenderVhsEffect(upbary, downbary, updistort, downdistort, barsize); + GL_RenderVhsEffect(upbary, downbary, updistort, downdistort, barsize); } void HWR_MakeScreenFinalTexture(void) { - HWD.pfnMakeScreenTexture(HWD_SCREENTEXTURE_GENERIC2); + GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC2); } -void HWR_DrawScreenFinalTexture(INT32 width, INT32 height) +void HWR_DrawScreenFinalTexture(INT32 width, INT32 height, boolean useshader) { - HWD.pfnDrawScreenFinalTexture(HWD_SCREENTEXTURE_GENERIC2, width, height); + GL_DrawScreenFinalTexture(HWD_SCREENTEXTURE_GENERIC2, width, height, useshader); } #endif // HWRENDER diff --git a/src/hardware/hw_main.h b/src/hardware/hw_main.h index 2abb6dda6..52616b7e4 100644 --- a/src/hardware/hw_main.h +++ b/src/hardware/hw_main.h @@ -23,6 +23,7 @@ #include "hw_glob.h" #include "hw_data.h" #include "hw_defs.h" +#include "hw_portal.h" #include "../am_map.h" #include "../d_player.h" @@ -35,15 +36,32 @@ void HWR_Startup(void); void HWR_Shutdown(void); -extern float gr_viewwidth, gr_viewheight, gr_baseviewwindowx, gr_baseviewwindowy; +extern float gl_viewwidth, gl_viewheight, gl_baseviewwindowx, gl_baseviewwindowy; -extern float gr_basewindowcenterx, gr_basewindowcentery; +extern float gl_basewindowcenterx, gl_basewindowcentery; extern unsigned msaa; extern boolean a2c; extern FTransform atransform; -extern float gr_viewsin, gr_viewcos; +extern float gl_viewsin, gl_viewcos; + +extern boolean gl_drawing_stencil; + +extern seg_t *gl_curline; +extern side_t *gl_sidedef; +extern line_t *gl_linedef; +extern sector_t *gl_frontsector; +extern sector_t *gl_backsector; + +enum +{ + HWR_STENCIL_NORMAL, + HWR_STENCIL_BEGIN, + HWR_STENCIL_REVERSE, + HWR_STENCIL_DEPTH, + HWR_STENCIL_SKY +}; // Performance stats extern ps_metric_t ps_hw_nodesorttime; @@ -62,7 +80,7 @@ extern ps_metric_t ps_hw_numcolors; extern ps_metric_t ps_hw_batchsorttime; extern ps_metric_t ps_hw_batchdrawtime; -extern boolean gr_shadersavailable; +extern boolean gl_shadersavailable; // hw_draw.c void HWR_DrawPatch(GLPatch_t *gpatch, INT32 x, INT32 y, INT32 option); @@ -81,24 +99,28 @@ UINT8 *HWR_GetScreenshot(void); boolean HWR_Screenshot(const char *lbmname); // hw_main.c -void HWR_RenderFrame(INT32 viewnumber, player_t *player, boolean skybox); -void HWR_RenderPlayerView(INT32 viewnumber, player_t *player); void HWR_SetViewSize(void); void HWR_AddCommands(void); + +void HWR_RenderPlayerView(INT32 viewnumber, player_t *player); +void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals); + +void HWR_ClearSkyDome(void); +void HWR_BuildSkyDome(void); + void HWR_SetTransform(float fpov, player_t *player); void HWR_ClearClipper(void); +void HWR_SetStencilState(int state, int level); boolean HWR_UseShader(void); boolean HWR_ShouldUsePaletteRendering(void); boolean HWR_PalRenderFlashpal(void); -void HWR_TogglePaletteRendering(void); // My original intention was to split hw_main.c // into files like hw_bsp.c, hw_sprites.c... // hw_main.c: Lighting and fog void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *colormap); -UINT8 HWR_FogBlockAlpha(INT32 light, extracolormap_t *colormap); // Let's see if this can work FBITFIELD HWR_TranstableToAlpha(INT32 transtablenum, FSurfaceInfo *pSurf); @@ -106,79 +128,63 @@ FBITFIELD HWR_TranstableToAlpha(INT32 transtablenum, FSurfaceInfo *pSurf); INT32 HWR_GetTextureUsed(void); // hw_main.c: Post-rendering -void HWR_DoPostProcessor(player_t *player); void HWR_StartScreenWipe(void); void HWR_EndScreenWipe(void); void HWR_DrawIntermissionBG(void); void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum); void HWR_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize); void HWR_MakeScreenFinalTexture(void); -void HWR_DrawScreenFinalTexture(INT32 width, INT32 height); - -// hw_main.c: Planes -//void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, FBITFIELD PolyFlags, INT32 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap); -void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, boolean fogplane, extracolormap_t *planecolormap); - -void HWR_RenderPolyObjectPlane(polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, FBITFIELD blendmode, UINT8 lightlevel, lumpnum_t lumpnum, sector_t *FOFsector, UINT8 alpha, extracolormap_t *planecolormap); -void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, extracolormap_t *planecolormap); +void HWR_DrawScreenFinalTexture(INT32 width, INT32 height, boolean useshader); // hw_main.c: Segs void HWR_ProcessSeg(void); // Sort of like GLWall::Process in GZDoom -void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap); -void HWR_ProjectWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blendmode, INT32 lightlevel, extracolormap_t *wallcolormap); -void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo * pSurf, INT32 texnum, boolean noencore, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap); -// moved HWR_SplitWall to hw_main.c -void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf); -void HWR_DrawSkyBackground(float fpov); - -// hw_main.c: Sprites -void HWR_AddSprites(sector_t *sec); -void HWR_ProjectSprite(mobj_t *thing); -//void HWR_ProjectPrecipitationSprite(precipmobj_t *thing); -void HWR_DrawSprites(void); // hw_bsp.c void HWR_CreatePlanePolygons(INT32 bspnum); -extern boolean gr_maphasportals; +extern boolean gl_maphasportals; // hw_cache.c void HWR_LoadTextures(size_t pnumtextures); RGBA_t *HWR_GetTexturePalette(void); -void HWR_SetShaderState(void); - // Console variables -extern consvar_t cv_grshaders; +extern CV_PossibleValue_t glanisotropicmode_cons_t[]; + +extern consvar_t cv_glscreentextures; #ifdef USE_FBO_OGL -extern consvar_t cv_grframebuffer; +extern consvar_t cv_glframebuffer; #endif -extern consvar_t cv_splitwallfix; -extern consvar_t cv_grshearing; -extern consvar_t cv_grfov; -extern consvar_t cv_grmdls; -extern consvar_t cv_grfog; -extern consvar_t cv_grfogdensity; -extern consvar_t cv_grfiltermode; -extern consvar_t cv_granisotropicmode; -extern consvar_t cv_grcorrecttricks; -extern consvar_t cv_grfovchange; -extern consvar_t cv_grsolvetjoin; -extern consvar_t cv_grspritebillboarding; -extern consvar_t cv_grfakecontrast; -extern consvar_t cv_grslopecontrast; -extern consvar_t cv_grhorizonlines; -extern consvar_t cv_grfallbackplayermodel; -extern consvar_t cv_grbatching; -extern consvar_t cv_grrenderdistance; -extern consvar_t cv_grpaletterendering; -extern consvar_t cv_grpalettedepth; -extern consvar_t cv_grflashpal; -extern consvar_t cv_lightdither; -extern consvar_t cv_grscreentextures; -extern consvar_t cv_grportals; -extern consvar_t cv_nostencil; -extern consvar_t cv_secbright; -extern CV_PossibleValue_t granisotropicmode_cons_t[]; +extern consvar_t cv_glmdls; +extern consvar_t cv_glfallbackplayermodel; + +extern consvar_t cv_glspritebillboarding; +extern consvar_t cv_glshearing; + +extern consvar_t cv_glfakecontrast; +extern consvar_t cv_glslopecontrast; + +extern consvar_t cv_glshaders; + +extern consvar_t cv_gllightdither; +extern consvar_t cv_glsecbright; + +extern consvar_t cv_glfiltermode; +extern consvar_t cv_glanisotropicmode; + +extern consvar_t cv_glsolvetjoin; + +extern consvar_t cv_glbatching; + +extern consvar_t cv_glrenderdistance; + +extern consvar_t cv_glhorizonlines; +extern consvar_t cv_glportals; + +extern consvar_t cv_glfovchange; + +extern consvar_t cv_glpaletterendering; +extern consvar_t cv_glpalettedepth; +extern consvar_t cv_glflashpal; #endif diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index c71f47185..c21823a36 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -25,12 +25,14 @@ #include "../doomstat.h" #ifdef HWRENDER -#include "hw_drv.h" + +#include "hw_gl.h" #include "hw_md2.h" #include "../d_main.h" #include "../r_bsp.h" #include "../r_fps.h" #include "../r_main.h" +#include "../p_setup.h" #include "../m_misc.h" #include "../w_wad.h" #include "../z_zone.h" @@ -43,8 +45,8 @@ #include "hw_main.h" #include "../v_video.h" -#ifdef HAVE_PNG +#ifdef HAVE_PNG #ifndef _MSC_VER #ifndef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE @@ -147,7 +149,7 @@ static void PNG_warn(png_structp PNG, png_const_charp pngtext) CONS_Debug(DBG_RENDER, "libpng warning at %p: %s", PNG, pngtext); } -static GLTextureFormat_t PNG_Load(const char *filename, int *w, int *h, GLPatch_t *grpatch) +static GLTextureFormat_t PNG_Load(const char *filename, int *w, int *h, GLPatch_t *glpatch) { png_structp png_ptr; png_infop png_info_ptr; @@ -201,7 +203,7 @@ static GLTextureFormat_t PNG_Load(const char *filename, int *w, int *h, GLPatch_ //CONS_Debug(DBG_RENDER, "libpng load error on %s\n", filename); png_destroy_read_struct(&png_ptr, &png_info_ptr, NULL); fclose(png_FILE); - Z_Free(grpatch->mipmap->data); + Z_Free(glpatch->mipmap->data); return 0; } #ifdef USE_FAR_KEYWORD @@ -242,7 +244,7 @@ static GLTextureFormat_t PNG_Load(const char *filename, int *w, int *h, GLPatch_ { png_uint_32 i, pitch = png_get_rowbytes(png_ptr, png_info_ptr); - png_bytep PNG_image = Z_Malloc(pitch*height, PU_HWRCACHE, &grpatch->mipmap->data); + png_bytep PNG_image = Z_Malloc(pitch*height, PU_HWRCACHE, &glpatch->mipmap->data); png_bytepp row_pointers = png_malloc(png_ptr, height * sizeof (png_bytep)); for (i = 0; i < height; i++) row_pointers[i] = PNG_image + i*pitch; @@ -282,7 +284,7 @@ typedef struct } PcxHeader; static GLTextureFormat_t PCX_Load(const char *filename, int *w, int *h, - GLPatch_t *grpatch) + GLPatch_t *glpatch) { PcxHeader header; #define PALSIZE 768 @@ -322,7 +324,7 @@ static GLTextureFormat_t PCX_Load(const char *filename, int *w, int *h, pw = *w = header.xmax - header.xmin + 1; ph = *h = header.ymax - header.ymin + 1; - image = Z_Malloc(pw*ph*4, PU_HWRCACHE, &grpatch->mipmap->data); + image = Z_Malloc(pw*ph*4, PU_HWRCACHE, &glpatch->mipmap->data); if (fread(palette, sizeof (UINT8), PALSIZE, file) != PALSIZE) { @@ -364,43 +366,43 @@ static GLTextureFormat_t PCX_Load(const char *filename, int *w, int *h, // -----------------+ static void md2_loadTexture(md2_t *model) { - GLPatch_t *grpatch; + GLPatch_t *glpatch; const char *filename = model->filename; - if (model->grpatch) + if (model->glpatch) { - grpatch = model->grpatch; - Z_Free(grpatch->mipmap->data); + glpatch = model->glpatch; + Z_Free(glpatch->mipmap->data); } else { - grpatch = Z_Calloc(sizeof *grpatch, PU_HWRPATCHINFO, - &(model->grpatch)); - grpatch->mipmap = Z_Calloc(sizeof (GLMipmap_t), PU_HWRPATCHINFO, NULL); + glpatch = Z_Calloc(sizeof *glpatch, PU_HWRPATCHINFO, + &(model->glpatch)); + glpatch->mipmap = Z_Calloc(sizeof (GLMipmap_t), PU_HWRPATCHINFO, NULL); } - if (!grpatch->mipmap->downloaded && !grpatch->mipmap->data) + if (!glpatch->mipmap->downloaded && !glpatch->mipmap->data) { int w = 0, h = 0; #ifdef HAVE_PNG - grpatch->mipmap->format = PNG_Load(filename, &w, &h, grpatch); - if (grpatch->mipmap->format == 0) + glpatch->mipmap->format = PNG_Load(filename, &w, &h, glpatch); + if (glpatch->mipmap->format == 0) #endif - grpatch->mipmap->format = PCX_Load(filename, &w, &h, grpatch); - if (grpatch->mipmap->format == 0) + glpatch->mipmap->format = PCX_Load(filename, &w, &h, glpatch); + if (glpatch->mipmap->format == 0) { - grpatch->notfound = true;// mark it so its not searched for again repeatedly + glpatch->notfound = true;// mark it so its not searched for again repeatedly return; } - grpatch->mipmap->downloaded = 0; - grpatch->mipmap->flags = 0; + glpatch->mipmap->downloaded = 0; + glpatch->mipmap->flags = 0; - grpatch->width = (INT16)w; - grpatch->height = (INT16)h; - grpatch->mipmap->width = (UINT16)w; - grpatch->mipmap->height = (UINT16)h; + glpatch->width = (INT16)w; + glpatch->height = (INT16)h; + glpatch->mipmap->width = (UINT16)w; + glpatch->mipmap->height = (UINT16)h; // for palette rendering, color cube is applied in post-processing instead of here if (!HWR_ShouldUsePaletteRendering()) @@ -408,7 +410,7 @@ static void md2_loadTexture(md2_t *model) UINT32 size; RGBA_t *image; // Lactozilla: Apply colour cube - image = grpatch->mipmap->data; + image = glpatch->mipmap->data; size = w*h; while (size--) { @@ -417,8 +419,8 @@ static void md2_loadTexture(md2_t *model) } } } - HWD.pfnSetTexture(grpatch->mipmap); - HWR_UnlockCachedPatch(grpatch); + GL_SetTexture(glpatch->mipmap); + HWR_UnlockCachedPatch(glpatch); } // -----------------+ @@ -426,49 +428,49 @@ static void md2_loadTexture(md2_t *model) // -----------------+ static void md2_loadBlendTexture(md2_t *model) { - GLPatch_t *grpatch; + GLPatch_t *glpatch; char *filename = Z_Malloc(strlen(model->filename)+7, PU_STATIC, NULL); strcpy(filename, model->filename); FIL_ForceExtension(filename, "_blend.png"); - if (model->blendgrpatch) + if (model->blendglpatch) { - grpatch = model->blendgrpatch; - Z_Free(grpatch->mipmap->data); + glpatch = model->blendglpatch; + Z_Free(glpatch->mipmap->data); } else { - grpatch = Z_Calloc(sizeof *grpatch, PU_HWRPATCHINFO, - &(model->blendgrpatch)); - grpatch->mipmap = Z_Calloc(sizeof (GLMipmap_t), PU_HWRPATCHINFO, NULL); + glpatch = Z_Calloc(sizeof *glpatch, PU_HWRPATCHINFO, + &(model->blendglpatch)); + glpatch->mipmap = Z_Calloc(sizeof (GLMipmap_t), PU_HWRPATCHINFO, NULL); } - if (!grpatch->mipmap->downloaded && !grpatch->mipmap->data) + if (!glpatch->mipmap->downloaded && !glpatch->mipmap->data) { int w = 0, h = 0; #ifdef HAVE_PNG - grpatch->mipmap->format = PNG_Load(filename, &w, &h, grpatch); - if (grpatch->mipmap->format == 0) + glpatch->mipmap->format = PNG_Load(filename, &w, &h, glpatch); + if (glpatch->mipmap->format == 0) #endif - grpatch->mipmap->format = PCX_Load(filename, &w, &h, grpatch); - if (grpatch->mipmap->format == 0) + glpatch->mipmap->format = PCX_Load(filename, &w, &h, glpatch); + if (glpatch->mipmap->format == 0) { - grpatch->notfound = true;// mark it so its not searched for again repeatedly + glpatch->notfound = true;// mark it so its not searched for again repeatedly Z_Free(filename); return; } - grpatch->mipmap->downloaded = 0; - grpatch->mipmap->flags = 0; + glpatch->mipmap->downloaded = 0; + glpatch->mipmap->flags = 0; - grpatch->width = (INT16)w; - grpatch->height = (INT16)h; - grpatch->mipmap->width = (UINT16)w; - grpatch->mipmap->height = (UINT16)h; + glpatch->width = (INT16)w; + glpatch->height = (INT16)h; + glpatch->mipmap->width = (UINT16)w; + glpatch->mipmap->height = (UINT16)h; } - HWD.pfnSetTexture(grpatch->mipmap); // We do need to do this so that it can be cleared and knows to recreate it when necessary - HWR_UnlockCachedPatch(grpatch); + GL_SetTexture(glpatch->mipmap); // We do need to do this so that it can be cleared and knows to recreate it when necessary + HWR_UnlockCachedPatch(glpatch); Z_Free(filename); } @@ -489,7 +491,7 @@ void HWR_InitMD2(void) { md2_playermodels[s].scale = -1.0f; md2_playermodels[s].model = NULL; - md2_playermodels[s].grpatch = NULL; + md2_playermodels[s].glpatch = NULL; md2_playermodels[s].skin = -1; md2_playermodels[s].notfound = true; md2_playermodels[s].error = false; @@ -498,7 +500,7 @@ void HWR_InitMD2(void) { md2_localplayermodels[s].scale = -1.0f; md2_localplayermodels[s].model = NULL; - md2_localplayermodels[s].grpatch = NULL; + md2_localplayermodels[s].glpatch = NULL; md2_localplayermodels[s].skin = -1; md2_localplayermodels[s].notfound = true; md2_localplayermodels[s].error = false; @@ -507,7 +509,7 @@ void HWR_InitMD2(void) { md2_models[i].scale = -1.0f; md2_models[i].model = NULL; - md2_models[i].grpatch = NULL; + md2_models[i].glpatch = NULL; md2_models[i].skin = -1; md2_models[i].notfound = true; md2_models[i].error = false; @@ -680,7 +682,7 @@ spritemd2found: #define SETBRIGHTNESS(brightness,r,g,b) \ brightness = (UINT8)(((1063*(UINT32)(r))/5000) + ((3576*(UINT32)(g))/5000) + ((361*(UINT32)(b))/5000)) -static void HWR_CreateBlendedTexture(GLPatch_t *gpatch, GLPatch_t *blendgpatch, GLMipmap_t *grmip, INT32 skinnum, skincolors_t color) +static void HWR_CreateBlendedTexture(GLPatch_t *gpatch, GLPatch_t *blendgpatch, GLMipmap_t *glMipmap, INT32 skinnum, skincolors_t color) { UINT16 w = gpatch->width, h = gpatch->height; UINT32 size = w*h; @@ -696,24 +698,24 @@ static void HWR_CreateBlendedTexture(GLPatch_t *gpatch, GLPatch_t *blendgpatch, memset(translation, 0, sizeof(translation)); memset(cutoff, 0, sizeof(cutoff)); - if (grmip->width == 0) + if (glMipmap->width == 0) { - grmip->width = gpatch->width; - grmip->height = gpatch->height; + glMipmap->width = gpatch->width; + glMipmap->height = gpatch->height; // no wrap around, no chroma key - grmip->flags = 0; + glMipmap->flags = 0; // setup the texture info - grmip->format = GL_TEXFMT_RGBA; + glMipmap->format = GL_TEXFMT_RGBA; } - if (grmip->data) + if (glMipmap->data) { - Z_Free(grmip->data); - grmip->data = NULL; + Z_Free(glMipmap->data); + glMipmap->data = NULL; } - cur = Z_Malloc(size*4, PU_HWRCACHE, &grmip->data); + cur = Z_Malloc(size*4, PU_HWRCACHE, &glMipmap->data); memset(cur, 0x00, size*4); image = gpatch->mipmap->data; @@ -794,10 +796,9 @@ static void HWR_CreateBlendedTexture(GLPatch_t *gpatch, GLPatch_t *blendgpatch, } } } - } - if (translen > 0) colorbrightnesses[translen] = colorbrightnesses[translen-1]; + } while (size--) { @@ -1044,28 +1045,29 @@ skippixel: static void HWR_GetBlendedTexture(GLPatch_t *gpatch, GLPatch_t *blendgpatch, INT32 skinnum, const UINT8 *colormap, skincolors_t color) { // mostly copied from HWR_GetMappedPatch, hence the similarities and comment - GLMipmap_t *grmip, *newmip; + GLMipmap_t *glMipmap, *newMipmap; if (colormap == colormaps || colormap == NULL) { // Don't do any blending - HWD.pfnSetTexture(gpatch->mipmap); + GL_SetTexture(gpatch->mipmap); return; } - // search for the mimmap + // search for the Mipmap // skip the first (no colormap translated) - for (grmip = gpatch->mipmap; grmip->nextcolormap; ) + for (glMipmap = gpatch->mipmap; glMipmap->nextcolormap; ) { - grmip = grmip->nextcolormap; - if (grmip->colormap == colormap) + glMipmap = glMipmap->nextcolormap; + + if (glMipmap->colormap != colormap) + continue; + + if (glMipmap->downloaded && glMipmap->data) { - if (grmip->downloaded && grmip->data) - { - HWD.pfnSetTexture(grmip); // found the colormap, set it to the correct texture - Z_ChangeTag(grmip->data, PU_HWRCACHE_UNLOCKED); - return; - } + GL_SetTexture(glMipmap); // found the colormap, set it to the correct texture + Z_ChangeTag(glMipmap->data, PU_HWRCACHE_UNLOCKED); + return; } } @@ -1076,26 +1078,25 @@ static void HWR_GetBlendedTexture(GLPatch_t *gpatch, GLPatch_t *blendgpatch, INT // (it have a liste of mipmap) // this malloc is cleared in HWR_FreeTextureCache // (...) unfortunately z_malloc fragment alot the memory :(so malloc is better - newmip = calloc(1, sizeof (*newmip)); - if (newmip == NULL) + newMipmap = calloc(1, sizeof (*newMipmap)); + if (newMipmap == NULL) I_Error("%s: Out of memory", "HWR_GetMappedPatch"); - grmip->nextcolormap = newmip; - newmip->colormap = colormap; + glMipmap->nextcolormap = newMipmap; + newMipmap->colormap = colormap; - HWR_CreateBlendedTexture(gpatch, blendgpatch, newmip, skinnum, color); + HWR_CreateBlendedTexture(gpatch, blendgpatch, newMipmap, skinnum, color); - HWD.pfnSetTexture(newmip); - Z_ChangeTag(newmip->data, PU_HWRCACHE_UNLOCKED); + GL_SetTexture(newMipmap); + Z_ChangeTag(newMipmap->data, PU_HWRCACHE_UNLOCKED); } - // -----------------+ // HWR_DrawMD2 : Draw MD2 // : // Returns : // -----------------+ -void HWR_DrawMD2(gr_vissprite_t *spr) +void HWR_DrawMD2(gl_vissprite_t *spr) { md2_t *md2; @@ -1105,7 +1106,7 @@ void HWR_DrawMD2(gr_vissprite_t *spr) FTransform p; FSurfaceInfo Surf; - if (!cv_grmdls.value) + if (!cv_glmdls.value) return; if (spr->precip) @@ -1164,7 +1165,7 @@ void HWR_DrawMD2(gr_vissprite_t *spr) angle_t ang; interpmobjstate_t interp; - if (R_UsingFrameInterpolation() && !paused && (!cv_grmaxinterpdist.value || R_QuickCamDist(spr->mobj->x, spr->mobj->y) < cv_grmaxinterpdist.value)) + if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || R_QuickCamDist(spr->mobj->x, spr->mobj->y) < cv_maxinterpdist.value)) { R_InterpolateMobjState(spr->mobj, rendertimefrac, &interp); } @@ -1234,7 +1235,7 @@ void HWR_DrawMD2(gr_vissprite_t *spr) if (md2->model) { md2_printModelInfo(md2->model); - HWD.pfnCreateModelVBOs(md2->model); + GL_CreateModelVBOs(md2->model); } else { @@ -1244,22 +1245,22 @@ void HWR_DrawMD2(gr_vissprite_t *spr) } } //Hurdler: arf, I don't like that implementation at all... too much crappy - gpatch = md2->grpatch; + gpatch = md2->glpatch; if (!gpatch || ((!gpatch->mipmap->format || !gpatch->mipmap->downloaded) && !gpatch->notfound)) md2_loadTexture(md2); - gpatch = md2->grpatch; // Load it again, because it isn't being loaded into gpatch after md2_loadtexture... + gpatch = md2->glpatch; // Load it again, because it isn't being loaded into gpatch after md2_loadtexture... if ((gpatch && gpatch->mipmap->format) // don't load the blend texture if the base texture isn't available - && (!md2->blendgrpatch - || ((!((GLPatch_t *)md2->blendgrpatch)->mipmap->format || !((GLPatch_t *)md2->blendgrpatch)->mipmap->downloaded) - && !((GLPatch_t *)md2->blendgrpatch)->notfound))) + && (!md2->blendglpatch + || ((!((GLPatch_t *)md2->blendglpatch)->mipmap->format || !((GLPatch_t *)md2->blendglpatch)->mipmap->downloaded) + && !((GLPatch_t *)md2->blendglpatch)->notfound))) md2_loadBlendTexture(md2); if (gpatch && gpatch->mipmap->format) // else if meant that if a texture couldn't be loaded, it would just end up using something else's texture { if ((skincolors_t)spr->mobj->color != SKINCOLOR_NONE && - md2->blendgrpatch && ((GLPatch_t *)md2->blendgrpatch)->mipmap->format - && gpatch->width == ((GLPatch_t *)md2->blendgrpatch)->width && gpatch->height == ((GLPatch_t *)md2->blendgrpatch)->height) + md2->blendglpatch && ((GLPatch_t *)md2->blendglpatch)->mipmap->format + && gpatch->width == ((GLPatch_t *)md2->blendglpatch)->width && gpatch->height == ((GLPatch_t *)md2->blendglpatch)->height) { INT32 tcskinnum = TC_DEFAULT; if ((spr->mobj->flags & MF_BOSS) && (spr->mobj->flags2 & MF2_FRET) && (leveltime & 1)) // Bosses "flash" @@ -1284,12 +1285,12 @@ void HWR_DrawMD2(gr_vissprite_t *spr) } else tcskinnum = TC_DEFAULT; } - HWR_GetBlendedTexture(gpatch, (GLPatch_t *)md2->blendgrpatch, tcskinnum, spr->colormap, (skincolors_t)spr->mobj->color); + HWR_GetBlendedTexture(gpatch, (GLPatch_t *)md2->blendglpatch, tcskinnum, spr->colormap, (skincolors_t)spr->mobj->color); } else { // This is safe, since we know the texture has been downloaded - HWD.pfnSetTexture(gpatch->mipmap); + GL_SetTexture(gpatch->mipmap); } } else @@ -1313,7 +1314,7 @@ void HWR_DrawMD2(gr_vissprite_t *spr) // Interpolate the model interpolation. (lol) tics -= FixedToFloat(rendertimefrac); - if (cv_grmdls.value == 1 && tics <= durs) + if (cv_glmdls.value == 1 && tics <= durs) { // frames are handled differently for states with FF_ANIMATE, so get the next frame differently for the interpolation if (spr->mobj->frame & FF_ANIMATE) @@ -1370,19 +1371,16 @@ void HWR_DrawMD2(gr_vissprite_t *spr) p.spritexscale = FIXED_TO_FLOAT(spr->mobj->spritexscale); p.spriteyscale = FIXED_TO_FLOAT(spr->mobj->spriteyscale); - - angle_t sliptideroll = 0; - if (spr->mobj->player) - sliptideroll = ((cv_sloperoll.value && cv_sliptideroll.value) ? spr->mobj->player->sliproll : 0); + angle_t sliptideroll = ((cv_sloperoll.value && cv_sliptideroll.value && spr->mobj->player) ? spr->mobj->player->sliproll : 0); - if ((spr->mobj->rollangle)||(sliptideroll && cv_sliptideroll.value)) + if (spr->mobj->rollangle || sliptideroll) { angle_t rollang = 0; rollfactor = ((spr->mobj->rollmodel == true) ? 1 : 0); - rollang = (spr->mobj->player && sliptideroll && cv_sliptideroll.value) - ? (spr->mobj->rollangle * rollfactor) + (sliptideroll * spr->mobj->player->sliptidemem) + rollang = sliptideroll + ? (spr->mobj->rollangle * rollfactor) + (sliptideroll * spr->mobj->player->kartstuff[k_aizdriftstrat]) : (spr->mobj->rollangle * rollfactor); fixed_t anglef = AngleFixed(rollang); @@ -1465,7 +1463,7 @@ void HWR_DrawMD2(gr_vissprite_t *spr) p.mirror = atransform.mirror; // from Kart #endif - HWD.pfnSetShader(SHADER_MODEL); // model shader + GL_SetShader(SHADER_MODEL); // model shader { SINT8 flipfactor = flip ? -1 : 1; @@ -1478,11 +1476,11 @@ void HWR_DrawMD2(gr_vissprite_t *spr) float oy = ys * flipfactor*FIXED_TO_FLOAT(interp.spriteyoffset); // offset perpendicular to the camera angle - p.x -= ox * gr_viewsin; - p.y += ox * gr_viewcos; + p.x -= ox * gl_viewsin; + p.y += ox * gl_viewcos; p.z += oy; - HWD.pfnDrawModel(md2->model, frame, durs, tics, nextFrame, &p, md2->scale * xs, md2->scale * ys, flip, hflip, &Surf); + GL_DrawModel(md2->model, frame, durs, tics, nextFrame, &p, md2->scale * xs, md2->scale * ys, flip, hflip, &Surf); } } } diff --git a/src/hardware/hw_md2.h b/src/hardware/hw_md2.h index 7b58a6f97..e9eafd387 100644 --- a/src/hardware/hw_md2.h +++ b/src/hardware/hw_md2.h @@ -28,8 +28,8 @@ typedef struct float scale; float offset; model_t *model; - void *grpatch; - void *blendgrpatch; + void *glpatch; + void *blendglpatch; boolean notfound; INT32 skin; boolean error; @@ -40,7 +40,7 @@ extern md2_t md2_playermodels[MAXSKINS]; extern md2_t md2_localplayermodels[MAXLOCALSKINS]; void HWR_InitMD2(void); -void HWR_DrawMD2(gr_vissprite_t *spr); +void HWR_DrawMD2(gl_vissprite_t *spr); void HWR_AddPlayerMD2(INT32 skin, boolean local); void HWR_AddSpriteMD2(size_t spritenum); diff --git a/src/hardware/hw_portal.c b/src/hardware/hw_portal.c new file mode 100644 index 000000000..f26e71331 --- /dev/null +++ b/src/hardware/hw_portal.c @@ -0,0 +1,231 @@ +// SONIC ROBO BLAST 2 KART +//----------------------------------------------------------------------------- +// Copyright (C) 2024 by Kart Krew. +// Copyright (C) 2020 by Sonic Team Junior. +// Copyright (C) 2000 by DooM Legacy Team. +// Copyright (C) 1996 by id Software, Inc. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file hw_portal.c +/// \brief OpenGL renderer portals. + +// ========================================================================== +// Visual portals (attr. Hannu Hanhi) +// ========================================================================== + +#ifdef HWRENDER + +#include "../r_portal.h" + +#include "../z_zone.h" + +#include "hw_clip.h" +#include "hw_gl.h" +#include "hw_defs.h" +#include "hw_main.h" +#include "hw_portal.h" + +SINT8 gl_portal_state = GLPORTAL_OFF; + +gl_portallist_t *currentportallist; + +// clip the area outside the portal destination window +void HWR_PortalClipping(gl_portal_t *portal) +{ + gld_clipper_SafeAddClipRange(portal->angle1, portal->angle2); +} + +static gl_portal_t* HWR_Portal_Add (seg_t *seg) +{ + gl_portal_t *portal = Z_Malloc(sizeof(gl_portal_t), PU_STATIC, NULL); + + // Linked list. + if (!currentportallist->base) + { + currentportallist->base = portal; + currentportallist->cap = portal; + } + else + { + currentportallist->cap->next = portal; + currentportallist->cap = portal; + } + portal->next = NULL; + + portal->seg = seg; + + return portal; +} + +void HWR_FreePortalList(gl_portallist_t freelist) +{ + portalcullsector = NULL; + + // free memory from portal list allocated by calls to Add2Lines + gl_portal_t *gl_portal_temp = freelist.base; + while (gl_portal_temp) + { + gl_portal_t *nextportal = gl_portal_temp->next; + Z_Free(gl_portal_temp); + gl_portal_temp = nextportal; + } +} + +void HWR_Portal_Add2Lines(const INT32 line1, const INT32 line2, seg_t *seg) +{ + gl_portal_t *portal = HWR_Portal_Add(seg); + + // Offset the portal view by the linedef centers + line_t* start = &lines[line1]; + line_t* dest = &lines[line2]; + + angle_t dangle = R_PointToAngle2(0, 0, dest->dx, dest->dy) - R_PointToAngle2(start->dx, start->dy, 0, 0); + + fixed_t disttopoint; + angle_t angtopoint; + + vertex_t dest_c, start_c; + + // looking glass center + start_c.x = start->v1->x/2 + start->v2->x/2; + start_c.y = start->v1->y/2 + start->v2->y/2; + + // other side center + dest_c.x = dest->v1->x/2 + dest->v2->x/2; + dest_c.y = dest->v1->y/2 + dest->v2->y/2; + + disttopoint = R_PointToDist2(start_c.x, start_c.y, viewx, viewy); + angtopoint = R_PointToAngle2(start_c.x, start_c.y, viewx, viewy); + angtopoint += dangle; + + portal->viewx = dest_c.x + FixedMul(FINECOSINE(angtopoint>>ANGLETOFINESHIFT), disttopoint); + portal->viewy = dest_c.y + FixedMul(FINESINE(angtopoint>>ANGLETOFINESHIFT), disttopoint); + portal->viewz = viewz + dest->frontsector->floorheight - start->frontsector->floorheight; + portal->viewangle = viewangle + dangle; + + portal->angle1 = R_PointToAngle64(seg->v1->x, seg->v1->y) + dangle; + portal->angle2 = R_PointToAngle64(seg->v2->x, seg->v2->y) + dangle; + + portal->clipline = line2; +} + +void HWR_PortalFrame(gl_portal_t* portal) +{ + viewx = portal->viewx; + viewy = portal->viewy; + viewz = portal->viewz; + + viewangle = portal->viewangle; + //viewsin = FINESINE(viewangle>>ANGLETOFINESHIFT); + //viewcos = FINECOSINE(viewangle>>ANGLETOFINESHIFT); + + if (portal->clipline != -1) + { + portalclipline = &lines[portal->clipline]; + portalcullsector = portalclipline->frontsector; + viewsector = portalclipline->frontsector; + } + else + { + portalclipline = NULL; + portalcullsector = NULL; + viewsector = R_PointInSubsectorFast(viewx, viewy)->sector; + } +} + +// Renders a portal segment. +static void HWR_RenderPortalSeg(gl_portal_t* portal, SINT8 state) +{ + gl_drawing_stencil = true; // do not draw outside of the stencil buffer, idiot. + + // set our portal state and prepare to render the seg + HWR_SetPortalState(state); + + gl_curline = portal->seg; + gl_frontsector = portal->seg->frontsector; + gl_backsector = portal->seg->backsector; + + HWR_ProcessSeg(); + gl_drawing_stencil = false; + + // need to work around the r_opengl PF_Invisible bug with this call + // similarly as in the linkdraw hack in HWR_DrawSprites + GL_SetBlend(PF_Translucent|PF_Occlude|PF_Masked); +} + +// Renders a single portal from the current viewpoint. +void HWR_RenderPortal(gl_portal_t* portal, gl_portal_t* rootportal, const float fpov, player_t *player, int stencil_level) +{ + // draw portal seg to stencil buffer with increment + HWR_SetTransform(fpov, player); + HWR_ClearClipper(); + + HWR_SetStencilState(HWR_STENCIL_BEGIN, stencil_level); + HWR_RenderPortalSeg(portal, GLPORTAL_STENCIL); + + // go to portal frame lmao + HWR_PortalFrame(portal); + // call HWR_RenderViewpoint + HWR_RenderViewpoint(portal, fpov, player, stencil_level + 1, true); + // return to current frame + if (rootportal) + HWR_PortalFrame(rootportal); + else // current frame is not a portal frame but the main view! + { + R_SetupFrame(viewssnum, false); + portalclipline = NULL; + } + + // remove portal seg from stencil buffer + HWR_SetTransform(fpov, player); + HWR_ClearClipper(); + + HWR_SetStencilState(HWR_STENCIL_REVERSE, stencil_level); + HWR_RenderPortalSeg(portal, GLPORTAL_STENCIL); + + // draw portal seg to depth buffer + HWR_ClearClipper(); + HWR_SetStencilState(HWR_STENCIL_DEPTH, stencil_level); + HWR_RenderPortalSeg(portal, GLPORTAL_DEPTH); +} + +// returns true if the point is on the correct (viewable) side of the +// portal destination line +boolean HWR_PortalCheckPointSide(fixed_t x, fixed_t y) +{ + // we are checking if the point is on the viewable side of the portal exit. + // being exactly on the portal exit line is not enough to pass the test. + // P_PointOnLineSide could behave differently from this expectation on this case, + // so first check if the point is precisely on the line, and then if not, check the side. + + vertex_t closest_point; + P_ClosestPointOnLine(x, y, portalclipline, &closest_point); + if (closest_point.x != x || closest_point.y != y) + { + if (P_PointOnLineSide(x, y, portalclipline) != 1) + return true; + } + return false; +} + +boolean HWR_PortalCheckBBox(const fixed_t *bspcoord) +{ + if (!portalclipline) + return true; + + if (HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXTOP]) || + HWR_PortalCheckPointSide(bspcoord[BOXLEFT], bspcoord[BOXBOTTOM]) || + HWR_PortalCheckPointSide(bspcoord[BOXRIGHT], bspcoord[BOXTOP]) || + HWR_PortalCheckPointSide(bspcoord[BOXRIGHT], bspcoord[BOXBOTTOM])) + { + return true; + } + + // we did not find any reason to pass the check, so return failure + return false; +} + +#endif diff --git a/src/hardware/hw_portal.h b/src/hardware/hw_portal.h new file mode 100644 index 000000000..f42d2f61c --- /dev/null +++ b/src/hardware/hw_portal.h @@ -0,0 +1,81 @@ +// SONIC ROBO BLAST 2 +//----------------------------------------------------------------------------- +// Copyright (C) 1993-1996 by id Software, Inc. +// Copyright (C) 1998-2000 by DooM Legacy Team. +// Copyright (C) 1999-2018 by Sonic Team Junior. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file hw_portal.h +/// \brief OpenGL renderer portal struct, functions, linked list extern. + +#ifndef __HW_PORTAL__ +#define __HW_PORTAL__ + +#ifdef HWRENDER + +#include "../doomstat.h" +#include "../r_data.h" +#include "../r_bsp.h" + +/** Portal structure. + */ +enum +{ + GLPORTAL_OFF, + GLPORTAL_SEARCH, + GLPORTAL_STENCIL, + GLPORTAL_DEPTH, + GLPORTAL_INSIDE, +}; + +typedef struct gl_portal_s +{ + struct gl_portal_s *next; + + // Viewport. + fixed_t viewx; + fixed_t viewy; + fixed_t viewz; + angle_t viewangle; + + seg_t *seg; // seg that is used for drawing to the stencil buffer + INT32 clipline; // Optional clipline for line-based portals + + // angles for the left and right edges of the portal + // relative to the viewpoint + angle_t angle1; + angle_t angle2; +} gl_portal_t; + +typedef struct gl_portallist_s +{ + gl_portal_t *base; + gl_portal_t *cap; +} gl_portallist_t; + +extern SINT8 gl_portal_state; + +// new thing +extern gl_portallist_t *currentportallist; + +static inline void HWR_SetPortalState (SINT8 state) +{ + gl_portal_state = state; +} + +// Adds an entry to the clipper for portal rendering +void HWR_PortalClipping(gl_portal_t *portal); + +void HWR_Portal_Add2Lines(const INT32 line1, const INT32 line2, seg_t *seg); +void HWR_PortalFrame(gl_portal_t* portal); +void HWR_RenderPortal(gl_portal_t* portal, gl_portal_t* rootportal, const float fpov, player_t *player, int stencil_level); +void HWR_FreePortalList(gl_portallist_t portallist); + +boolean HWR_PortalCheckPointSide(fixed_t x, fixed_t y); +boolean HWR_PortalCheckBBox(const fixed_t *bspcoord); + +#endif +#endif diff --git a/src/hardware/hw_shaders.c b/src/hardware/hw_shaders.c index d7924a675..31ee2c066 100644 --- a/src/hardware/hw_shaders.c +++ b/src/hardware/hw_shaders.c @@ -13,7 +13,7 @@ #include "hw_main.h" #include "hw_glob.h" -#include "hw_drv.h" +#include "hw_gl.h" #include "hw_shaders.h" #include "../z_zone.h" @@ -25,13 +25,10 @@ static struct { const char *vertex; const char *fragment; } const gl_shadersources[] = { - + // Floor shader {GLSL_DEFAULT_VERTEX_SHADER, GLSL_FLOOR_FRAGMENT_SHADER}, - // Shadow shader - {GLSL_DEFAULT_VERTEX_SHADER, GLSL_SHADOW_FRAGMENT_SHADER}, - // Wall shader {GLSL_DEFAULT_VERTEX_SHADER, GLSL_WALL_FRAGMENT_SHADER}, @@ -52,7 +49,7 @@ static struct { // Palette postprocess shader {GLSL_DEFAULT_VERTEX_SHADER, GLSL_PALETTE_POSTPROCESS_FRAGMENT_SHADER}, - + // UI colormap fade shader {GLSL_DEFAULT_VERTEX_SHADER, GLSL_UI_COLORMAP_FADE_FRAGMENT_SHADER}, @@ -90,7 +87,7 @@ boolean HWR_InitShaders(void) { int i; - if (!HWD.pfnInitShaders()) + if (!GL_InitShaders()) return false; for (i = 0; i < NUMSHADERTARGETS; i++) @@ -279,11 +276,11 @@ static char *HWR_PreprocessShader(char *original) // Calculate length of modified shader. new_len = original_len; - - if (cv_grpaletterendering.value) + + if (cv_glpaletterendering.value) ADD_TO_LEN(PALETTE_RENDERING_DEFINE) - if (cv_lightdither.value) + if (cv_gllightdither.value) ADD_TO_LEN(LIGHT_DITHERING_DEFINE) #undef ADD_TO_LEN @@ -324,10 +321,10 @@ static char *HWR_PreprocessShader(char *original) } // Write the defines. - if (cv_grpaletterendering.value) + if (cv_glpaletterendering.value) WRITE_DEFINE(PALETTE_RENDERING_DEFINE) - if (cv_lightdither.value) + if (cv_gllightdither.value) WRITE_DEFINE(LIGHT_DITHERING_DEFINE) #undef WRITE_DEFINE @@ -369,16 +366,16 @@ static void HWR_CompileShader(int index) { char *preprocessed = HWR_PreprocessShader(vertex_source); if (!preprocessed) return; - HWD.pfnLoadShader(index, preprocessed, HWD_SHADERSTAGE_VERTEX); + GL_LoadShader(index, preprocessed, HWD_SHADERSTAGE_VERTEX); } if (fragment_source) { char *preprocessed = HWR_PreprocessShader(fragment_source); if (!preprocessed) return; - HWD.pfnLoadShader(index, preprocessed, HWD_SHADERSTAGE_FRAGMENT); + GL_LoadShader(index, preprocessed, HWD_SHADERSTAGE_FRAGMENT); } - gl_shaders[index].compiled = HWD.pfnCompileShader(index); + gl_shaders[index].compiled = GL_CompileShader(index); } // compile or recompile shaders @@ -410,7 +407,7 @@ int HWR_GetShaderFromTarget(int shader_target) // - custom shaders are enabled // - custom shaders are allowed by the server if (custom_shader != -1 && gl_shaders[custom_shader].compiled && - cv_grshaders.value == 1) + cv_glshaders.value == 1) return custom_shader; else return gl_shadertargets[shader_target].base_shader; @@ -432,7 +429,6 @@ static inline UINT16 HWR_FindShaderDefs(UINT16 wadnum) customshaderxlat_t shaderxlat[] = { {"Flat", SHADER_FLOOR}, - {"Shadow", SHADER_SHADOW}, {"WallTexture", SHADER_WALL}, {"Sprite", SHADER_SPRITE}, {"Model", SHADER_MODEL}, @@ -565,7 +561,7 @@ void HWR_LoadCustomShadersFromFile(UINT16 wadnum, boolean PK3) int i; boolean modified_shaders[NUMSHADERTARGETS] = {0}; - if (!gr_shadersavailable) + if (!gl_shadersavailable) return; lump = HWR_FindShaderDefs(wadnum); diff --git a/src/hardware/hw_shaders.h b/src/hardware/hw_shaders.h index 714b004b1..9826ba06f 100644 --- a/src/hardware/hw_shaders.h +++ b/src/hardware/hw_shaders.h @@ -99,6 +99,7 @@ GLSL_DOOM_COLORMAP_NODITHER \ "#endif\n" \ "}\n" + // lighting cap adjustment: // first num (155.0), increase to make it start to go dark sooner // second num (0.26), increase to make it go dark faster @@ -171,7 +172,7 @@ "gl_FragColor = final_color;\n" \ "}\n" \ "#endif\0" - + #define GLSL_SOFTWARE_FRAGMENT_SHADER_NOPAL \ "uniform sampler2D tex;\n" \ "uniform vec4 poly_color;\n" \ @@ -210,10 +211,6 @@ #define GLSL_WALL_FRAGMENT_SHADER \ GLSL_WALL_FUDGES \ GLSL_SOFTWARE_FRAGMENT_SHADER - -#define GLSL_SHADOW_FRAGMENT_SHADER \ - GLSL_FLOOR_FUDGES \ - GLSL_SOFTWARE_FRAGMENT_SHADER_NOPAL // // Water surface shader diff --git a/src/hardware/r_opengl/ogl_win.c b/src/hardware/r_opengl/ogl_win.c index 8ce44d788..e819e0f68 100644 --- a/src/hardware/r_opengl/ogl_win.c +++ b/src/hardware/r_opengl/ogl_win.c @@ -358,8 +358,8 @@ static INT32 WINAPI SetRes(viddef_t *lvid, vmode_t *pcurrentmode) else textureformatGL = GL_RGB5_A1; - SetModelView(lvid->width, lvid->height); - SetStates(); + GL_SetModelView(lvid->width, lvid->height); + GL_SetStates(); // we need to clear the depth buffer. Very important!!! pglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); @@ -526,7 +526,7 @@ EXPORT void HWRAPI(Shutdown) (void) // -----------------+ // FinishUpdate : Swap front and back buffers // -----------------+ -EXPORT void HWRAPI(FinishUpdate) (INT32 waitvbl) +void GL_FinishUpdate (INT32 waitvbl) { #ifdef USE_WGL_SWAP static INT32 oldwaitvbl = 0; @@ -547,23 +547,4 @@ EXPORT void HWRAPI(FinishUpdate) (INT32 waitvbl) SwapBuffers(hDC); } - - -// -----------------+ -// SetPalette : Set the color lookup table for paletted textures -// : in OpenGL, we store values for conversion of paletted graphics when -// : they are downloaded to the 3D card. -// -----------------+ -EXPORT void HWRAPI(SetPalette) (RGBA_t *pal) -{ - INT32 i; - - for (i = 0; i < 256; i++) - { - myPaletteData[i].s.red = pal[i].s.red; - myPaletteData[i].s.green = pal[i].s.green; - myPaletteData[i].s.blue = pal[i].s.blue; - myPaletteData[i].s.alpha = pal[i].s.alpha; - } -} #endif diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 4be4d4c27..72bb34e61 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -23,19 +23,23 @@ #include #include -#include "../../r_local.h" // For rendertimefrac, used for the leveltime shader uniform -#include "r_opengl.h" -#include "r_vbo.h" -#include "../hw_shaders.h" -#include "../hw_main.h" -#include "../hw_clip.h" // Eeeeh not sure is this right way, but it works < sry :c < sry again it had to go :c -extern fixed_t fovtan; // also extremely bad, I'm just too lazy!!! - #if defined (HWRENDER) && !defined (NOROPENGL) +#include "r_opengl.h" +#include "r_vbo.h" + +#include "../hw_batching.h" +#include "../hw_clip.h" +#include "../hw_main.h" +#include "../hw_shaders.h" + +#include "../../f_finale.h" +#include "../../r_local.h" // For rendertimefrac, used for the leveltime shader uniform +#include "../../i_video.h" + struct GLRGBAFloat { GLfloat red; @@ -110,6 +114,8 @@ static FTransform md2_transform; const GLubyte *gl_version = NULL; const GLubyte *gl_renderer = NULL; const GLubyte *gl_extensions = NULL; +const GLubyte *gl_vendor = NULL; +GLuint gl_num_extensions; // Loaded OpenGL version int majorGL = 0, minorGL = 0; @@ -121,9 +127,9 @@ static GLint viewport[4]; #ifdef USE_FBO_OGL GLuint FramebufferObject, FramebufferTexture, RenderbufferObject; -GLboolean FrameBufferEnabled = GL_FALSE, RenderToFramebuffer = GL_FALSE; boolean supportFBO = false; +static boolean fboinit = false; #endif // Sryder: NextTexAvail is broken for these because palette changes or changes to the texture filter or antialiasing @@ -700,13 +706,21 @@ static gl_shaderstate_t gl_shaderstate; static float shader_leveltime = 0; // Lactozilla: Shader functions -static boolean Shader_CompileProgram(gl_shader_t *shader, GLint i); -static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade); +static boolean GL_Shader_CompileProgram(gl_shader_t *shader, GLint i); +static void GL_Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade); static GLRGBAFloat shader_defaultcolor = {1.0f, 1.0f, 1.0f, 1.0f}; #ifdef USE_FBO_OGL -static boolean GLFramebuffer_IsFuncAvailible(void); +static boolean GLFramebuffer_CheckExt(void) +{ + //this stuff needs atleast OGL 3.0 + if (majorGL < 3) + return false; + + // check if all needed gl extensions are available + return (GL_isExtAvailable("GL_ARB_framebuffer_no_attachments", gl_extensions) && GL_isExtAvailable("GL_ARB_framebuffer_object", gl_extensions) && GL_isExtAvailable("GL_ARB_framebuffer_sRGB", gl_extensions)); +} #endif void SetupGLFunc4(void) @@ -753,7 +767,7 @@ void SetupGLFunc4(void) pglGetUniformLocation = GetGLFunc("glGetUniformLocation"); #ifdef USE_FBO_OGL - if (GLFramebuffer_IsFuncAvailible()) + if (GLFramebuffer_CheckExt()) { pglGenFramebuffers = GetGLFunc("glGenFramebuffers"); pglBindFramebuffer = GetGLFunc("glBindFramebuffer"); @@ -766,25 +780,18 @@ void SetupGLFunc4(void) pglRenderbufferStorage = GetGLFunc("glRenderbufferStorage"); pglFramebufferRenderbuffer = GetGLFunc("glFramebufferRenderbuffer"); + // check if ALL functions are availible + if (pglGenFramebuffers && pglBindFramebuffer && + pglDeleteFramebuffers && pglFramebufferTexture2D && + pglCheckFramebufferStatus && pglGenRenderbuffers && + pglBindRenderbuffer && pglDeleteRenderbuffers && + pglRenderbufferStorage && pglFramebufferRenderbuffer) supportFBO = true; } #endif } -#ifdef USE_FBO_OGL -static boolean GLFramebuffer_IsFuncAvailible(void) -{ - //this stuff needs atleast OGL 3.0 - if (majorGL < 3) - return false; - - return (isExtAvailable("GL_ARB_framebuffer_no_attachments",gl_extensions) && isExtAvailable("GL_ARB_framebuffer_object",gl_extensions) && isExtAvailable("GL_ARB_framebuffer_sRGB",gl_extensions)); - - return false; -} -#endif - -EXPORT boolean HWRAPI(InitShaders) (void) +boolean GL_InitShaders(void) { if (!pglUseProgram) return false; @@ -792,7 +799,7 @@ EXPORT boolean HWRAPI(InitShaders) (void) gl_fallback_shader.vertex_shader = Z_StrDup(GLSL_FALLBACK_VERTEX_SHADER); gl_fallback_shader.fragment_shader = Z_StrDup(GLSL_FALLBACK_FRAGMENT_SHADER); - if (!Shader_CompileProgram(&gl_fallback_shader, -1)) + if (!GL_Shader_CompileProgram(&gl_fallback_shader, -1)) { GL_MSG_Error("Failed to compile the fallback shader program!\n"); return false; @@ -801,7 +808,7 @@ EXPORT boolean HWRAPI(InitShaders) (void) return true; } -EXPORT void HWRAPI(LoadShader) (int slot, char *code, hwdshaderstage_t stage) +void GL_LoadShader(int slot, char *code, hwdshaderstage_t stage) { gl_shader_t *shader; @@ -826,12 +833,12 @@ EXPORT void HWRAPI(LoadShader) (int slot, char *code, hwdshaderstage_t stage) #undef LOADSHADER } -EXPORT boolean HWRAPI(CompileShader) (int slot) +boolean GL_CompileShader(int slot) { if (slot < 0 || slot >= HWR_MAXSHADERS) I_Error("CompileShader: Invalid slot %d", slot); - if (Shader_CompileProgram(&gl_shaders[slot], slot)) + if (GL_Shader_CompileProgram(&gl_shaders[slot], slot)) { return true; } @@ -847,7 +854,7 @@ EXPORT boolean HWRAPI(CompileShader) (int slot) // Those are given to the uniforms. // -EXPORT void HWRAPI(SetShaderInfo) (hwdshaderinfo_t info, INT32 value) +void GL_SetShaderInfo(hwdshaderinfo_t info, INT32 value) { switch (info) { @@ -859,11 +866,11 @@ EXPORT void HWRAPI(SetShaderInfo) (hwdshaderinfo_t info, INT32 value) } } -EXPORT void HWRAPI(SetShader) (int slot) +void GL_SetShader(int slot) { if (slot == SHADER_NONE) { - UnSetShader(); + GL_UnSetShader(); return; } if (gl_allowshaders) @@ -890,7 +897,7 @@ EXPORT void HWRAPI(SetShader) (int slot) gl_shadersenabled = false; } -EXPORT void HWRAPI(UnSetShader) (void) +void GL_UnSetShader(void) { if (gl_shadersenabled) // don't repeatedly call glUseProgram if not needed { @@ -909,10 +916,10 @@ EXPORT void HWRAPI(UnSetShader) (void) // -----------------+ // SetNoTexture : Disable texture // -----------------+ -static void SetNoTexture(void) +static void GL_SetNoTexture(void) { // Disable texture. - if (tex_downloaded != NOTEXTURE_NUM) + if (tex_downloaded != NOTEXTURE_NUM && !currently_batching) { if (NOTEXTURE_NUM == 0) pglGenTextures(1, &NOTEXTURE_NUM); @@ -921,7 +928,10 @@ static void SetNoTexture(void) } } -static void GLPerspective(GLfloat fovy, GLfloat aspect) +// -----------------+ +// Perspective : +// -----------------+ +static void GL_Perspective(GLfloat fovy, GLfloat aspect) { GLfloat m[4][4] = { @@ -930,32 +940,27 @@ static void GLPerspective(GLfloat fovy, GLfloat aspect) { 0.0f, 0.0f, 1.0f,-1.0f}, { 0.0f, 0.0f, 0.0f, 0.0f}, }; - const GLfloat zNear = NEAR_CLIPPING_PLANE; - const GLfloat zFar = FAR_CLIPPING_PLANE; - const GLfloat radians = (GLfloat)(fovy / 2.0f * M_PIl / 180.0f); - const GLfloat sine = (GLfloat)sin(radians); - const GLfloat deltaZ = zFar - zNear; - GLfloat cotangent; - if ((fabsf((float)deltaZ) < 1.0E-36f) || fpclassify(sine) == FP_ZERO || fpclassify(aspect) == FP_ZERO) + const GLfloat focallength = (GLfloat)(1.0f / (GLfloat)tan(fovy * (GLfloat)M_PIl / 360.0f)); + const GLfloat deltaZ = FAR_CLIPPING_PLANE - NEAR_CLIPPING_PLANE; + + if ((fabsf((float)deltaZ) < 1.0E-36f) || fpclassify(aspect) == FP_ZERO) { return; } - cotangent = cosf(radians) / sine; - m[0][0] = cotangent / aspect; - m[1][1] = cotangent; - m[2][2] = -(zFar + zNear) / deltaZ; - m[3][2] = -2.0f * zNear * zFar / deltaZ; + m[0][0] = focallength / aspect; + m[1][1] = focallength; + m[2][2] = -(FAR_CLIPPING_PLANE + NEAR_CLIPPING_PLANE) / deltaZ; + m[3][2] = -2.0f * NEAR_CLIPPING_PLANE * FAR_CLIPPING_PLANE / deltaZ; pglMultMatrixf(&m[0][0]); } - // -----------------+ // SetModelView : // -----------------+ -void SetModelView(GLint w, GLint h) +void GL_SetModelView(GLint w, GLint h) { //GL_DBG_Printf("SetModelView(): %dx%d\n", (int)w, (int)h); @@ -967,7 +972,7 @@ void SetModelView(GLint w, GLint h) pglMatrixMode(GL_MODELVIEW); pglLoadIdentity(); - GLPerspective(fov, ASPECT_RATIO); + GL_Perspective(fov, ASPECT_RATIO); // added for new coronas' code (without depth buffer) pglGetIntegerv(GL_VIEWPORT, viewport); @@ -977,7 +982,7 @@ void SetModelView(GLint w, GLint h) // -----------------+ // SetStates : Set permanent states // -----------------+ -void SetStates(void) +void GL_SetStates(void) { pglEnable(GL_TEXTURE_2D); // two-dimensional texturing pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); @@ -997,10 +1002,10 @@ void SetStates(void) // this set CurrentPolyFlags to the actual configuration CurrentPolyFlags = 0xffffffff; - SetBlend(0); + GL_SetBlend(0); tex_downloaded = 0; - SetNoTexture(); + GL_SetNoTexture(); pglPolygonOffset(-1.0f, -1.0f); @@ -1009,10 +1014,11 @@ void SetStates(void) pglScalef(1.0f, 1.0f, -1.0f); pglGetFloatv(GL_MODELVIEW_MATRIX, modelMatrix); // added for new coronas' code (without depth buffer) } + // -----------------+ // DeleteTexture : Deletes a texture from the GPU and frees its data // -----------------+ -EXPORT void HWRAPI(DeleteTexture) (GLMipmap_t *pTexInfo) +void GL_DeleteTexture(GLMipmap_t *pTexInfo) { FTextureInfo *head = TexCacheHead; @@ -1044,9 +1050,9 @@ EXPORT void HWRAPI(DeleteTexture) (GLMipmap_t *pTexInfo) } #ifdef USE_FBO_OGL -static void GLFramebuffer_GenerateAttachments(void) +static void GL_Framebuffer_GenerateAttachments(void) { - if (!supportFBO) + if (!supportFBO || !UseScreenFBO()) return; // Bind the framebuffer @@ -1076,18 +1082,23 @@ static void GLFramebuffer_GenerateAttachments(void) pglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, RenderbufferObject); // Clear the renderbuffer - ClearBuffer(true, true, true, NULL); + GL_ClearBuffer(true, true, true, NULL); pglBindRenderbuffer(GL_RENDERBUFFER, 0); } // Unbind the framebuffer pglBindFramebuffer(GL_FRAMEBUFFER, 0); + + fboinit = true; } -void GLFramebuffer_DeleteAttachments(void) +void GL_Framebuffer_DeleteAttachments(void) { - if (!supportFBO) + if (!supportFBO || fboinit == false) + return; + + if (FramebufferObject == 0 && RenderbufferObject == 0 && FramebufferTexture == 0) return; // Unbind the framebuffer @@ -1102,11 +1113,12 @@ void GLFramebuffer_DeleteAttachments(void) FramebufferTexture = 0; RenderbufferObject = 0; + fboinit = false; } -static void GLFramebuffer_Generate(void) +static void GL_Framebuffer_Generate(void) { - if (!supportFBO) + if (!supportFBO || !UseScreenFBO()) return; // Generate the framebuffer @@ -1114,53 +1126,59 @@ static void GLFramebuffer_Generate(void) pglGenFramebuffers(1, &FramebufferObject); if (pglCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) - GLFramebuffer_GenerateAttachments(); + GL_Framebuffer_GenerateAttachments(); } -static void GLFramebuffer_Delete(void) +static void GL_Framebuffer_Delete(void) { - if (!supportFBO) + if (!supportFBO || fboinit == false) return; if (FramebufferObject) pglDeleteFramebuffers(1, &FramebufferObject); - GLFramebuffer_DeleteAttachments(); + GL_Framebuffer_DeleteAttachments(); FramebufferObject = 0; } -inline void GLFramebuffer_Unbind(void) +inline void GL_Framebuffer_Unbind(void) { - if (!supportFBO) + if (!supportFBO || fboinit == false) + return; + + if (FramebufferObject == 0 && RenderbufferObject == 0) return; pglBindFramebuffer(GL_FRAMEBUFFER, 0); pglBindRenderbuffer(GL_RENDERBUFFER, 0); } -inline void GLFramebuffer_Enable(void) +inline void GL_Framebuffer_Enable(void) { - if (!supportFBO) + if (!supportFBO || !UseScreenFBO()) return; if (FramebufferObject == 0) - GLFramebuffer_Generate(); + GL_Framebuffer_Generate(); else if (FramebufferTexture == 0 || RenderbufferObject == 0) - GLFramebuffer_GenerateAttachments(); + GL_Framebuffer_GenerateAttachments(); pglBindFramebuffer(GL_FRAMEBUFFER, FramebufferObject); pglBindRenderbuffer(GL_RENDERBUFFER, RenderbufferObject); } -void GLFramebuffer_Disable(void) +void GL_Framebuffer_Disable(void) { - if (!supportFBO) + if (!supportFBO || fboinit == false) + return; + + if (FramebufferObject == 0 && RenderbufferObject == 0) return; pglBindFramebuffer(GL_FRAMEBUFFER, 0); pglBindRenderbuffer(GL_RENDERBUFFER, 0); - GLFramebuffer_Delete(); + GL_Framebuffer_Delete(); } #endif @@ -1168,10 +1186,8 @@ void GLFramebuffer_Disable(void) // Flush : flush OpenGL textures // : Clear list of downloaded mipmaps // -----------------+ -void Flush(void) +void GL_Flush(void) { - //GL_DBG_Printf ("HWR_Flush()\n"); - while (TexCacheHead) { FTextureInfo *pTexInfo = TexCacheHead; @@ -1198,12 +1214,11 @@ void Flush(void) textureBufferSize = 0; } - // -----------------+ // isExtAvailable : Look if an OpenGL extension is available // Returns : true if extension available // -----------------+ -INT32 isExtAvailable(const char *extension, const GLubyte *start) +INT32 GL_isExtAvailable(const char *extension, const GLubyte *start) { GLubyte *where, *terminator; @@ -1226,40 +1241,29 @@ INT32 isExtAvailable(const char *extension, const GLubyte *start) return 0; } - // -----------------+ // Init : Initialise the OpenGL interface API // Returns : // -----------------+ -EXPORT boolean HWRAPI(Init) (void) +boolean GL_Init (void) { - return LoadGL(); + return SetupGLfunc(); } - // -----------------+ // SetupGLInfo : Retreive and store currently loaded OpenGL version // -----------------+ -EXPORT void HWRAPI(SetupGLInfo) (void) +void SetupGLInfo(void) { const GLubyte *versionGL = pglGetString(GL_VERSION); CONS_Printf("Loaded OpenGL version %s\n", (const char*)versionGL); sscanf((const char*)versionGL, "%d.%d", &majorGL, &minorGL); } - -// -----------------+ -// ClearMipMapCache : Flush OpenGL textures from memory -// -----------------+ -EXPORT void HWRAPI(ClearMipMapCache) (void) -{ - Flush(); -} - // Writes screen texture tex into dst_data. // Pixel format is 24-bit RGB. Row order is top to bottom. // Dimensions are screen_width * screen_height. -EXPORT void HWRAPI(ReadScreenTexture) (int tex, UINT16 *dst_data) +void GL_ReadScreenTexture(int tex, UINT16 *dst_data) { INT32 i; int dst_stride = screen_width * 3; // stride between rows of image data @@ -1272,11 +1276,11 @@ EXPORT void HWRAPI(ReadScreenTexture) (int tex, UINT16 *dst_data) // and draw generic2 back after reading the framebuffer. // this hack is for some reason **much** faster than the simple solution of using glGetTexImage. if (tex != HWD_SCREENTEXTURE_GENERIC2) - DrawScreenTexture(tex, NULL, 0); + GL_DrawScreenTexture(tex, NULL, 0); pglPixelStorei(GL_PACK_ALIGNMENT, 1); pglReadPixels(0, 0, screen_width, screen_height, GL_RGB, GL_UNSIGNED_BYTE, dst_data); if (tex != HWD_SCREENTEXTURE_GENERIC2) - DrawScreenTexture(HWD_SCREENTEXTURE_GENERIC2, NULL, 0); + GL_DrawScreenTexture(HWD_SCREENTEXTURE_GENERIC2, NULL, 0); // Flip image upside down. // In other words, convert OpenGL's "bottom->top" row order into "top->bottom". for(i = 0; i < screen_height/2; i++) @@ -1290,10 +1294,25 @@ EXPORT void HWRAPI(ReadScreenTexture) (int tex, UINT16 *dst_data) free(row); } +// -----------------+ +// SetPalette : Changes the current texture palette +// -----------------+ +void GL_SetPalette(RGBA_t *palette) +{ + INT32 i; + + for (i = 0; i < 256; i++) + { + myPaletteData[i].s = palette[i].s; + } + + GL_Flush(); +} + // -----------------+ // GClipRect : Defines the 2D hardware clipping window // -----------------+ -EXPORT void HWRAPI(GClipRect) (INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, float nearclip, float farclip) +void GL_GClipRect(INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, float nearclip, float farclip) { //GL_DBG_Printf("GClipRect(%d, %d, %d, %d)\n", minx, miny, maxx, maxy); @@ -1304,7 +1323,7 @@ EXPORT void HWRAPI(GClipRect) (INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, f //pglScissor(minx, screen_height-maxy, maxx-minx, maxy-miny); pglMatrixMode(GL_PROJECTION); pglLoadIdentity(); - GLPerspective(fov, ASPECT_RATIO); + GL_Perspective(fov, ASPECT_RATIO); pglMatrixMode(GL_MODELVIEW); // added for new coronas' code (without depth buffer) @@ -1316,10 +1335,7 @@ EXPORT void HWRAPI(GClipRect) (INT32 minx, INT32 miny, INT32 maxx, INT32 maxy, f // -----------------+ // ClearBuffer : Clear the color/alpha/depth buffer(s) // -----------------+ -EXPORT void HWRAPI(ClearBuffer) (FBOOLEAN ColorMask, - FBOOLEAN DepthMask, - FBOOLEAN StencilMask, - FRGBAFloat * ClearColor) +void GL_ClearBuffer(FBOOLEAN ColorMask, FBOOLEAN DepthMask, FBOOLEAN StencilMask, FRGBAFloat * ClearColor) { //GL_DBG_Printf("ClearBuffer(%d)\n", alpha); GLbitfield ClearMask = 0; @@ -1341,7 +1357,7 @@ EXPORT void HWRAPI(ClearBuffer) (FBOOLEAN ColorMask, ClearMask |= GL_DEPTH_BUFFER_BIT; } - SetBlend(DepthMask ? PF_Occlude | CurrentPolyFlags : CurrentPolyFlags&~PF_Occlude); + GL_SetBlend(DepthMask ? PF_Occlude | CurrentPolyFlags : CurrentPolyFlags&~PF_Occlude); if (StencilMask) ClearMask |= GL_STENCIL_BUFFER_BIT;// looks like sometimes stencil buffer needs clearing? had a problem with random black screens @@ -1354,9 +1370,7 @@ EXPORT void HWRAPI(ClearBuffer) (FBOOLEAN ColorMask, // -----------------+ // HWRAPI Draw2DLine: Render a 2D line // -----------------+ -EXPORT void HWRAPI(Draw2DLine) (F2DCoord * v1, - F2DCoord * v2, - RGBA_t Color) +void GL_Draw2DLine(F2DCoord * v1, F2DCoord * v2, RGBA_t Color) { //GL_DBG_Printf("DrawLine(): %f %f, %f %f\n", v1->x, v1->y, v2->x, v2->y); GLfloat p[12]; @@ -1398,147 +1412,155 @@ static void Clamp2D(GLenum pname) #endif } - // -----------------+ // SetBlend : Set render mode // -----------------+ // PF_Masked - we could use an ALPHA_TEST of GL_EQUAL, and alpha ref of 0, // is it faster when pixels are discarded ? -EXPORT void HWRAPI(SetBlend) (FBITFIELD PolyFlags) +void GL_SetBlend(FBITFIELD PolyFlags) { - FBITFIELD Xor; - Xor = CurrentPolyFlags^PolyFlags; - if (Xor & (PF_Blending|PF_RemoveYWrap|PF_ForceWrapX|PF_ForceWrapY|PF_Occlude|PF_NoTexture|PF_Modulated|PF_NoDepthTest|PF_Decal|PF_Invisible|PF_NoAlphaTest)) + const FBITFIELD Xor = (CurrentPolyFlags ^ PolyFlags); + + if (!(Xor & (PF_Blending|PF_RemoveYWrap|PF_ForceWrapX|PF_ForceWrapY|PF_Occlude|PF_NoTexture|PF_Modulated|PF_NoDepthTest|PF_Decal|PF_Invisible|PF_NoAlphaTest))) { - if (Xor&(PF_Blending)) // if blending mode must be changed - { - switch (PolyFlags & PF_Blending) { - case PF_Translucent & PF_Blending: - pglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // alpha = level of transparency - pglAlphaFunc(GL_NOTEQUAL, 0.0f); - break; - case PF_Masked & PF_Blending: - // Hurdler: does that mean lighting is only made by alpha src? - // it sounds ok, but not for polygonsmooth - pglBlendFunc(GL_SRC_ALPHA, GL_ZERO); // 0 alpha = holes in texture - pglAlphaFunc(GL_GREATER, 0.5f); - break; - case PF_Additive & PF_Blending: - pglBlendFunc(GL_SRC_ALPHA, GL_ONE); // src * alpha + dest - pglAlphaFunc(GL_NOTEQUAL, 0.0f); - break; - case PF_Environment & PF_Blending: - pglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - pglAlphaFunc(GL_NOTEQUAL, 0.0f); - break; - case PF_Substractive & PF_Blending: - // good for shadow - // not really but what else ? - pglBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); - pglAlphaFunc(GL_NOTEQUAL, 0.0f); - break; - case PF_Fog & PF_Fog: - // Sryder: Fog - // multiplies input colour by input alpha, and destination colour by input colour, then adds them - pglBlendFunc(GL_SRC_ALPHA, GL_SRC_COLOR); - pglAlphaFunc(GL_ALWAYS, 0.0f); // Don't discard zero alpha fragments - break; - default : // must be 0, otherwise it's an error - // No blending - pglBlendFunc(GL_ONE, GL_ZERO); // the same as no blending - pglAlphaFunc(GL_GREATER, 0.5f); - break; - } - } - if (Xor & PF_NoAlphaTest) - { - if (PolyFlags & PF_NoAlphaTest) - pglDisable(GL_ALPHA_TEST); - else - pglEnable(GL_ALPHA_TEST); // discard 0 alpha pixels (holes in texture) - } + CurrentPolyFlags = PolyFlags; + return; + } - if (Xor & PF_Decal) + if (Xor & PF_Blending) // if blending mode must be changed + { + switch (PolyFlags & PF_Blending) { - if (PolyFlags & PF_Decal) - pglEnable(GL_POLYGON_OFFSET_FILL); - else - pglDisable(GL_POLYGON_OFFSET_FILL); - } - if (Xor&PF_NoDepthTest) - { - if (PolyFlags & PF_NoDepthTest) - pglDepthFunc(GL_ALWAYS); //pglDisable(GL_DEPTH_TEST); - else - pglDepthFunc(GL_LEQUAL); //pglEnable(GL_DEPTH_TEST); + case (PF_Translucent & PF_Blending): + pglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // alpha = level of transparency + pglAlphaFunc(GL_NOTEQUAL, 0.0f); + break; + case (PF_Masked & PF_Blending): + // Hurdler: does that mean lighting is only made by alpha src? + // it sounds ok, but not for polygonsmooth + pglBlendFunc(GL_SRC_ALPHA, GL_ZERO); // 0 alpha = holes in texture + pglAlphaFunc(GL_GREATER, 0.5f); + break; + case (PF_Additive & PF_Blending): + pglBlendFunc(GL_SRC_ALPHA, GL_ONE); // src * alpha + dest + pglAlphaFunc(GL_NOTEQUAL, 0.0f); + break; + case (PF_Environment & PF_Blending): + pglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + pglAlphaFunc(GL_NOTEQUAL, 0.0f); + break; + case (PF_Substractive & PF_Blending): + // good for shadow + // not really but what else ? + pglBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); + pglAlphaFunc(GL_NOTEQUAL, 0.0f); + break; + case (PF_Fog & PF_Fog): + // Sryder: Fog + // multiplies input colour by input alpha, and destination colour by input colour, then adds them + pglBlendFunc(GL_SRC_ALPHA, GL_SRC_COLOR); + pglAlphaFunc(GL_ALWAYS, 0.0f); // Don't discard zero alpha fragments + break; + default : // must be 0, otherwise it's an error + // No blending + pglBlendFunc(GL_ONE, GL_ZERO); // the same as no blending + pglAlphaFunc(GL_GREATER, 0.5f); + break; } + } - if (Xor&PF_RemoveYWrap) - { - if (PolyFlags & PF_RemoveYWrap) - Clamp2D(GL_TEXTURE_WRAP_T); - } + if (Xor & PF_NoAlphaTest) + { + if (PolyFlags & PF_NoAlphaTest) + pglDisable(GL_ALPHA_TEST); + else + pglEnable(GL_ALPHA_TEST); // discard 0 alpha pixels (holes in texture) + } - if (Xor&PF_ForceWrapX) - { - if (PolyFlags & PF_ForceWrapX) - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - } + if (Xor & PF_Decal) + { + if (PolyFlags & PF_Decal) + pglEnable(GL_POLYGON_OFFSET_FILL); + else + pglDisable(GL_POLYGON_OFFSET_FILL); + } + if (Xor & PF_NoDepthTest) + { + if (PolyFlags & PF_NoDepthTest) + pglDepthFunc(GL_ALWAYS); //pglDisable(GL_DEPTH_TEST); + else + pglDepthFunc(GL_LEQUAL); //pglEnable(GL_DEPTH_TEST); + } - if (Xor&PF_ForceWrapY) - { - if (PolyFlags & PF_ForceWrapY) - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - } + if (Xor & PF_RemoveYWrap) + { + if (PolyFlags & PF_RemoveYWrap) + Clamp2D(GL_TEXTURE_WRAP_T); + } - if (Xor&PF_Modulated) - { + if (Xor & PF_ForceWrapX) + { + if (PolyFlags & PF_ForceWrapX) + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + } + + if (Xor & PF_ForceWrapY) + { + if (PolyFlags & PF_ForceWrapY) + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + } + + if (Xor & PF_Modulated) + { #if defined (__unix__) || defined (UNIXCOMMON) - if (oglflags & GLF_NOTEXENV) - { - if (!(PolyFlags & PF_Modulated)) - pglColor4ubv(white); - } - else + if (oglflags & GLF_NOTEXENV) + { + if (!(PolyFlags & PF_Modulated)) + pglColor4ubv(white); + } + else #endif - // mix texture colour with Surface->PolyColor - if (PolyFlags & PF_Modulated) - pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - // colour from texture is unchanged before blending - else - pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - } - - if (Xor & PF_Occlude) // depth test but (no) depth write - { - if (PolyFlags&PF_Occlude) - pglDepthMask(1); - else - pglDepthMask(0); - } - ////Hurdler: not used if we don't define POLYSKY - if (Xor & PF_Invisible) - { - if (PolyFlags&PF_Invisible) - pglBlendFunc(GL_ZERO, GL_ONE); // transparent blending - else - { // big hack: (TODO: manage that better) - // we test only for PF_Masked because PF_Invisible is only used - // (for now) with it (yeah, that's crappy, sorry) - if ((PolyFlags&PF_Blending)==PF_Masked) - pglBlendFunc(GL_SRC_ALPHA, GL_ZERO); - } - } - if (PolyFlags & PF_NoTexture) - SetNoTexture(); + // mix texture colour with Surface->PolyColor + if (PolyFlags & PF_Modulated) + pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + // colour from texture is unchanged before blending + else + pglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } + + if (Xor & PF_Occlude) // depth test but (no) depth write + { + if (PolyFlags & PF_Occlude) + pglDepthMask(1); + else + pglDepthMask(0); + } + + ////Hurdler: not used if we don't define POLYSKY + if (Xor & PF_Invisible) + { + if (PolyFlags&PF_Invisible) + pglBlendFunc(GL_ZERO, GL_ONE); // transparent blending + else + { // big hack: (TODO: manage that better) + // we test only for PF_Masked because PF_Invisible is only used + // (for now) with it (yeah, that's crappy, sorry) + if ((PolyFlags & PF_Blending) == PF_Masked) + pglBlendFunc(GL_SRC_ALPHA, GL_ZERO); + } + } + + if (PolyFlags & PF_NoTexture) + GL_SetNoTexture(); + CurrentPolyFlags = PolyFlags; } -static void AllocTextureBuffer(GLMipmap_t *pTexInfo) +static void GL_AllocTextureBuffer(GLMipmap_t *pTexInfo) { size_t size = pTexInfo->width * pTexInfo->height; + if (size > textureBufferSize) { textureBuffer = realloc(textureBuffer, size * sizeof(RGBA_t)); @@ -1551,7 +1573,7 @@ static void AllocTextureBuffer(GLMipmap_t *pTexInfo) // -----------------+ // UpdateTexture : Updates texture data. // -----------------+ -EXPORT void HWRAPI(UpdateTexture) (GLMipmap_t *pTexInfo) +static void GL_UpdateTexture(GLMipmap_t *pTexInfo) { // Upload a texture GLuint num = pTexInfo->downloaded; @@ -1563,7 +1585,9 @@ EXPORT void HWRAPI(UpdateTexture) (GLMipmap_t *pTexInfo) const GLubyte *pImgData = (const GLubyte *)pTexInfo->data; const GLvoid *ptex = NULL; RGBA_t *tex = NULL; - + + GLint texformat = 0; + // Generate a new texture name. if (!num) { @@ -1574,91 +1598,103 @@ EXPORT void HWRAPI(UpdateTexture) (GLMipmap_t *pTexInfo) //GL_DBG_Printf("UpdateTexture %d %x\n", (INT32)num, pImgData); - if ((pTexInfo->format == GL_TEXFMT_P_8) || (pTexInfo->format == GL_TEXFMT_AP_88)) + texformat = textureformatGL; + + switch (pTexInfo->format) { - AllocTextureBuffer(pTexInfo); - ptex = tex = textureBuffer; + case GL_TEXFMT_P_8: + case GL_TEXFMT_AP_88: + GL_AllocTextureBuffer(pTexInfo); + ptex = tex = textureBuffer; - for (j = 0; j < h; j++) - { - for (i = 0; i < w; i++) + const int chromakeyed = (pTexInfo->flags & TF_CHROMAKEYED); + + for (j = 0; j < h; j++) { - if ((*pImgData == HWR_PATCHES_CHROMAKEY_COLORINDEX) && - (pTexInfo->flags & TF_CHROMAKEYED)) + for (i = 0; i < w; i++) { - tex[w*j+i].s.red = 0; - tex[w*j+i].s.green = 0; - tex[w*j+i].s.blue = 0; - tex[w*j+i].s.alpha = 0; - pTexInfo->flags |= TF_TRANSPARENT; // there is a hole in it - } - else - { - tex[w*j+i].s.red = myPaletteData[*pImgData].s.red; - tex[w*j+i].s.green = myPaletteData[*pImgData].s.green; - tex[w*j+i].s.blue = myPaletteData[*pImgData].s.blue; - tex[w*j+i].s.alpha = myPaletteData[*pImgData].s.alpha; - } + int idx = (w*j+i); - pImgData++; + if (chromakeyed && (*pImgData == HWR_PATCHES_CHROMAKEY_COLORINDEX)) + { + tex[idx].s.red = 0; + tex[idx].s.green = 0; + tex[idx].s.blue = 0; + tex[idx].s.alpha = 0; + pTexInfo->flags |= TF_TRANSPARENT; // there is a hole in it + } + else + { + tex[idx].s = myPaletteData[*pImgData].s; + } - if (pTexInfo->format == GL_TEXFMT_AP_88) - { - if (!(pTexInfo->flags & TF_CHROMAKEYED)) - tex[w*j+i].s.alpha = *pImgData; + pImgData++; + + if (pTexInfo->format != GL_TEXFMT_AP_88) + continue; + if (chromakeyed) + continue; + + tex[idx].s.alpha = *pImgData; pImgData++; } } - } - } - else if (pTexInfo->format == GL_TEXFMT_RGBA) - { - // Directly upload the texture data without any kind of conversion. - ptex = pImgData; - } - else if (pTexInfo->format == GL_TEXFMT_ALPHA_INTENSITY_88) - { - AllocTextureBuffer(pTexInfo); - ptex = tex = textureBuffer; + break; + case GL_TEXFMT_RGBA: + // Directly upload the texture data without any kind of conversion. + ptex = pImgData; + break; + case GL_TEXFMT_ALPHA_INTENSITY_88: + GL_AllocTextureBuffer(pTexInfo); + ptex = tex = textureBuffer; + texformat = GL_LUMINANCE_ALPHA; - for (j = 0; j < h; j++) - { - for (i = 0; i < w; i++) + for (j = 0; j < h; j++) { - tex[w*j+i].s.red = *pImgData; - tex[w*j+i].s.green = *pImgData; - tex[w*j+i].s.blue = *pImgData; - pImgData++; - tex[w*j+i].s.alpha = *pImgData; - pImgData++; - } - } - } - else if (pTexInfo->format == GL_TEXFMT_ALPHA_8) // Used for fade masks - { - AllocTextureBuffer(pTexInfo); - ptex = tex = textureBuffer; + for (i = 0; i < w; i++) + { + int idx = (w*j+i); - for (j = 0; j < h; j++) - { - for (i = 0; i < w; i++) - { - tex[w*j+i].s.red = 255; // 255 because the fade mask is modulated with the screen texture, so alpha affects it while the colours don't - tex[w*j+i].s.green = 255; - tex[w*j+i].s.blue = 255; - tex[w*j+i].s.alpha = *pImgData; - pImgData++; + tex[idx].s.red = *pImgData; + tex[idx].s.green = *pImgData; + tex[idx].s.blue = *pImgData; + pImgData++; + tex[idx].s.alpha = *pImgData; + pImgData++; + } } - } + break; + case GL_TEXFMT_ALPHA_8: // Used for fade masks + GL_AllocTextureBuffer(pTexInfo); + ptex = tex = textureBuffer; + texformat = GL_ALPHA; + + for (j = 0; j < h; j++) + { + for (i = 0; i < w; i++) + { + int idx = (w*j+i); + + tex[idx].s.red = 255; // 255 because the fade mask is modulated with the screen texture, so alpha affects it while the colours don't + tex[idx].s.green = 255; + tex[idx].s.blue = 255; + tex[idx].s.alpha = *pImgData; + pImgData++; + } + } + break; + default: + GL_MSG_Warning("UpdateTexture: bad format %d\n", pTexInfo->format); + break; } - else - GL_MSG_Warning("UpdateTexture: bad format %d\n", pTexInfo->format); pglBindTexture(GL_TEXTURE_2D, num); tex_downloaded = num; + const int transparent = (pTexInfo->flags & TF_TRANSPARENT); + // disable texture filtering on any texture that has holes so there's no dumb borders or blending issues - if (pTexInfo->flags & TF_TRANSPARENT) + if (transparent) { pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); @@ -1669,73 +1705,25 @@ EXPORT void HWRAPI(UpdateTexture) (GLMipmap_t *pTexInfo) pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter); } - if (pTexInfo->format == GL_TEXFMT_ALPHA_INTENSITY_88) + if (MipMap && !transparent) // No mipmaps on transparent stuff { - //pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - if (MipMap) - { - pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - pglTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); - if (pTexInfo->flags & TF_TRANSPARENT) - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 0); // No mippmaps on transparent stuff - else - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); - //pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_LINEAR_MIPMAP_LINEAR); - } + if (update) + pglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); else - { - if (update) - pglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - else - pglTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - } - } - else if (pTexInfo->format == GL_TEXFMT_ALPHA_8) - { - //pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - if (MipMap) - { - pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); + pglTexImage2D(GL_TEXTURE_2D, 0, texformat, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); - if (pTexInfo->flags & TF_TRANSPARENT) - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 0); // No mippmaps on transparent stuff - else - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); - //pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_LINEAR_MIPMAP_LINEAR); - } - else - { - if (update) - pglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - else - pglTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - } + // Control the mipmap level of detail + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); } else { - if (MipMap) - { - pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - pglTexImage2D(GL_TEXTURE_2D, 0, textureformatGL, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - - // Control the mipmap level of detail - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); // the lower the number, the higer the detail - if (pTexInfo->flags & TF_TRANSPARENT) - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 0); // No mippmaps on transparent stuff - else - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 5); - } + if (update) + pglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); else - { - if (update) - pglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - else - pglTexImage2D(GL_TEXTURE_2D, 0, textureformatGL, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); - } + pglTexImage2D(GL_TEXTURE_2D, 0, texformat, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptex); } if (pTexInfo->flags & TF_WRAPX) @@ -1756,18 +1744,19 @@ EXPORT void HWRAPI(UpdateTexture) (GLMipmap_t *pTexInfo) // -----------------+ // SetTexture : The mipmap becomes the current texture source // -----------------+ -EXPORT void HWRAPI(SetTexture) (GLMipmap_t *pTexInfo) +void GL_SetTexture(GLMipmap_t *pTexInfo) { if (!pTexInfo) { - SetNoTexture(); + GL_SetNoTexture(); return; } else if (pTexInfo->downloaded) { if (pTexInfo->downloaded != tex_downloaded) { - pglBindTexture(GL_TEXTURE_2D, pTexInfo->downloaded); + if (!currently_batching) + pglBindTexture(GL_TEXTURE_2D, pTexInfo->downloaded); tex_downloaded = pTexInfo->downloaded; } } @@ -1775,7 +1764,7 @@ EXPORT void HWRAPI(SetTexture) (GLMipmap_t *pTexInfo) { FTextureInfo *newTex = calloc(1, sizeof (*newTex)); - UpdateTexture(pTexInfo); + GL_UpdateTexture(pTexInfo); newTex->texture = pTexInfo; newTex->downloaded = (UINT32)pTexInfo->downloaded; @@ -1795,7 +1784,7 @@ EXPORT void HWRAPI(SetTexture) (GLMipmap_t *pTexInfo) } } -static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade) +static void GL_Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAFloat *tint, GLRGBAFloat *fade) { gl_shader_t *shader = gl_shaderstate.current; @@ -1860,7 +1849,7 @@ static void Shader_SetUniforms(FSurfaceInfo *Surface, GLRGBAFloat *poly, GLRGBAF } } -static boolean Shader_CompileProgram(gl_shader_t *shader, GLint i) +static boolean GL_Shader_CompileProgram(gl_shader_t *shader, GLint i) { GLuint gl_vertShader = 0; GLuint gl_fragShader = 0; @@ -2005,13 +1994,13 @@ static boolean Shader_CompileProgram(gl_shader_t *shader, GLint i) // code that is common between DrawPolygon and DrawIndexedTriangles // DrawScreenTexture also can use this function for fancier screen texture drawing // the corona thing is there too, i have no idea if that stuff works with DrawIndexedTriangles and batching -static void PreparePolygon(FSurfaceInfo *pSurf, FBITFIELD PolyFlags) +static void GL_PreparePolygon(FSurfaceInfo *pSurf, FBITFIELD PolyFlags) { static GLRGBAFloat poly = {0,0,0,0}; static GLRGBAFloat tint = {0,0,0,0}; static GLRGBAFloat fade = {0,0,0,0}; - SetBlend(PolyFlags); //TODO: inline (#pragma..) + GL_SetBlend(PolyFlags); //TODO: inline (#pragma..) if (pSurf) { @@ -2051,15 +2040,15 @@ static void PreparePolygon(FSurfaceInfo *pSurf, FBITFIELD PolyFlags) } } - Shader_SetUniforms(pSurf, &poly, &tint, &fade); + GL_Shader_SetUniforms(pSurf, &poly, &tint, &fade); } // -----------------+ // DrawPolygon : Render a polygon, set the texture, set render mode // -----------------+ -EXPORT void HWRAPI(DrawPolygon) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags) +void GL_DrawPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags) { - PreparePolygon(pSurf, PolyFlags); + GL_PreparePolygon(pSurf, PolyFlags); pglVertexPointer(3, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].x); pglTexCoordPointer(2, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].s); @@ -2075,9 +2064,9 @@ EXPORT void HWRAPI(DrawPolygon) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUI Clamp2D(GL_TEXTURE_WRAP_T); } -EXPORT void HWRAPI(DrawIndexedTriangles) (FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, unsigned int *IndexArray) +void GL_DrawIndexedTriangles(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, unsigned int *IndexArray) { - PreparePolygon(pSurf, PolyFlags); + GL_PreparePolygon(pSurf, PolyFlags); pglVertexPointer(3, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].x); pglTexCoordPointer(2, GL_FLOAT, sizeof(FOutVector), &pOutVerts[0].s); @@ -2086,236 +2075,83 @@ EXPORT void HWRAPI(DrawIndexedTriangles) (FSurfaceInfo *pSurf, FOutVector *pOutV // the DrawPolygon variant of this has some code about polyflags and wrapping here but havent noticed any problems from omitting it? } -// Sky dome code, taken/backported from SRB2 - -typedef struct vbo_vertex_s -{ - float x, y, z; - float u, v; - unsigned char r, g, b, a; -} vbo_vertex_t; - -typedef struct -{ - int mode; - int vertexcount; - int vertexindex; - int use_texture; -} GLSkyLoopDef; - -typedef struct -{ - unsigned int id; - int rows, columns; - int loopcount; - GLSkyLoopDef *loops; - vbo_vertex_t *data; -} GLSkyVBO; - static const boolean gl_ext_arb_vertex_buffer_object = true; -#define NULL_VBO_VERTEX ((vbo_vertex_t*)NULL) -#define sky_vbo_x (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->x : &vbo->data[0].x) -#define sky_vbo_u (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->u : &vbo->data[0].u) -#define sky_vbo_r (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->r : &vbo->data[0].r) +#define NULL_VBO_VERTEX ((gl_skyvertex_t*)NULL) +#define sky_vbo_x (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->x : &sky->data[0].x) +#define sky_vbo_u (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->u : &sky->data[0].u) +#define sky_vbo_r (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->r : &sky->data[0].r) -// The texture offset to be applied to the texture coordinates in SkyVertex(). -static int rows, columns; -static signed char yflip; -static int texw, texh; -static boolean foglayer; -static float delta = 0.0f; - -static int gl_sky_detail = 16; - -static INT32 lasttex = -1; - -#define MAP_COEFF 128.0f - -static void SkyVertex(vbo_vertex_t *vbo, int r, int c) -{ - const float radians = (float)(M_PIl / 180.0f); - const float scale = 10000.0f; - const float maxSideAngle = 60.0f; - - float topAngle = (c / (float)columns * 360.0f); - float sideAngle = (maxSideAngle * (rows - r) / rows); - float height = (float)(sin(sideAngle * radians)); - float realRadius = (float)(scale * cos(sideAngle * radians)); - float x = (float)(realRadius * cos(topAngle * radians)); - float y = (!yflip) ? scale * height : -scale * height; - float z = (float)(realRadius * sin(topAngle * radians)); - float timesRepeat = (4 * (256.0f / texw)); - if (fpclassify(timesRepeat) == FP_ZERO) - timesRepeat = 1.0f; - - if (!foglayer) - { - vbo->r = 255; - vbo->g = 255; - vbo->b = 255; - vbo->a = (r == 0 ? 0 : 255); - - // And the texture coordinates. - //vbo->u = (-timesRepeat * c / (float)columns); - vbo->u = (timesRepeat * c / (float)columns);// TEST - if (!yflip) // Flipped Y is for the lower hemisphere. - vbo->v = (r / (float)rows) + 0.5f; - else - vbo->v = 1.0f + ((rows - r) / (float)rows) + 0.5f; - } - - if (r != 4) - { - y += 300.0f; - } - - // And finally the vertex. - vbo->x = x; - vbo->y = y + delta; - vbo->z = z; -} - -static GLSkyVBO sky_vbo; - -static void gld_BuildSky(int row_count, int col_count) -{ - int c, r; - vbo_vertex_t *vertex_p; - int vertex_count = 2 * row_count * (col_count * 2 + 2) + col_count * 2; - - GLSkyVBO *vbo = &sky_vbo; - - if ((vbo->columns != col_count) || (vbo->rows != row_count)) - { - free(vbo->loops); - free(vbo->data); - memset(vbo, 0, sizeof(&vbo)); - } - - if (!vbo->data) - { - memset(vbo, 0, sizeof(&vbo)); - vbo->loops = malloc((row_count * 2 + 2) * sizeof(vbo->loops[0])); - // create vertex array - vbo->data = malloc(vertex_count * sizeof(vbo->data[0])); - } - - vbo->columns = col_count; - vbo->rows = row_count; - - vertex_p = &vbo->data[0]; - vbo->loopcount = 0; - - for (yflip = 0; yflip < 2; yflip++) - { - vbo->loops[vbo->loopcount].mode = GL_TRIANGLE_FAN; - vbo->loops[vbo->loopcount].vertexindex = vertex_p - &vbo->data[0]; - vbo->loops[vbo->loopcount].vertexcount = col_count; - vbo->loops[vbo->loopcount].use_texture = false; - vbo->loopcount++; - - delta = 0.0f; - foglayer = true; - for (c = 0; c < col_count; c++) - { - SkyVertex(vertex_p, 1, c); - vertex_p->r = 255; - vertex_p->g = 255; - vertex_p->b = 255; - vertex_p->a = 255; - vertex_p++; - } - foglayer = false; - - delta = (yflip ? 5.0f : -5.0f) / MAP_COEFF; - - for (r = 0; r < row_count; r++) - { - vbo->loops[vbo->loopcount].mode = GL_TRIANGLE_STRIP; - vbo->loops[vbo->loopcount].vertexindex = vertex_p - &vbo->data[0]; - vbo->loops[vbo->loopcount].vertexcount = 2 * col_count + 2; - vbo->loops[vbo->loopcount].use_texture = true; - vbo->loopcount++; - - for (c = 0; c <= col_count; c++) - { - SkyVertex(vertex_p++, r + (yflip ? 1 : 0), (c ? c : 0)); - SkyVertex(vertex_p++, r + (yflip ? 0 : 1), (c ? c : 0)); - } - } - } -} - -//----------------------------------------------------------------------------- -// -// -// -//----------------------------------------------------------------------------- - -static void RenderDome(INT32 skytexnum) +void GL_RenderSkyDome(gl_sky_t *sky) { int i, j; - int vbosize; - GLSkyVBO *vbo = &sky_vbo; - rows = 4; - columns = 4 * gl_sky_detail; - - vbosize = 2 * rows * (columns * 2 + 2) + columns * 2; + GL_Shader_SetUniforms(NULL, NULL, NULL, NULL); // Build the sky dome! Yes! - if (lasttex != skytexnum) + if (sky->rebuild) { // delete VBO when already exists if (gl_ext_arb_vertex_buffer_object) { - if (vbo->id) - pglDeleteBuffers(1, &vbo->id); + if (sky->vbo) + pglDeleteBuffers(1, &sky->vbo); } - lasttex = skytexnum; - gld_BuildSky(rows, columns); - if (gl_ext_arb_vertex_buffer_object) { // generate a new VBO and get the associated ID - pglGenBuffers(1, &vbo->id); + pglGenBuffers(1, &sky->vbo); // bind VBO in order to use - pglBindBuffer(GL_ARRAY_BUFFER, vbo->id); + pglBindBuffer(GL_ARRAY_BUFFER, sky->vbo); // upload data to VBO - pglBufferData(GL_ARRAY_BUFFER, vbosize * sizeof(vbo->data[0]), vbo->data, GL_STATIC_DRAW); + pglBufferData(GL_ARRAY_BUFFER, sky->vertex_count * sizeof(sky->data[0]), sky->data, GL_STATIC_DRAW); } + + sky->rebuild = false; } // bind VBO in order to use if (gl_ext_arb_vertex_buffer_object) - pglBindBuffer(GL_ARRAY_BUFFER, vbo->id); + pglBindBuffer(GL_ARRAY_BUFFER, sky->vbo); // activate and specify pointers to arrays - pglVertexPointer(3, GL_FLOAT, sizeof(vbo->data[0]), sky_vbo_x); - pglTexCoordPointer(2, GL_FLOAT, sizeof(vbo->data[0]), sky_vbo_u); - pglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(vbo->data[0]), sky_vbo_r); + pglVertexPointer(3, GL_FLOAT, sizeof(sky->data[0]), sky_vbo_x); + pglTexCoordPointer(2, GL_FLOAT, sizeof(sky->data[0]), sky_vbo_u); + pglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(sky->data[0]), sky_vbo_r); // activate color arrays pglEnableClientState(GL_COLOR_ARRAY); // set transforms - pglScalef(1.0f, (float)texh / 230.0f, 1.0f); + pglScalef(1.0f, (float)sky->height / 200.0f, 1.0f); pglRotatef(270.0f, 0.0f, 1.0f, 0.0f); for (j = 0; j < 2; j++) { - for (i = 0; i < vbo->loopcount; i++) + for (i = 0; i < sky->loopcount; i++) { - GLSkyLoopDef *loop = &vbo->loops[i]; + gl_skyloopdef_t *loop = &sky->loops[i]; + unsigned int mode = 0; if (j == 0 ? loop->use_texture : !loop->use_texture) continue; - pglDrawArrays(loop->mode, loop->vertexindex, loop->vertexcount); + switch (loop->mode) + { + case HWD_SKYLOOP_FAN: + mode = GL_TRIANGLE_FAN; + break; + case HWD_SKYLOOP_STRIP: + mode = GL_TRIANGLE_STRIP; + break; + default: + continue; + } + + pglDrawArrays(mode, loop->vertexindex, loop->vertexcount); } } @@ -2330,38 +2166,18 @@ static void RenderDome(INT32 skytexnum) pglDisableClientState(GL_COLOR_ARRAY); } -EXPORT void HWRAPI(RenderSkyDome) (INT32 tex, INT32 texture_width, INT32 texture_height, FTransform transform) -{ - SetBlend(PF_Translucent|PF_NoDepthTest|PF_Modulated); - SetTransform(&transform); - texw = texture_width; - texh = texture_height; - RenderDome(tex); - SetBlend(0); -} - // ========================================================================== // // ========================================================================== -EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) +void GL_SetSpecialState(hwdspecialstate_t IdState, INT32 Value) { switch (IdState) { case HWD_SET_SHADERS: gl_allowshaders = Value; break; -#ifdef USE_FBO_OGL - case HWD_SET_FRAMEBUFFER: - FrameBufferEnabled = Value ? GL_TRUE : GL_FALSE; - - if (!supportFBO) - { - FrameBufferEnabled = GL_FALSE; - CV_Set(&cv_grframebuffer, "Off"); - } - break; -#endif case HWD_SET_TEXTUREFILTERMODE: + switch (Value) { case HWD_SET_TEXTUREFILTER_TRILINEAR: @@ -2393,16 +2209,17 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) MipMap = GL_TRUE; break; default: - mag_filter = GL_LINEAR; min_filter = GL_NEAREST; + mag_filter = GL_LINEAR; } + if (!supportMipMap) { MipMap = GL_FALSE; min_filter = GL_LINEAR; } - Flush(); //??? if we want to change filter mode by texture, remove this + GL_Flush(); //??? if we want to change filter mode by texture, remove this break; case HWD_SET_MSAA: @@ -2415,9 +2232,9 @@ EXPORT void HWRAPI(SetSpecialState) (hwdspecialstate_t IdState, INT32 Value) break; case HWD_SET_TEXTUREANISOTROPICMODE: - anisotropic_filter = min(Value,maximumAnisotropy); + anisotropic_filter = min(Value, maximumAnisotropy); if (maximumAnisotropy) - Flush(); //??? if we want to change filter mode by texture, remove this + GL_Flush(); //??? if we want to change filter mode by texture, remove this break; case HWD_SET_SCREEN_TEXTURES: @@ -2503,7 +2320,7 @@ static size_t lerpTinyBufferSize = 0; // Static temporary buffer for doing frame interpolation // 'size' is the vertex size -static void AllocLerpBuffer(size_t size) +static void GL_AllocLerpBuffer(size_t size) { if (lerpBufferSize >= size) return; @@ -2521,7 +2338,7 @@ static void AllocLerpBuffer(size_t size) // Static temporary buffer for doing frame interpolation // 'size' is the vertex size -static void AllocLerpTinyBuffer(size_t size) +static void GL_AllocLerpTinyBuffer(size_t size) { if (lerpTinyBufferSize >= size) return; @@ -2545,7 +2362,7 @@ static void AllocLerpTinyBuffer(size_t size) #define GL_ARRAY_BUFFER 0x8892 #endif -static void CreateModelVBO(mesh_t *mesh, mdlframe_t *frame) +static void GL_CreateModelVBO(mesh_t *mesh, mdlframe_t *frame) { int bufferSize = sizeof(vbo64_t)*mesh->numTriangles * 3; vbo64_t *buffer = (vbo64_t*)malloc(bufferSize); @@ -2613,7 +2430,7 @@ static void CreateModelVBO(mesh_t *mesh, mdlframe_t *frame) pglBindBuffer(GL_ARRAY_BUFFER, 0); } -static void CreateModelVBOTiny(mesh_t *mesh, tinyframe_t *frame) +static void GL_CreateModelVBOTiny(mesh_t *mesh, tinyframe_t *frame) { int bufferSize = sizeof(vbotiny_t)*mesh->numTriangles * 3; vbotiny_t *buffer = (vbotiny_t*)malloc(bufferSize); @@ -2658,9 +2475,10 @@ static void CreateModelVBOTiny(mesh_t *mesh, tinyframe_t *frame) pglBindBuffer(GL_ARRAY_BUFFER, 0); } -EXPORT void HWRAPI(CreateModelVBOs) (model_t *model) +void GL_CreateModelVBOs(model_t *model) { int i; + for (i = 0; i < model->numMeshes; i++) { mesh_t *mesh = &model->meshes[i]; @@ -2674,7 +2492,7 @@ EXPORT void HWRAPI(CreateModelVBOs) (model_t *model) if (frame->vboID) pglDeleteBuffers(1, &frame->vboID); frame->vboID = 0; - CreateModelVBO(mesh, frame); + GL_CreateModelVBO(mesh, frame); } } else if (mesh->tinyframes) @@ -2686,7 +2504,7 @@ EXPORT void HWRAPI(CreateModelVBOs) (model_t *model) if (frame->vboID) pglDeleteBuffers(1, &frame->vboID); frame->vboID = 0; - CreateModelVBOTiny(mesh, frame); + GL_CreateModelVBOTiny(mesh, frame); } } } @@ -2694,7 +2512,7 @@ EXPORT void HWRAPI(CreateModelVBOs) (model_t *model) #define BUFFER_OFFSET(i) ((char*)(i)) -static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface) +void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface) { static GLRGBAFloat poly = {0,0,0,0}; static GLRGBAFloat tint = {0,0,0,0}; @@ -2733,9 +2551,9 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float poly.alpha = byte2float[Surface->PolyColor.s.alpha]; if (poly.alpha < 1) - SetBlend(PF_Translucent|PF_Modulated); + GL_SetBlend(PF_Translucent|PF_Modulated); else - SetBlend(PF_Masked|PF_Modulated|PF_Occlude); + GL_SetBlend(PF_Masked|PF_Modulated|PF_Occlude); pglColor4ubv((GLubyte*)&Surface->PolyColor.s); @@ -2757,7 +2575,7 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float lt_downloaded = Surface->LightTableId; } - Shader_SetUniforms(Surface, &poly, &tint, &fade); + GL_Shader_SetUniforms(Surface, &poly, &tint, &fade); pglEnable(GL_CULL_FACE); pglEnable(GL_NORMALIZE); @@ -2853,7 +2671,7 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float int j = 0; // Dangit, I soooo want to do this in a GLSL shader... - AllocLerpTinyBuffer(mesh->numVertices * sizeof(short) * 3); + GL_AllocLerpTinyBuffer(mesh->numVertices * sizeof(short) * 3); vertPtr = vertTinyBuffer; normPtr = normTinyBuffer; @@ -2896,7 +2714,7 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float int j = 0; // Dangit, I soooo want to do this in a GLSL shader... - AllocLerpBuffer(mesh->numVertices * sizeof(float) * 3); + GL_AllocLerpBuffer(mesh->numVertices * sizeof(float) * 3); vertPtr = vertBuffer; normPtr = normBuffer; @@ -2922,18 +2740,10 @@ static void DrawModelEx(model_t *model, INT32 frameIndex, float duration, float pglDisable(GL_NORMALIZE); } -// -----------------+ -// HWRAPI DrawModel : Draw a model -// -----------------+ -EXPORT void HWRAPI(DrawModel) (model_t *model, INT32 frameIndex, float duration, float tics, INT32 nextFrameIndex, FTransform *pos, float hscale, float vscale, UINT8 flipped, UINT8 hflipped, FSurfaceInfo *Surface) -{ - DrawModelEx(model, frameIndex, duration, tics, nextFrameIndex, pos, hscale, vscale, flipped, hflipped, Surface); -} - // -----------------+ // SetTransform : // -----------------+ -EXPORT void HWRAPI(SetTransform) (FTransform *stransform) +void GL_SetTransform(FTransform *stransform) { static boolean special_splitscreen; GLdouble used_fov; @@ -2992,11 +2802,11 @@ EXPORT void HWRAPI(SetTransform) (FTransform *stransform) if (special_splitscreen) { - used_fov = (float)(atan(tan(used_fov*M_PI/360)*0.8)*360/M_PI); - GLPerspective((GLfloat)used_fov, 2*ASPECT_RATIO); + used_fov = (float)(atan(tan(used_fov * M_PIl / 360) * 0.8) * 360 / M_PIl); + GL_Perspective((GLfloat)used_fov, 2*ASPECT_RATIO); } else - GLPerspective((GLfloat)used_fov, ASPECT_RATIO); + GL_Perspective((GLfloat)used_fov, ASPECT_RATIO); pglGetFloatv(GL_PROJECTION_MATRIX, projMatrix); // added for new coronas' code (without depth buffer) pglMatrixMode(GL_MODELVIEW); @@ -3004,7 +2814,7 @@ EXPORT void HWRAPI(SetTransform) (FTransform *stransform) pglGetFloatv(GL_MODELVIEW_MATRIX, modelMatrix); // added for new coronas' code (without depth buffer) } -EXPORT INT32 HWRAPI(GetTextureUsed) (void) +INT32 GL_GetTextureUsed(void) { FTextureInfo *tmp = TexCacheHead; INT32 res = 0; @@ -3029,7 +2839,7 @@ EXPORT INT32 HWRAPI(GetTextureUsed) (void) return res; } -EXPORT void HWRAPI(PostImgRedraw) (float points[SCREENVERTS][SCREENVERTS][2]) +void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2]) { INT32 x, y; float float_x, float_y, float_nextx, float_nexty; @@ -3066,9 +2876,9 @@ EXPORT void HWRAPI(PostImgRedraw) (float points[SCREENVERTS][SCREENVERTS][2]) pglDrawArrays(GL_TRIANGLE_FAN, 0, 4); pglEnableClientState(GL_TEXTURE_COORD_ARRAY); - for(x=0;xcurl, CURLOPT_POSTFIELDS, post); - ok = HMS_do(hms); + okay = HMS_do(hms); - if (ok) + if (okay) { hms_server_token = strdup(strtok(hms->buffer, "\n")); } HMS_end(hms); - return ok; + return okay; } int HMS_unlist (void) { struct HMS_buffer *hms; - int ok; + int okay; hms = HMS_connect("servers/%s/unlist", hms_server_token); @@ -342,19 +342,19 @@ HMS_unlist (void) curl_easy_setopt(hms->curl, CURLOPT_POST, 1); curl_easy_setopt(hms->curl, CURLOPT_POSTFIELDSIZE, 0); - ok = HMS_do(hms); + okay = HMS_do(hms); HMS_end(hms); free(hms_server_token); - return ok; + return okay; } int HMS_update (void) { struct HMS_buffer *hms; - int ok; + int okay; char post[256]; @@ -376,10 +376,10 @@ HMS_update (void) curl_easy_setopt(hms->curl, CURLOPT_POSTFIELDS, post); - ok = HMS_do(hms); + okay = HMS_do(hms); HMS_end(hms); - return ok; + return okay; } void @@ -488,7 +488,7 @@ int HMS_compare_mod_version (char *buffer, size_t buffer_size) { struct HMS_buffer *hms; - int ok; + int okay; char *version; char *version_name; @@ -498,7 +498,7 @@ HMS_compare_mod_version (char *buffer, size_t buffer_size) if (! hms) return 0; - ok = 0; + okay = 0; if (HMS_do(hms)) { @@ -510,16 +510,16 @@ HMS_compare_mod_version (char *buffer, size_t buffer_size) if (atoi(version) != MODVERSION) { strlcpy(buffer, version_name, buffer_size); - ok = 1; + okay = 1; } else - ok = -1; + okay = -1; } } HMS_end(hms); - return ok; + return okay; } const char * @@ -532,9 +532,9 @@ HMS_fetch_rules (char *buffer, size_t buffer_size) if (! hms) return NULL; - boolean ok = HMS_do(hms); + boolean okay = HMS_do(hms); - if (ok) + if (okay) { char *p = strstr(hms->buffer, "\n\n"); @@ -552,7 +552,7 @@ HMS_fetch_rules (char *buffer, size_t buffer_size) HMS_end(hms); - if (!ok) + if (!okay) return NULL; return buffer; diff --git a/src/hu_stuff.c b/src/hu_stuff.c index d8e345ba7..6cbb46148 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -1003,7 +1003,7 @@ static void Got_Saycmd(UINT8 **p, INT32 playernum) // run the lua hook even if we were supposed to eat the msg, netgame consistency goes first. - if (LUAh_PlayerMsg(playernum, target, flags, msg, spam_eatmsg)) + if (LUA_HookPlayerMsg(playernum, target, flags, msg, spam_eatmsg)) return; if (spam_eatmsg) @@ -2274,7 +2274,7 @@ void HU_Drawer(void) if (renderisnewtic) { LUA_HUD_ClearDrawList(luahuddrawlist_scores); - LUAh_ScoresHUD(luahuddrawlist_scores); + LUA_HUDHOOK(scores, luahuddrawlist_scores); } LUA_HUD_DrawList(luahuddrawlist_scores); @@ -2617,7 +2617,8 @@ static void HU_DrawRankings(void) boolean completed[MAXPLAYERS]; UINT32 whiteplayer = MAXPLAYERS; - V_DrawFadeScreen(0xFF00, 16); // A little more readable, and prevents cheating the fades under other circumstances. + if (!automapactive) + V_DrawFadeScreen(0xFF00, 16); // A little more readable, and prevents cheating the fades under other circumstances. if (cons_menuhighlight.value) hilicol = cons_menuhighlight.value; diff --git a/src/i_joy.h b/src/i_joy.h index f780d8018..01f29c2cd 100644 --- a/src/i_joy.h +++ b/src/i_joy.h @@ -53,6 +53,6 @@ typedef struct JoyType_s JoyType_t; for palyer[sic] 1-4's joystick/gamepad */ -extern JoyType_t Joystick, Joystick2, Joystick3, Joystick4; +extern JoyType_t Joystick[MAXSPLITSCREENPLAYERS]; #endif // __I_JOY_H__ diff --git a/src/i_net.h b/src/i_net.h index 11dbc6341..504936a3b 100644 --- a/src/i_net.h +++ b/src/i_net.h @@ -82,18 +82,10 @@ extern holepunch_t *holepunchpacket; */ extern boolean (*I_NetGet)(void); -/** \brief ask to driver if there is data waiting -*/ -extern boolean (*I_NetCanGet)(void); - /** \brief send packet within doomcom struct */ extern void (*I_NetSend)(void); -/** \brief ask to driver if all is ok to send data now -*/ -extern boolean (*I_NetCanSend)(void); - /** \brief close a connection \param nodenum node to be closed diff --git a/src/i_system.h b/src/i_system.h index f49bca4a1..baaa0d446 100644 --- a/src/i_system.h +++ b/src/i_system.h @@ -202,9 +202,13 @@ void I_JoyScale4(void); // Called by D_SRB2Main. +/** \brief to startup joystick + */ +void I_InitJoystick(UINT8 index); + /** \brief to startup the first joystick */ -void I_InitJoystick(void); +void I_InitJoystick1(void); /** \brief to startup the second joystick */ @@ -307,21 +311,9 @@ INT32 I_mkdir(const char *dirname, INT32 unixright); */ const char *I_LocateWad(void); -/** \brief First Joystick's events +/** \brief Joystick events */ -void I_GetJoystickEvents(void); - -/** \brief Second Joystick's events -*/ -void I_GetJoystick2Events(void); - -/** \brief Third Joystick's events -*/ -void I_GetJoystick3Events(void); - -/** \brief Fourth Joystick's events -*/ -void I_GetJoystick4Events(void); +void I_GetJoystickEvents(UINT8 index); /** \brief Mouses events */ diff --git a/src/i_tcp.c b/src/i_tcp.c index d7b0d3374..14dd8b5ed 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -168,7 +168,6 @@ static UINT8 UPNP_support = TRUE; #endif #include "i_addrinfo.h" -#define SELECTTEST #define DEFAULTPORT "5029" @@ -750,59 +749,6 @@ static boolean SOCK_Get(void) } #endif -// check if we can send (do not go over the buffer) -#ifndef NONET - -static fd_set masterset; - -#ifdef SELECTTEST -static boolean FD_CPY(fd_set *src, fd_set *dst, SOCKET_TYPE *fd, size_t len) -{ - size_t i; - boolean testset = false; - FD_ZERO(dst); - for (i = 0; i < len;i++) - { - if(fd[i] != (SOCKET_TYPE)ERRSOCKET && - FD_ISSET(fd[i], src) && !FD_ISSET(fd[i], dst)) // no checking for dups - { - FD_SET(fd[i], dst); - testset = true; - } - } - return testset; -} - -static boolean SOCK_CanSend(void) -{ - struct timeval timeval_for_select = {0, 0}; - fd_set tset; - int wselect; - - if(!FD_CPY(&masterset, &tset, mysockets, mysocketses)) - return false; - wselect = select(255, NULL, &tset, NULL, &timeval_for_select); - if (wselect >= 1) - return true; - return false; -} - -static boolean SOCK_CanGet(void) -{ - struct timeval timeval_for_select = {0, 0}; - fd_set tset; - int rselect; - - if(!FD_CPY(&masterset, &tset, mysockets, mysocketses)) - return false; - rselect = select(255, &tset, NULL, NULL, &timeval_for_select); - if (rselect >= 1) - return true; - return false; -} -#endif -#endif - #ifndef NONET static inline ssize_t SOCK_SendToAddr(SOCKET_TYPE socket, mysockaddr_t *sockaddr) { @@ -877,7 +823,7 @@ static void SOCK_Send(void) } } #undef ALLOWEDERROR -#endif +#endif //NONET #ifndef NONET static void SOCK_FreeNodenum(INT32 numnode) @@ -1029,7 +975,6 @@ static boolean UDP_Socket(void) mysockets[s] = ERRSOCKET; for (s = 0; s < MAXNETNODES+1; s++) nodesocket[s] = ERRSOCKET; - FD_ZERO(&masterset); s = 0; memset(&hints, 0x00, sizeof (hints)); @@ -1056,7 +1001,6 @@ static boolean UDP_Socket(void) mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen); if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET) { - FD_SET(mysockets[s], &masterset); myfamily[s] = hints.ai_family; s++; } @@ -1077,7 +1021,6 @@ static boolean UDP_Socket(void) mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen); if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET) { - FD_SET(mysockets[s], &masterset); myfamily[s] = hints.ai_family; s++; #ifdef HAVE_MINIUPNPC @@ -1110,7 +1053,6 @@ static boolean UDP_Socket(void) mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen); if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET) { - FD_SET(mysockets[s], &masterset); myfamily[s] = hints.ai_family; s++; } @@ -1131,7 +1073,6 @@ static boolean UDP_Socket(void) mysockets[s] = UDP_Bind(runp->ai_family, runp->ai_addr, (socklen_t)runp->ai_addrlen); if (mysockets[s] != (SOCKET_TYPE)ERRSOCKET) { - FD_SET(mysockets[s], &masterset); myfamily[s] = hints.ai_family; s++; } @@ -1298,16 +1239,15 @@ boolean I_InitTcpDriver(void) static void SOCK_CloseSocket(void) { size_t i; - for (i=0; i < MAXNETNODES+1; i++) + + for (i = 0; i < mysocketses; i++) { - if (mysockets[i] != (SOCKET_TYPE)ERRSOCKET - && FD_ISSET(mysockets[i], &masterset)) - { - FD_CLR(mysockets[i], &masterset); + if (mysockets[i] != (SOCKET_TYPE)ERRSOCKET) close(mysockets[i]); - } mysockets[i] = ERRSOCKET; } + + mysocketses = 0; } #endif @@ -1417,9 +1357,7 @@ static void rendezvous(int size) if (tic == refreshtic) { - #ifdef HOLEPUNCH holepunchpacket->magic = hole_punch_magic; - #endif sendto(mysockets[0], doomcom->data, size, 0, &rzv.any, sizeof rzv.ip4); } @@ -1444,7 +1382,6 @@ static void SOCK_RegisterHolePunch(void) rendezvous(4); } #endif - #endif static boolean SOCK_OpenSocket(void) @@ -1464,13 +1401,7 @@ static boolean SOCK_OpenSocket(void) I_NetFreeNodenum = SOCK_FreeNodenum; I_NetMakeNodewPort = SOCK_NetMakeNodewPort; -#ifdef SELECTTEST - // seem like not work with libsocket : ( - I_NetCanSend = SOCK_CanSend; - I_NetCanGet = SOCK_CanGet; -#endif #ifdef HOLEPUNCH - I_NetRequestHolePunch = SOCK_RequestHolePunch; I_NetRegisterHolePunch = SOCK_RegisterHolePunch; #endif diff --git a/src/i_video.h b/src/i_video.h index 6a60f8036..70321d138 100644 --- a/src/i_video.h +++ b/src/i_video.h @@ -139,13 +139,13 @@ UINT32 I_GetRefreshRate(void); boolean I_UseNativeKeyboard(void); +boolean I_CheckNativeRes(void); + #ifdef USE_FBO_OGL -#if defined (__unix__) -extern boolean xwaylandcrap; -#endif void RefreshOGLSDLSurface(void); void I_DownSample(void); +boolean UseScreenFBO(void); extern boolean downsample; #endif diff --git a/src/info.c b/src/info.c index f8cb9a6f1..7afc76bf6 100644 --- a/src/info.c +++ b/src/info.c @@ -21,7 +21,6 @@ #include "d_player.h" #include "lzf.h" -// Hey, moron! If you change this table, don't forget about the sprite enum in info.h and the sprite lights in hw_light.c! char sprnames[NUMSPRITES + 1][5] = { "NULL","UNKN","THOK","PLAY","POSS","SPOS","FISH","BUZZ","RBUZ","JETB", diff --git a/src/info.h b/src/info.h index aff87a663..4d24f729a 100644 --- a/src/info.h +++ b/src/info.h @@ -159,9 +159,6 @@ enum actionnum A_SPAWNOBJECTRELATIVE, A_CHANGEANGLERELATIVE, A_CHANGEANGLEABSOLUTE, - A_ROLLANGLE, - A_CHANGEROLLANGLERELATIVE, - A_CHANGEROLLANGLEABSOLUTE, A_PLAYSOUND, A_FINDTARGET, A_FINDTRACER, @@ -460,7 +457,6 @@ extern boolean actionsoverridden[NUMACTIONS]; #define NUMSPRITEFREESLOTS NUMMOBJFREESLOTS #define NUMSTATEFREESLOTS (NUMMOBJFREESLOTS*8) -// Hey, moron! If you change this table, don't forget about sprnames in info.c and the sprite lights in hw_light.c! typedef enum sprite { SPR_NULL, // invisible object diff --git a/src/k_director.c b/src/k_director.c index fc6e211f6..dafea6072 100644 --- a/src/k_director.c +++ b/src/k_director.c @@ -69,7 +69,7 @@ static fixed_t ScaleFromMap(fixed_t n, fixed_t scale) static boolean K_DirectorIsEnabled(void) { - return cv_director.value && !splitscreen && (gamestate == GS_LEVEL && (((stplyr && !stplyr->spectator) && (!playeringame[consoleplayer] || players[consoleplayer].spectator)) || (demo.playback && !demo.freecam && (!demo.title || !modeattacking))) && !K_DirectorIsPlayerAlone()); + return cv_director.value && !splitscreen && (gamestate == GS_LEVEL && (((!playeringame[consoleplayer] || players[consoleplayer].spectator)) || (demo.playback && !demo.freecam && (!demo.title || !modeattacking))) && !K_DirectorIsPlayerAlone()); } void K_InitDirector(void) diff --git a/src/k_kart.c b/src/k_kart.c index f71ceb049..a6aa76e4d 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -497,10 +497,9 @@ UINT8 colortranslations[MAXTRANSLATIONS][16] = { */ void K_RainbowColormap(UINT8 *dest_colormap, UINT8 skincolor) { - INT32 i; + INT32 i, j; RGBA_t color; UINT8 brightness; - INT32 j; UINT8 colorbrightnesses[16]; UINT16 brightdif; INT32 temp; @@ -523,6 +522,7 @@ void K_RainbowColormap(UINT8 *dest_colormap, UINT8 skincolor) color = V_GetColor(i); SETBRIGHTNESS(brightness, color.s.red, color.s.green, color.s.blue); brightdif = 256; + for (j = 0; j < 16; j++) { temp = abs((INT16)brightness - (INT16)colorbrightnesses[j]); @@ -725,34 +725,34 @@ void K_RegisterKartStuff(void) CV_RegisterVar(&cv_showinput); CV_RegisterVar(&cv_showlaptimes); CV_RegisterVar(&cv_newspeedometer); - + CV_RegisterVar(&cv_battlespeedo); - + CV_RegisterVar(&cv_saltyhop); CV_RegisterVar(&cv_saltyhopsfx); CV_RegisterVar(&cv_saltysquish); - + //Colourized HUD CV_RegisterVar(&cv_colorizedhud); CV_RegisterVar(&cv_colorizedhudcolor); CV_RegisterVar(&cv_colorizeditembox); - + CV_RegisterVar(&cv_darkitembox); - + CV_RegisterVar(&cv_biglaps); - + CV_RegisterVar(&cv_highresportrait); - + CV_RegisterVar(&cv_slamsound); - + CV_RegisterVar(&cv_minihead); CV_RegisterVar(&cv_showminimapnames); CV_RegisterVar(&cv_showlapemblem); - - CV_RegisterVar(&cv_stagetitle); - + + CV_RegisterVar(&cv_stagetitle); + CV_RegisterVar(&cv_lessflicker); - + CV_RegisterVar(&cv_mouseturn); } @@ -2060,6 +2060,38 @@ void K_MomentumToFacing(player_t *player) player->mo->momy = FixedMul(player->mo->momy - player->cmomy, player->mo->friction) + player->cmomy; } +static inline fixed_t K_GetProjectileSpeed(void) +{ + switch (gamespeed) + { + case 0: + return 68*mapobjectscale; // Avg Speed is 34 + break; + case 2: + return 96*mapobjectscale; // Avg Speed is 48 + break; + default: + return 82*mapobjectscale; // Avg Speed is 41 + break; + } +} + +static inline fixed_t K_GetSneakerBoostSpeed(void) +{ + switch (gamespeed) + { + case 0: + return 53740+768; + break; + case 2: + return 17294+768; + break; + default: + return 32768; + break; + } +} + // sets k_boostpower, k_speedboost, and k_accelboost to whatever we need it to be static void K_GetKartBoostPower(player_t *player) { @@ -2093,18 +2125,7 @@ static void K_GetKartBoostPower(player_t *player) if (player->kartstuff[k_sneakertimer]) // Sneaker { - switch (gamespeed) - { - case 0: - speedboost = max(speedboost, 53740+768); - break; - case 2: - speedboost = max(speedboost, 17294+768); - break; - default: - speedboost = max(speedboost, 32768); - break; - } + speedboost = max(speedboost, K_GetSneakerBoostSpeed()); accelboost = max(accelboost, 8*FRACUNIT); // + 800% } @@ -2312,7 +2333,7 @@ void K_SpinPlayer(player_t *player, mobj_t *source, INT32 type, mobj_t *inflicto UINT8 scoremultiply = 1; // PS: Inflictor is unused for all purposes here and is actually only ever relevant to Lua. It may be nil too. boolean force = false; // Used to check if Lua ShouldSpin should get us damaged reguardless of flashtics or heck knows what. - UINT8 shouldForce = LUAh_ShouldSpin(player, inflictor, source); + UINT8 shouldForce = LUA_HookShouldSpin(player, inflictor, source); if (P_MobjWasRemoved(player->mo)) return; // mobj was removed (in theory that shouldn't happen) @@ -2345,7 +2366,7 @@ void K_SpinPlayer(player_t *player, mobj_t *source, INT32 type, mobj_t *inflicto } } - if (LUAh_PlayerSpin(player, inflictor, source)) // Let Lua do its thing or overwrite if it wants to. Make sure to let any possible instashield happen because we didn't get "damaged" in this case. + if (LUA_HookPlayerSpin(player, inflictor, source)) // Let Lua do its thing or overwrite if it wants to. Make sure to let any possible instashield happen because we didn't get "damaged" in this case. return; if (source && source != player->mo && source->player) @@ -2453,7 +2474,7 @@ void K_SquishPlayer(player_t *player, mobj_t *source, mobj_t *inflictor) UINT8 scoremultiply = 1; // PS: Inflictor is unused for all purposes here and is actually only ever relevant to Lua. It may be nil too. boolean force = false; // Used to check if Lua ShouldSquish should get us damaged reguardless of flashtics or heck knows what. - UINT8 shouldForce = LUAh_ShouldSquish(player, inflictor, source); + UINT8 shouldForce = LUA_HookShouldSquish(player, inflictor, source); if (P_MobjWasRemoved(player->mo)) return; // mobj was removed (in theory that shouldn't happen) if (shouldForce == 1) @@ -2483,7 +2504,7 @@ void K_SquishPlayer(player_t *player, mobj_t *source, mobj_t *inflictor) } } - if (LUAh_PlayerSquish(player, inflictor, source)) // Let Lua do its thing or overwrite if it wants to. Make sure to let any possible instashield happen because we didn't get "damaged" in this case. + if (LUA_HookPlayerSquish(player, inflictor, source)) // Let Lua do its thing or overwrite if it wants to. Make sure to let any possible instashield happen because we didn't get "damaged" in this case. return; player->kartstuff[k_sneakertimer] = 0; @@ -2564,7 +2585,7 @@ void K_ExplodePlayer(player_t *player, mobj_t *source, mobj_t *inflictor) // A b fixed_t upgoer; UINT8 scoremultiply = 1; boolean force = false; // Used to check if Lua ShouldExplode should get us damaged reguardless of flashtics or heck knows what. - UINT8 shouldForce = LUAh_ShouldExplode(player, inflictor, source); + UINT8 shouldForce = LUA_HookShouldExplode(player, inflictor, source); if (P_MobjWasRemoved(player->mo)) return; // mobj was removed (in theory that shouldn't happen) @@ -2597,7 +2618,7 @@ void K_ExplodePlayer(player_t *player, mobj_t *source, mobj_t *inflictor) // A b } } - if (LUAh_PlayerExplode(player, inflictor, source)) // Same thing. Also make sure to let Instashield happen blah blah + if (LUA_HookPlayerExplode(player, inflictor, source)) // Same thing. Also make sure to let Instashield happen blah blah return; if (source && source != player->mo && source->player) @@ -2779,16 +2800,9 @@ void K_SpawnKartExplosion(fixed_t x, fixed_t y, fixed_t z, fixed_t radius, INT32 TVector v; TVector *res; fixed_t finalx, finaly, finalz, dist; - //mobj_t hoopcenter; angle_t degrees, fa, closestangle; fixed_t mobjx, mobjy, mobjz; - //hoopcenter.x = x; - //hoopcenter.y = y; - //hoopcenter.z = z; - - //hoopcenter.z = z - mobjinfo[type].height/2; - degrees = FINEANGLES/number; closestangle = 0; @@ -3089,7 +3103,7 @@ static void K_SpawnDriftSparks(player_t *player) //spark->momz = player->mo->momz/2; // rotate the sparks based on pitch and roll; it just looks neat - if (cv_sparkroll.value == 1) + if (cv_sparkroll.value) { spark->slopepitch = player->mo->slopepitch; spark->sloperoll = player->mo->sloperoll; @@ -3174,17 +3188,19 @@ static void K_SpawnAIZDust(player_t *player) static void K_StretchPlayerGravity(player_t *p) { - fixed_t mos = FRACUNIT; - fixed_t rzs = abs(p->mo->momz); - fixed_t zspd = abs(rzs/mos); + I_Assert(p != NULL); + I_Assert(p->mo != NULL); + I_Assert(!P_MobjWasRemoved(p->mo)); + + fixed_t mos = FRACUNIT; + fixed_t rzs = abs(p->mo->momz); + fixed_t zspd = abs(rzs/mos); fixed_t stretchScaleFactor = 0; fixed_t rzsDiv = 1; fixed_t slamDiv = 1; - fixed_t dxs = p->mo->realxscale; - fixed_t dys = p->mo->realyscale; - //boolean gravSlamming = false; - //fixed_t impactFactor = 0; + fixed_t dxs = p->mo->realxscale; + fixed_t dys = p->mo->realyscale; stretchScaleFactor = FixedDiv(FRACUNIT*60, cv_gravstretch.value); if (stretchScaleFactor > 17476977) @@ -3194,10 +3210,6 @@ static void K_StretchPlayerGravity(player_t *p) //CONS_Printf(M_GetText("div: %d, scale factor: %d, stretch value: %d\n"), rzsDiv, stretchScaleFactor, cv_gravstretch.value); - I_Assert(p != NULL); - I_Assert(p->mo != NULL); - I_Assert(!P_MobjWasRemoved(p->mo)); - if (p->mo->slamsoundtimer) p->mo->slamsoundtimer--; @@ -3207,43 +3219,43 @@ static void K_StretchPlayerGravity(player_t *p) p->mo->slamsoundtimer = TICRATE; } - if (!P_IsObjectOnGround(p->mo)) - { - if (zspd != 0) - { - if (((dxs-(rzsDiv))) > (dxs/5)) - { - p->mo->spritexscale = ((dxs-(rzsDiv))); - p->mo->stretchslam = rzs; - } - else - p->mo->spritexscale = (dxs/5); + if (!P_IsObjectOnGround(p->mo)) + { + if (zspd != 0) + { + if (((dxs-(rzsDiv))) > (dxs/5)) + { + p->mo->spritexscale = ((dxs-(rzsDiv))); + p->mo->stretchslam = rzs; + } + else + p->mo->spritexscale = (dxs/5); - p->mo->spriteyscale = (dys+((rzsDiv*2)/3)); - } - else - { - p->mo->spritexscale = (dxs); - p->mo->spriteyscale = (dys); - } - } - else - { + p->mo->spriteyscale = (dys+((rzsDiv*2)/3)); + } + else + { + p->mo->spritexscale = (dxs); + p->mo->spriteyscale = (dys); + } + } + else + { if (stretchScaleFactor > 17476977) slamDiv = 0; else slamDiv = FixedDiv(p->mo->stretchslam, stretchScaleFactor); - - p->mo->spritexscale = (dxs+(((slamDiv*2)/3)*2)); - p->mo->spriteyscale = (dys-(slamDiv)); - if (p->mo->stretchslam > 0) - p->mo->stretchslam -= (4*mos); - else - p->mo->stretchslam = 0; - } + + p->mo->spritexscale = (dxs+(((slamDiv*2)/3)*2)); + p->mo->spriteyscale = (dys-(slamDiv)); + if (p->mo->stretchslam > 0) + p->mo->stretchslam -= (4*mos); + else + p->mo->stretchslam = 0; + } } -static void K_QuiteSaltyHop(player_t *p) +static void K_QuiteSaltyHop(player_t *p) { // what the fuck is this haya fixed_t mos = FRACUNIT; // doesnt work correctly if it isnt :/ @@ -3265,7 +3277,7 @@ static void K_QuiteSaltyHop(player_t *p) p->mo->salty_zoffset = 0; p->mo->salty_momz = 0; p->mo->init_salty = true; - } + } else if ((p->mo->salty_jump)) { if (p->mo->eflags & MFE_JUSTHITFLOOR) { p->mo->salty_zoffset = 0; @@ -3299,65 +3311,66 @@ static void K_QuiteSaltyHop(player_t *p) p->mo->salty_jump = true; p->mo->salty_zoffset = 0; p->mo->salty_momz = 6*mos; - if (cv_saltyhopsfx.value) + if (cv_saltyhopsfx.value) S_StartSound(p->mo, sfx_s25a); } } #define SLOPEROLL_DIV 3 - void K_RollMobjBySlopes(mobj_t* mo, boolean usedistance) { - I_Assert(mo->subsector != NULL); - I_Assert(mo->subsector->sector != NULL); + if (P_MobjWasRemoved(mo)) + return; - angle_t an; - boolean flip = mo->eflags & MFE_VERTICALFLIP; - fixed_t m_dist = R_PointToDist(mo->x, mo->y); - fixed_t rolldist = cv_sloperolldist.value * mapobjectscale; + I_Assert(mo->subsector != NULL); + I_Assert(mo->subsector->sector != NULL); - // lifted from hw_md2 - if (mo->standingslope) - { - fixed_t tempz = mo->standingslope->normal.z; - fixed_t tempy = mo->standingslope->normal.y; - fixed_t tempx = mo->standingslope->normal.x; - fixed_t tempangle = -(R_PointToAngle2( - 0, 0, FixedSqrt(FixedMul(tempy, tempy) + FixedMul(tempz, tempz)), tempx)); + // lifted from hw_md2 + if (mo->standingslope) + { + angle_t an; + const boolean flip = (mo->eflags & MFE_VERTICALFLIP); + const fixed_t m_dist = usedistance ? R_PointToDist(mo->x, mo->y) : 0; + const fixed_t rolldist = cv_sloperolldist.value * mapobjectscale; - // admittedly this is a very hacky way to do the pitch and roll easing + fixed_t tempz = mo->standingslope->normal.z; + fixed_t tempy = mo->standingslope->normal.y; + fixed_t tempx = mo->standingslope->normal.x; + fixed_t tempangle = -(R_PointToAngle2(0, 0, FixedSqrt(FixedMul(tempy, tempy) + FixedMul(tempz, tempz)), tempx)); - // pitch - if ((!usedistance) || (m_dist <= (rolldist))) - { - an = (INT32)((angle_t)tempangle - mo->pitch_sprite) / SLOPEROLL_DIV; + // admittedly this is a very hacky way to do the pitch and roll easing - mo->pitch_sprite = an ? mo->pitch_sprite + an : (angle_t)tempangle; - } - else - mo->pitch_sprite = FixedAngle(0); + // pitch + if (!usedistance || (m_dist <= (rolldist))) + { + an = (INT32)((angle_t)tempangle - mo->pitch_sprite) / SLOPEROLL_DIV; - mo->slopepitch = flip ? InvAngle(mo->pitch_sprite) : mo->pitch_sprite; + mo->pitch_sprite = an ? mo->pitch_sprite + an : (angle_t)tempangle; + } + else + mo->pitch_sprite = FixedAngle(0); - // roll - tempangle = (R_PointToAngle2(0, 0, tempz, tempy)); + mo->slopepitch = flip ? InvAngle(mo->pitch_sprite) : mo->pitch_sprite; - if ((!usedistance) || (m_dist <= (rolldist))) - { - an = (INT32)((angle_t)tempangle - mo->roll_sprite) / SLOPEROLL_DIV; + // roll + tempangle = (R_PointToAngle2(0, 0, tempz, tempy)); - mo->roll_sprite = an ? mo->roll_sprite + an : (angle_t)tempangle; - } - else - mo->roll_sprite = FixedAngle(0); + if (!usedistance || (m_dist <= (rolldist))) + { + an = (INT32)((angle_t)tempangle - mo->roll_sprite) / SLOPEROLL_DIV; - mo->sloperoll = flip ? InvAngle(mo->roll_sprite) : mo->roll_sprite; - } - else if (P_IsObjectOnGround(mo)) - { - mo->sloperoll = FixedAngle(0); - mo->slopepitch = FixedAngle(0); - } + mo->roll_sprite = an ? mo->roll_sprite + an : (angle_t)tempangle; + } + else + mo->roll_sprite = FixedAngle(0); + + mo->sloperoll = flip ? InvAngle(mo->roll_sprite) : mo->roll_sprite; + } + else if (P_IsObjectOnGround(mo)) + { + mo->sloperoll = FixedAngle(0); + mo->slopepitch = FixedAngle(0); + } } void K_SpawnBoostTrail(player_t *player) @@ -3411,7 +3424,7 @@ void K_SpawnBoostTrail(player_t *player) flame->momx = 8; // since you have to be on the ground for sneaker trails, this should be fine(?) - if (cv_sparkroll.value == 1) + if (cv_sparkroll.value) { flame->slopepitch = player->mo->slopepitch; flame->sloperoll = player->mo->sloperoll; @@ -3603,18 +3616,7 @@ static mobj_t *K_ThrowKartItem(player_t *player, boolean missile, mobjtype_t map } else { - switch (gamespeed) - { - case 0: - PROJSPEED = 68*mapobjectscale; // Avg Speed is 34 - break; - case 2: - PROJSPEED = 96*mapobjectscale; // Avg Speed is 48 - break; - default: - PROJSPEED = 82*mapobjectscale; // Avg Speed is 41 - break; - } + PROJSPEED = K_GetProjectileSpeed(); } if (altthrow) @@ -3842,18 +3844,7 @@ void K_PuntMine(mobj_t *thismine, mobj_t *punter) if (!mine || P_MobjWasRemoved(mine)) return; - switch (gamespeed) - { - case 0: - spd = 68*mapobjectscale; // Avg Speed is 34 - break; - case 2: - spd = 96*mapobjectscale; // Avg Speed is 48 - break; - default: - spd = 82*mapobjectscale; // Avg Speed is 41 - break; - } + spd = K_GetProjectileSpeed(); mine->flags |= MF_NOCLIPTHING; @@ -4000,20 +3991,7 @@ static void K_DoHyudoroSteal(player_t *player) void K_DoSneaker(player_t *player, INT32 type) { - fixed_t intendedboost; - - switch (gamespeed) - { - case 0: - intendedboost = 53740+768; - break; - case 2: - intendedboost = 17294+768; - break; - default: - intendedboost = 32768; - break; - } + const fixed_t intendedboost = K_GetSneakerBoostSpeed(); if (!player->kartstuff[k_floorboost] || player->kartstuff[k_floorboost] == 3) { @@ -4460,7 +4438,6 @@ void K_RepairOrbitChain(mobj_t *orbit) if (orbit->target && orbit->target->player) { player_t *player = orbit->target->player; - INT32 num = 0; mobj_t *cur = orbit->target->hnext; @@ -5361,7 +5338,7 @@ void K_KartPlayerThink(player_t *player, ticcmd_t *cmd) // Plays the music during and after the starting countdown. if (P_IsLocalPlayer(player)) - S_StartMapMusic(false); + S_StartMapMusic(); } void K_KartPlayerAfterThink(player_t *player) @@ -5689,7 +5666,6 @@ static void K_KartDrift(player_t *player, boolean onground) } } - // Stop drifting if (player->kartstuff[k_spinouttimer] > 0 || player->speed < minspeed) { @@ -5698,7 +5674,6 @@ static void K_KartDrift(player_t *player, boolean onground) if (!player->sliproll) { - player->sliptidemem = 0; player->sliproll = 0; } @@ -5721,8 +5696,6 @@ static void K_KartDrift(player_t *player, boolean onground) if (player->sliproll < (32*ANG1)) player->sliproll += (4*ANG1); - - player->sliptidemem = player->kartstuff[k_aizdriftstrat]; } if (player->kartstuff[k_drift] @@ -6070,10 +6043,12 @@ void K_MoveKartPlayer(player_t *player, boolean onground) P_SetScale(overlay, player->mo->scale); } player->kartstuff[k_invincibilitytimer] = itemtime+(2*TICRATE); // 10 seconds + if (P_IsLocalPlayer(player) && cv_supermusic.value == 1 && cv_birdmusic.value) S_ChangeMusicSpecial("kinvnc"); else S_StartSound(player->mo, (cv_kartinvinsfx.value ? sfx_alarmi : sfx_kinvnc)); + P_RestoreMusic(player); K_PlayPowerGloatSound(player->mo); player->kartstuff[k_itemamount]--; @@ -6490,7 +6465,7 @@ void K_MoveKartPlayer(player_t *player, boolean onground) K_KartDrift(player, onground); - if ((!player->kartstuff[k_aizdriftstrat])||(!P_IsObjectOnGround(player->mo))||(player->kartstuff[k_drift])) + if ((!player->kartstuff[k_aizdriftstrat]) || (!P_IsObjectOnGround(player->mo)) || (player->kartstuff[k_drift])) { if (player->sliproll && (player->sliproll > 0)) player->sliproll -= (4*ANG1); @@ -6504,14 +6479,9 @@ void K_MoveKartPlayer(player_t *player, boolean onground) player->mo->spriteyscale = player->mo->realyscale; } - boolean usedist = false; - - if (cv_sloperolldist.value > 0) - usedist = true; - if ((cv_spriteroll.value) && (cv_sloperoll.value)) + if (cv_sloperoll.value && !player->mo->salty_jump) // seeing a character rotate mid-hop looks really janky { - if ((!player->mo->salty_jump)) // seeing a character rotate mid-hop looks really janky - K_RollMobjBySlopes(player->mo, usedist); + K_RollMobjBySlopes(player->mo, (cv_sloperolldist.value && !splitscreen)); } else { @@ -6519,7 +6489,6 @@ void K_MoveKartPlayer(player_t *player, boolean onground) player->mo->slopepitch = FixedAngle(0); } - // Quick Turning // You can't turn your kart when you're not moving. // So now it's time to burn some rubber! @@ -7111,7 +7080,7 @@ void K_LoadKartHUDGraphics(void) kp_karmasticker = W_CachePatchName("K_STKARM", PU_HUDGFX); kp_splitkarmabomb = W_CachePatchName("K_SPTKRM", PU_HUDGFX); kp_timeoutsticker = W_CachePatchName("K_STTOUT", PU_HUDGFX); - + if (xtra_speedo) // snowy speedometer { skp_smallsticker = W_CachePatchName("SP_SMSTC", PU_HUDGFX); @@ -7126,8 +7095,8 @@ void K_LoadKartHUDGraphics(void) { skp_smallsticker3 = W_CachePatchName("SP_SM3TC", PU_HUDGFX); } - - if (achi_speedo) + + if (achi_speedo) { skp_smallstickerachi = W_CachePatchName("SP_AMSTC", PU_HUDGFX); skp_speedpatchesachi[0] = W_CachePatchName("K_TRNULL", PU_HUDGFX); // lolxd @@ -7137,7 +7106,8 @@ void K_LoadKartHUDGraphics(void) skp_speedpatchesachi[4] = W_CachePatchName("SP_APERC", PU_HUDGFX); } - if (big_lap){ + if (big_lap) + { kp_lapstickerbig = W_CachePatchName("K_STLAPB", PU_HUDGFX); kp_lapstickerbig2 = W_CachePatchName("K_STLA2B", PU_HUDGFX); } @@ -7159,8 +7129,8 @@ void K_LoadKartHUDGraphics(void) kp_itembgclr[3] = W_CachePatchName("K_ISBCD", PU_HUDGFX); kp_itemmulstickerclr[1] = W_CachePatchName("K_ISMULC", PU_HUDGFX); kp_itemmulstickerclr[0] = W_CachePatchName("K_ITMULC", PU_HUDGFX); - - if (big_lap_color){ + + if (big_lap_color){ kp_lapstickerbigclr = W_CachePatchName("K_SCLAPB", PU_HUDGFX); kp_lapstickerbig2clr = W_CachePatchName("K_SCLA2B", PU_HUDGFX); } @@ -7170,8 +7140,8 @@ void K_LoadKartHUDGraphics(void) if (xtra_speedo3 && xtra_speedo_clr3) // 80x11 patch scaled to size skp_smallstickerclr3 = W_CachePatchName("SC_SM3TC", PU_HUDGFX); - - if (achi_speedo && achi_speedo_clr) + + if (achi_speedo && achi_speedo_clr) { skp_smallstickerachiclr = W_CachePatchName("SC_AMSTC", PU_HUDGFX); skp_speedpatchesachiclr[0] = W_CachePatchName("K_TRNULL", PU_HUDGFX); // lolxd @@ -7202,14 +7172,14 @@ void K_LoadKartHUDGraphics(void) // Nametags if (nametaggfx) { - nametagpic = W_CachePatchName("NTLINE", PU_HUDGFX); nametagline = W_CachePatchName("NTLINEV", PU_HUDGFX); nametagspeed = W_CachePatchName("NTSP", PU_HUDGFX); nametagweight = W_CachePatchName("NTWH", PU_HUDGFX); } - - if (driftgaugegfx){ + + if (driftgaugegfx) + { driftgauge = W_CachePatchName("K_DGAU", PU_HUDGFX); driftgaugecolor = W_CachePatchName("K_DCAU", PU_HUDGFX); driftgaugesmall = W_CachePatchName("K_DGSU", PU_HUDGFX); @@ -7775,7 +7745,7 @@ static void K_drawKartStats(void) flags = V_SNAPTOBOTTOM|V_SNAPTOLEFT; UINT8 splitnum = 0; - + for (; splitnum < MAXSPLITSCREENPLAYERS; ++splitnum) { if (stplyr == &players[displayplayers[splitnum]]) @@ -7784,7 +7754,7 @@ static void K_drawKartStats(void) if (!LUA_HudEnabled(hud_statdisplay)) return; - + //Internal offset for speedometer if (cv_kartspeedometer.value) { @@ -8195,13 +8165,13 @@ void K_drawKartTimestamp(tic_t drawtime, INT32 TX, INT32 TY, INT16 emblemmap, UI } } - if (!K_UseColorHud()) - V_DrawScaledPatch(TX, TY, splitflags, ((mode == 2) ? kp_lapstickerwide : kp_timestickerwide)); - else //Colourized hud + if (K_UseColorHud()) // Colourized hud { UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); V_DrawMappedPatch(TX, TY, splitflags, ((mode == 2) ? kp_lapstickerwideclr : kp_timestickerwideclr), colormap); } + else + V_DrawScaledPatch(TX, TY, splitflags, ((mode == 2) ? kp_lapstickerwide : kp_timestickerwide)); TX += 33; @@ -8348,7 +8318,7 @@ static void K_DrawKartPositionNum(INT32 num) scale *= 2; overtake = true; // this is used for splitscreen stuff in conjunction with flipdraw. } - + if (splitscreen || (cv_showinput.value && !splitscreen)) scale /= 2; @@ -8640,7 +8610,7 @@ void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, I p = &players[tab[i].num]; if (cv_highresportrait.value) V_DrawSmallMappedPatch(x, y-4, 0, R_GetSkinFaceWant(p), colormap); - else + else V_DrawMappedPatch(x, y-4, 0, R_GetSkinFaceRank(p), colormap); } /*if (G_BattleGametype() && players[tab[i].num].kartstuff[k_bumper] > 0) -- not enough space for this @@ -8704,12 +8674,9 @@ void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, I } } -static boolean K_BigLapSticker(void) +static boolean K_BigLap(void) { - if (K_UseColorHud()) - return ((cv_numlaps.value > 9) && (big_lap_color) && (cv_biglaps.value) && (!stplyr->exiting)); - else - return ((cv_numlaps.value > 9) && (big_lap) && (cv_biglaps.value) && (!stplyr->exiting)); + return (cv_biglaps.value && (cv_numlaps.value > 9) && (K_UseColorHud() ? big_lap_color : big_lap) && (!stplyr->exiting)); } static void K_drawKartLaps(void) @@ -8748,20 +8715,16 @@ static void K_drawKartLaps(void) } else { - if (!K_UseColorHud()) - { - if (K_BigLapSticker()) - V_DrawScaledPatch(fx, fy, V_HUDTRANS|splitflags, ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2 : kp_lapstickerbig)); - else - V_DrawScaledPatch(fx, fy, V_HUDTRANS|splitflags, kp_lapsticker); - } - else //Colourized hud + if (K_UseColorHud()) // Colourized hud { UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - if (K_BigLapSticker()) - V_DrawMappedPatch(fx, fy, V_HUDTRANS|splitflags, ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2clr : kp_lapstickerbigclr), colormap); - else - V_DrawMappedPatch(fx, fy, V_HUDTRANS|splitflags, kp_lapstickerclr, colormap); + patch_t *biglapclr = (K_BigLap() ? ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2clr : kp_lapstickerbigclr) : kp_lapstickerclr); + V_DrawMappedPatch(fx, fy, V_HUDTRANS|splitflags, biglapclr, colormap); + } + else + { + patch_t *biglap = (K_BigLap() ? ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2 : kp_lapstickerbig) : kp_lapsticker); + V_DrawScaledPatch(fx, fy, V_HUDTRANS|splitflags, biglap); } if (stplyr->exiting) @@ -8782,7 +8745,7 @@ static void K_drawKartSpeedometer(void) //KartZ speedo fixed_t fuspeed = 0; INT32 spdpatch = 0; - + INT32 speedtype = 0; INT32 splitflags = K_calcSplitFlags(V_SNAPTOBOTTOM|V_SNAPTOLEFT); @@ -8810,7 +8773,7 @@ static void K_drawKartSpeedometer(void) } // man. - if ((cv_newspeedometer.value == 1) || (cv_newspeedometer.value == 2 && !xtra_speedo) || (cv_newspeedometer.value == 3 && !achi_speedo) || (cv_newspeedometer.value == 4 && !kartzspeedo) || (cv_newspeedometer.value == 5 && !xtra_speedo3)) + if ((cv_newspeedometer.value == 1) || (cv_newspeedometer.value == 2 && !xtra_speedo) || (cv_newspeedometer.value == 3 && !achi_speedo) || (cv_newspeedometer.value == 4 && !kartzspeedo) || (cv_newspeedometer.value == 5 && !xtra_speedo3)) { switch (speedtype) { case 1: @@ -8859,34 +8822,34 @@ static void K_drawKartSpeedometer(void) V_DrawScaledPatch(SPDM_X + 1, SPDM_Y + 4, (V_HUDTRANS|splitflags), (skp_smallstickerachi)); V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed, 3, NULL); V_DrawScaledPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatchesachi[cv_kartspeedometer.value]); - } - } + } + } else if (cv_newspeedometer.value == 5 && xtra_speedo3) // why bother if we dont? { if (K_UseColorHud() && xtra_speedo_clr3) //Colourized hud { UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); V_DrawStretchyFixedPatch((SPDM_X-1)<speed, mapobjectscale)/FRACUNIT; - + #define NUM_INTERVALS 22 const int speedIntervals[NUM_INTERVALS] = {2, 5, 7, 10, 12, 15, 17, 20, 22, 25, 27, 30, 32, 35, 37, 40, 42, 45, 47, 50, 52, 55}; - for (int i = 0; i < NUM_INTERVALS; ++i) + for (int i = 0; i < NUM_INTERVALS; ++i) { - if (fuspeed < speedIntervals[i]) + if (fuspeed < speedIntervals[i]) { spdpatch = i; break; @@ -8979,28 +8942,21 @@ static void K_drawKartBumpersOrKarma(void) static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *target, fixed_t hofs, boolean dontclip) { fixed_t distfact; - fixed_t dist; - fixed_t xres; - fixed_t yres; - fixed_t fov; - fixed_t fovratio; fixed_t offset; - boolean srcflip; - boolean targflip; fixed_t y; fixed_t x; // this should never happen but its also kart so ¯\_(ツ)_/¯ - if (!player || !target) + if (!player || P_MobjWasRemoved(target)) return false; - xres = vid.width<<(FRACBITS-1); - yres = vid.height<<(FRACBITS-1); - fov = FixedDiv(xres, FINETANGENT(((FixedAngle(cv_fov.value/2)+ANGLE_90)>>ANGLETOFINESHIFT) & 4095)); + const fixed_t xres = vid.width<<(FRACBITS-1); + const fixed_t yres = vid.height<<(FRACBITS-1); + const fixed_t fov = FixedDiv(xres, FINETANGENT(((FixedAngle(cv_fov.value/2)+ANGLE_90)>>ANGLETOFINESHIFT) & 4095)); - fixed_t targx = lerp(target->old_x, target->x); - fixed_t targy = lerp(target->old_y, target->y); - fixed_t targz = lerp(target->old_z, target->z); + const fixed_t targx = lerp(target->old_x, target->x); + const fixed_t targy = lerp(target->old_y, target->y); + const fixed_t targz = lerp(target->old_z, target->z); // X coordinate // get difference between camangle and angle towards target @@ -9015,8 +8971,8 @@ static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *targe return false; // flipping - targflip = target->eflags & MFE_VERTICALFLIP; - srcflip = player->pflags & PF_FLIPCAM && player->mo->eflags & MFE_VERTICALFLIP; + const boolean targflip = target->eflags & MFE_VERTICALFLIP; + const boolean srcflip = player->pflags & PF_FLIPCAM && player->mo->eflags & MFE_VERTICALFLIP; // Y coordinate // getting the angle difference here is a bit more involved... @@ -9026,11 +8982,11 @@ static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *targe y = y - (targflip ? -hofs : hofs); // then get the distance between camera and target - dist = R_PointToDist(targx, targy); + const fixed_t dist = R_PointToDist(targx, targy); #ifdef HWRENDER // NOW we can get the angle differnce - if (rendermode == render_opengl && cv_grshearing.value == 0) + if (rendermode == render_opengl && cv_glshearing.value == 0) { angle_t yang = R_PointToAngle2(0, 0, dist, y); // not perspective x = FixedMul(x, FINECOSINE((yang>>ANGLETOFINESHIFT) & FINEMASK)); // perspective @@ -9048,7 +9004,7 @@ static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *targe else #endif { - fovratio = FixedDiv(90*FRACUNIT, 180*FRACUNIT - FixedMul(cv_fov.value, 4*FRACUNIT/3)-FRACUNIT*-30); + const fixed_t fovratio = FixedDiv(90*FRACUNIT, 180*FRACUNIT - FixedMul(cv_fov.value, 4*FRACUNIT/3)-FRACUNIT*-30); y = FixedDiv(y, FixedMul(dist, distfact)); if (srcflip) @@ -9076,9 +9032,9 @@ static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *targe // project the angle to get our final X coordinate x = FixedMul(FINETANGENT(((x+ANGLE_90)>>ANGLETOFINESHIFT) & 4095), fov); if (splitscreen == 1) // divide by 320/200 (1.6) on 2P splitscreen - x = (x/2) + (x/8); + x = (x/2) + (x/8); x = x + xres; - + // now clip in screen-space if (!dontclip && (x < 0 || x > xres*2 || y < 0 || y > yres*2)) return false; @@ -9118,33 +9074,27 @@ static void K_drawNameTags(void) fixed_t tagwidth; fixed_t tagwidthsmall; fixed_t namex,namey; - int dup = 0; - int tagcolor = 0; - int vflags = 0; - int flipped = 0; int tagsdisplayed = 0; char *tag; patch_t *icon; - INT32 hudtransflag = V_LocalTransFlag(); - boolean flipcam; + const INT32 hudtransflag = V_LocalTransFlag(); - if (!stplyr->mo || (stplyr->spectator && !cv_shownametagspectator.value) || (stplyr->exiting && !cv_shownametagfinish.value)) + if (P_MobjWasRemoved(stplyr->mo) || (stplyr->spectator && !cv_shownametagspectator.value) || (stplyr->exiting && !cv_shownametagfinish.value)) return; // True if currently viewed player is flipped and has flipcam on - flipcam = (stplyr->pflags & PF_FLIPCAM) && (stplyr->mo->eflags & MFE_VERTICALFLIP); + const boolean flipcam = ((stplyr->pflags & PF_FLIPCAM) && (stplyr->mo->eflags & MFE_VERTICALFLIP)); for (i = 0; i < MAXPLAYERS; i++) { - UINT8 *cm; fixed_t distance = 0; - fixed_t maxdistance = (10*cv_nametagdist.value)* mapobjectscale; - flipped = 0; + const fixed_t maxdistance = ((10*cv_nametagdist.value)* mapobjectscale); + boolean flipped = 0; fixed_t z; - + if (i > PLAYERSMASK) continue; - if (!players[i].mo || P_MobjWasRemoved(players[i].mo) || players[i].spectator || !playeringame[i]) + if (P_MobjWasRemoved(players[i].mo) || players[i].spectator || !playeringame[i]) continue; if (i == displayplayers[stplyrnum] && !cv_showownnametag.value && !(leveltime < 130)) continue; @@ -9152,10 +9102,11 @@ static void K_drawNameTags(void) continue; if (players[i].kartstuff[k_hyudorotimer]) // player is invisible continue; - distance = R_PointToDist(players[i].mo->x, players[i].mo->y); + if (maxdistance) + distance = R_PointToDist(players[i].mo->x, players[i].mo->y); if (distance > maxdistance) continue; - if (!P_CheckSight(stplyr->mo, players[i].mo)) + if (!P_CheckSightFast(stplyr->mo, players[i].mo)) continue; switch (cv_nametagtrans.value) @@ -9180,7 +9131,7 @@ static void K_drawNameTags(void) trans = V_40TRANS; else if (distance > (maxdistance*3/5)) trans = V_20TRANS; - else + else trans = 0; break; case 3: @@ -9193,7 +9144,7 @@ static void K_drawNameTags(void) break; } - dup = vid.dupx; + const INT32 dup = vid.dupx; // If flipcam is on, other player is flipped relative to us when we have different // verticalflip flag value. Otherwise, they are simply flipped when verticalflip flag says @@ -9223,9 +9174,9 @@ static void K_drawNameTags(void) tag = va("%s%s ", HU_SkinColorToConsoleColor(players[i].mo->color),player_names[i]); icon = R_GetSkinFaceMini(players[i].mo->player); - cm = R_GetTranslationColormap(players[i].skin, players[i].mo->color, GTC_CACHE); - tagcolor = colortranslations[players[i].mo->color][7]; - vflags = trans | V_NOSCALESTART; + const UINT8 *cm = R_GetTranslationColormap(players[i].skin, players[i].mo->color, GTC_CACHE); + const INT32 tagcolor = colortranslations[players[i].mo->color][7]; + const INT32 vflags = trans | V_NOSCALESTART; tagwidth = cv_smallnametags.value ? dup*V_SmallStringWidth(player_names[i], V_ALLOWLOWERCASE) : dup*V_ThinStringWidth(player_names[i], V_ALLOWLOWERCASE); tagwidthsmall = cv_smallnametags.value ? V_SmallStringWidth(player_names[i], V_ALLOWLOWERCASE) : V_ThinStringWidth(player_names[i], V_ALLOWLOWERCASE); @@ -9338,13 +9289,10 @@ static void K_drawNameTags(void) // Based on Driftgauge refactor by GenericHeroGuy ported from lua and expanded by NepDisk static void K_drawDriftGauge(void) { - INT32 driftval = K_GetKartDriftSparkValue(stplyr); - INT32 driftcharge = min(driftval*4, stplyr->kartstuff[k_driftcharge]); vector2_t pos = {0}; - fixed_t basex,basey; - INT32 drifttrans = 0; - INT32 hudtransflag = V_LocalTransFlag(); - int dup = vid.dupx; + fixed_t basex, basey; + const INT32 hudtransflag = V_LocalTransFlag(); + const int dup = vid.dupx; int i; UINT8 driftcolors[3][4] = { @@ -9366,7 +9314,7 @@ static void K_drawDriftGauge(void) if (demo.playback && demo.freecam) return; - if (!stplyr->mo || (!splitscreen && !camera->chase)) + if (P_MobjWasRemoved(stplyr->mo) || (!splitscreen && !camera->chase)) return; if (forceshowhud) @@ -9380,26 +9328,31 @@ skipcrap: if (!K_GetScreenCoords(&pos, stplyr, stplyr->mo, FixedMul(cv_driftgaugeofs.value, cv_driftgaugeofs.value > 0 ? stplyr->mo->scale : mapobjectscale), false)) return; - basex = pos.x>>FRACBITS; + const INT32 driftval = K_GetKartDriftSparkValue(stplyr); + const INT32 driftcharge = min(driftval*4, stplyr->kartstuff[k_driftcharge]); + + basex = pos.x>>FRACBITS; basey = pos.y>>FRACBITS; fixed_t barx; fixed_t bary; INT32 BAR_WIDTH; - if (cv_driftgaugetrans.value) - drifttrans = hudtransflag; - else - drifttrans = 0; + const INT32 drifttrans = ((cv_driftgaugetrans.value) ? hudtransflag : 0); switch (cv_driftgaugestyle.value) { case 1: case 2: case 3: - if (driftgaugegfx) + case 5: { - if (cv_driftgaugestyle.value == 1 || cv_driftgaugestyle.value == 3) + if (!driftgaugegfx) + break; + + const boolean usescaledpatch = (cv_driftgaugestyle.value == 5 && xtra_speedo3); + + if (cv_driftgaugestyle.value == 1 || cv_driftgaugestyle.value == 3 || usescaledpatch) { barx = basex - dup*23; BAR_WIDTH = dup*47; @@ -9412,17 +9365,31 @@ skipcrap: bary = basey - dup*2; - INT32 limit = driftval * (driftcharge >= driftval*2 ? 2 : 1); - INT32 width = ((driftcharge - (driftcharge >= driftval ? limit : 0)) * BAR_WIDTH) / limit; - INT32 level = min(driftcharge / driftval, 2); UINT8 *cmap; + const INT32 limit = driftval * (driftcharge >= driftval*2 ? 2 : 1); + const INT32 width = ((driftcharge - (driftcharge >= driftval ? limit : 0)) * BAR_WIDTH) / limit; + const INT32 level = min(driftcharge / driftval, 2); - if (!K_UseColorHud()) - V_DrawMappedPatch(cv_driftgaugestyle.value == 2 ? basex + dup*11 : basex, basey, V_NOSCALESTART|V_OFFSET|drifttrans, cv_driftgaugestyle.value == 2 ? driftgaugesmall : driftgauge, NULL); - else //Colourized hud + if (usescaledpatch) // i hate hud code i hate hud code i hate hud code i hate hud code i hate hud code..... { - UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); - V_DrawMappedPatch(cv_driftgaugestyle.value == 2 ? basex + dup*11 : basex, basey, V_NOSCALESTART|V_OFFSET|drifttrans, cv_driftgaugestyle.value == 2 ? driftgaugesmallcolor : driftgaugecolor, colormap); + if (K_UseColorHud() && xtra_speedo_clr3) // Colourized hud + { + UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE); + V_DrawStretchyFixedPatch((basex - dup*30)<= driftval*4) // rainbow sparks @@ -9434,7 +9401,7 @@ skipcrap: else // none/blue/red { cmap = R_GetTranslationColormap(TC_RAINBOW, driftskins[level],GTC_CACHE); - for (i = 0; i < 4; i++) + for (i = 0; i < 4; i++) { if (driftcharge >= driftval) V_DrawFill(barx, bary+dup*1+dup*i, BAR_WIDTH, dup, driftcolors[level-1][i] | V_NOSCALESTART|drifttrans); @@ -9454,7 +9421,7 @@ skipcrap: case 4: { UINT8 *cmap; - INT32 level = min(driftcharge / driftval, 2); + const INT32 level = min(driftcharge / driftval, 2); if (driftcharge >= driftval*4) cmap = R_GetTranslationColormap(TC_RAINBOW, 1 + leveltime % (MAXSKINCOLORS-1),GTC_CACHE); else @@ -9631,7 +9598,8 @@ static void K_drawKartMinimapHead(mobj_t *mo, INT32 x, INT32 y, INT32 flags) boolean skinlocal = mo->skinlocal; fixed_t amnumxpos, amnumypos; - INT32 amxpos, amypos; + INT32 amxpos, amypos, wntdamxpos, wntdamypos; + fixed_t scale = FRACUNIT; if (mo->skin) skin = ((skin_t*)(mo->localskin ? mo->localskin : mo->skin))-(skinlocal ? localskins : skins); @@ -9642,11 +9610,28 @@ static void K_drawKartMinimapHead(mobj_t *mo, INT32 x, INT32 y, INT32 flags) if (encoremode) amnumxpos = -amnumxpos; - amxpos = amnumxpos + ((x + (SHORT(minimapinfo.minimap_pic->width)-SHORT((skinlocal ? localfacemmapprefix : facemmapprefix)[skin]->width))/2)<height)-SHORT((skinlocal ? localfacemmapprefix : facemmapprefix)[skin]->height))/2)<width)-SHORT((skinlocal ? localfacemmapprefix : facemmapprefix)[skin]->width)) / 2)<height)-SHORT((skinlocal ? localfacemmapprefix : facemmapprefix)[skin]->height)) / 2)<player && !(modeattacking || gamestate == GS_TIMEATTACK)) + { + const char *player_name = va("%c%s", (mo->color) ? V_GetSkincolorChar(mo->color) : 0, player_names[mo->player - players]); + V_DrawCenteredSmallStringAtFixed(amxpos + (4*FRACUNIT), amypos - (3*FRACUNIT), V_ALLOWLOWERCASE|flags, player_name); + } + + // thx wanted reticle for having weird offsets very cool + wntdamxpos = cv_minihead.value ? amxpos + (1<width) / 4)<height) / 4)<color) // 'default' color - V_DrawSciencePatch(amxpos, amypos, flags, ( (skinlocal) ? localfacemmapprefix : facemmapprefix )[skin], FRACUNIT); + V_DrawSciencePatch(amxpos, amypos, flags, ((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin], scale); else { UINT8 *colormap; @@ -9654,25 +9639,14 @@ static void K_drawKartMinimapHead(mobj_t *mo, INT32 x, INT32 y, INT32 flags) colormap = R_GetTranslationColormap(TC_RAINBOW, mo->color, GTC_CACHE); else colormap = R_GetLocalTranslationColormap(mo->skin, mo->localskin, mo->color, GTC_CACHE, skinlocal); - - if (cv_minihead.value) - V_DrawFixedPatch(amxpos + (2*FRACUNIT), amypos + (2*FRACUNIT), FRACUNIT/2, flags, ((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin], colormap); - else - V_DrawFixedPatch(amxpos, amypos, FRACUNIT, flags, ((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin], colormap); - - if (cv_showminimapnames.value && !(modeattacking || gamestate == GS_TIMEATTACK)) - { - const char *player_name = va("%c%s", V_GetSkincolorChar(mo->color), player_names[mo->player - players]); - V_DrawCenteredSmallStringAtFixed(amxpos + (4*FRACUNIT), amypos - (3*FRACUNIT), V_ALLOWLOWERCASE|flags, player_name); - } + + V_DrawFixedPatch(amxpos, amypos, scale, flags, ((skinlocal) ? localfacemmapprefix : facemmapprefix)[skin], colormap); + if (mo->player && ((G_RaceGametype() && mo->player->kartstuff[k_position] == spbplace) || (G_BattleGametype() && K_IsPlayerWanted(mo->player)))) { - if (cv_minihead.value) - V_DrawFixedPatch(amxpos, amypos, FRACUNIT/2, flags, kp_wantedreticle, NULL); - else - V_DrawFixedPatch(amxpos - (4<kartstuff[k_comebacktimer]/TICRATE)); else { - if (!K_UseColorHud()) - V_DrawFixedPatch(x<kartstuff[k_comebacktimer]/TICRATE)); } @@ -10505,7 +10480,7 @@ void K_drawKartHUD(void) // Draw the item window if (LUA_HudEnabled(hud_item) && !freecam) - K_drawKartItem(); + K_drawKartItem(); if (cv_driftgauge.value && !modeattacking) { diff --git a/src/lua_baselib.c b/src/lua_baselib.c index 1e60863ef..6bca10cbe 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -1109,6 +1109,18 @@ static int lib_pCheckSight(lua_State *L) return 1; } +// DONT USE THIS FOR ANYTHING GAMEPLAY, THIS WILL DESYNCH! +static int lib_pCheckSightFast(lua_State *L) +{ + mobj_t *t1 = *((mobj_t **)luaL_checkudata(L, 1, META_MOBJ)); + mobj_t *t2 = *((mobj_t **)luaL_checkudata(L, 2, META_MOBJ)); + //HUDSAFE? + if (!t1 || !t2) + return LUA_ErrInvalid(L, "mobj_t"); + lua_pushboolean(L, P_CheckSightFast(t1, t2)); + return 1; +} + static int lib_pCheckHoopPosition(lua_State *L) { mobj_t *hoopthing = *((mobj_t **)luaL_checkudata(L, 1, META_MOBJ)); @@ -3154,7 +3166,6 @@ static luaL_Reg lib[] = { {"P_LookForEnemies",lib_pLookForEnemies}, {"P_NukeEnemies",lib_pNukeEnemies}, {"P_HomingAttack",lib_pHomingAttack}, - //{"P_SuperReady",lib_pSuperReady}, {"P_Telekinesis",lib_pTelekinesis}, // p_map @@ -3167,6 +3178,7 @@ static luaL_Reg lib[] = { {"P_SlideMove",lib_pSlideMove}, {"P_BounceMove",lib_pBounceMove}, {"P_CheckSight", lib_pCheckSight}, + {"P_CheckSightFast", lib_pCheckSightFast}, {"P_CheckHoopPosition",lib_pCheckHoopPosition}, {"P_RadiusAttack",lib_pRadiusAttack}, {"P_FloorzAtPos",lib_pFloorzAtPos}, diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index f2fb03dc6..4c29ee317 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -169,7 +169,7 @@ void COM_Lua_f(void) for (i = 0; i < argc; i++) WRITESTRINGN(p, COM_Argv(i), 255); if (flags & 2) - SendNetXCmd2(XD_LUACMD, buf, p-buf); + SendNetXCmdForPlayer(1, XD_LUACMD, buf, p-buf); else SendNetXCmd(XD_LUACMD, buf, p-buf); free(buf); diff --git a/src/lua_hook.h b/src/lua_hook.h index 921336cd2..45237aa80 100644 --- a/src/lua_hook.h +++ b/src/lua_hook.h @@ -12,105 +12,129 @@ #include "r_defs.h" #include "d_player.h" +#include "s_sound.h" +#include "lua_hudlib_drawlist.h" -enum hook { - hook_NetVars=0, - hook_MapChange, - hook_MapLoad, - hook_PlayerJoin, - hook_PreThinkFrame, - hook_ThinkFrame, - hook_PostThinkFrame, - hook_MobjSpawn, - hook_MobjCollide, - hook_MobjMoveCollide, - hook_TouchSpecial, - hook_MobjFuse, - hook_MobjThinker, - hook_BossThinker, - hook_ShouldDamage, - hook_MobjDamage, - hook_MobjDeath, - hook_BossDeath, - hook_MobjRemoved, - hook_JumpSpecial, - hook_AbilitySpecial, - hook_SpinSpecial, - hook_JumpSpinSpecial, - hook_BotTiccmd, - hook_BotAI, - hook_LinedefExecute, - hook_PlayerMsg, - hook_HurtMsg, - hook_PlayerSpawn, - hook_PlayerQuit, - hook_PlayerThink, - hook_MusicChange, - hook_ShouldSpin, //SRB2KART - hook_ShouldExplode, //SRB2KART - hook_ShouldSquish, //SRB2KART - hook_PlayerSpin, //SRB2KART - hook_PlayerExplode, //SRB2KART - hook_PlayerSquish, //SRB2KART - hook_PlayerCmd, //SRB2KART - hook_IntermissionThinker, //SRB2KART - hook_VoteThinker, //SRB2KART - hook_ServerJoin, // SRB2KART - Saturn 32p +/* + * Do you know what an 'X Macro' is? Such a macro is called over each element of + * a list and expands the input. I use it for the hook lists because both an enum + * and array of hook names need to be kept in order. The X Macro handles this + * automatically. + */ - hook_MAX // last hook -}; -extern const char *const hookNames[]; +#define MOBJ_HOOK_LIST(X) \ + X (MobjSpawn),/* P_SpawnMobj */\ + X (MobjCollide),/* PIT_CheckThing */\ + X (MobjMoveCollide),/* tritto */\ + X (TouchSpecial),/* P_TouchSpecialThing */\ + X (MobjFuse),/* when mobj->fuse runs out */\ + X (MobjThinker),/* P_MobjThinker, P_SceneryThinker */\ + X (BossThinker),/* P_GenericBossThinker */\ + X (ShouldDamage),/* P_DamageMobj (Should mobj take damage?) */\ + X (MobjDamage),/* P_DamageMobj (Mobj actually takes damage!) */\ + X (MobjDeath),/* P_KillMobj */\ + X (BossDeath),/* A_BossDeath */\ + X (MobjRemoved),/* P_RemoveMobj */\ + X (HurtMsg),/* imhurttin */\ + +#define HOOK_LIST(X) \ + X (NetVars),/* add to archive table (netsave) */\ + X (MapChange),/* (before map load) */\ + X (MapLoad),\ + X (PlayerJoin),/* Got_AddPlayer */\ + X (PreThinkFrame)/* frame (before mobj and player thinkers) */,\ + X (ThinkFrame),/* frame (after mobj and player thinkers) */\ + X (PostThinkFrame),/* frame (at end of tick, ie after overlays, precipitation, specials) */\ + X (JumpSpecial),/* P_DoJumpStuff (Any-jumping) */\ + X (AbilitySpecial),/* P_DoJumpStuff (Double-jumping) */\ + X (SpinSpecial),/* P_DoSpinAbility (Spin button effect) */\ + X (JumpSpinSpecial),/* P_DoJumpStuff (Spin button effect (mid-air)) */\ + X (BotTiccmd),/* B_BuildTiccmd */\ + X (PlayerMsg),/* chat messages */\ + X (PlayerSpawn),/* G_SpawnPlayer */\ + X (PlayerQuit),\ + X (PlayerThink),/* P_PlayerThink */\ + X (MusicChange),\ + X (ShouldSpin),/*SRB2KART*/\ + X (ShouldExplode),/*SRB2KART*/\ + X (ShouldSquish),/*SRB2KART*/\ + X (PlayerSpin),/*SRB2KART*/\ + X (PlayerExplode),/*SRB2KART*/\ + X (PlayerSquish),/*SRB2KART*/\ + X (PlayerCmd),/* building the player's ticcmd struct (Ported from SRB2Kart) */\ + X (IntermissionThinker),/* Y_Ticker */\ + X (VoteThinker),/*SRB2KART*/\ + X (ServerJoin),/* SRB2KART - Saturn 32p*/\ + +#define STRING_HOOK_LIST(X) \ + X (BotAI),/* B_BuildTailsTiccmd by skin name */\ + X (LinedefExecute),\ + +#define HUD_HOOK_LIST(X) \ + X (game),\ + X (scores),/* emblems/multiplayer list */\ + X (intermission),\ + X (vote),\ + +/* + * I chose to access the hook enums through a macro as well. This could provide + * a hint to lookup the macro's definition instead of the enum's definition. + * (Since each enumeration is not defined in the source code, but by the list + * macros above, it is not greppable.) The name passed to the macro can also be + * grepped and found in the lists above. + */ + +#define MOBJ_HOOK(name) mobjhook_ ## name +#define HOOK(name) hook_ ## name +#define HUD_HOOK(name) hudhook_ ## name +#define STRING_HOOK(name) stringhook_ ## name + +#define ENUM(X) enum { X ## _LIST (X) X(MAX) } + +ENUM (MOBJ_HOOK); +ENUM (HOOK); +ENUM (HUD_HOOK); +ENUM (STRING_HOOK); + +#undef ENUM + +/* dead simple, LUA_HOOK(GameQuit) */ +#define LUA_HOOK(type) LUA_HookVoid(HOOK(type)) +#define LUA_HUDHOOK(type,drawlist) LUA_HookHUD(HUD_HOOK(type),(drawlist)) extern boolean hook_cmd_running; // This is used by PlayerCmd and lua_playerlib to prevent anything from being wirtten to player while we run PlayerCmd. extern int hook_defrosting; -void LUAh_MapChange(INT16 mapnumber); // Hook for map change (before load) -void LUAh_MapLoad(void); // Hook for map load -void LUAh_PlayerJoin(int playernum); // Hook for Got_AddPlayer -void LUAh_PreThinkFrame(void); // Hook for frame (before mobj and player thinkers) -void LUAh_ThinkFrame(void); // Hook for frame (after mobj and player thinkers) -void LUAh_PostThinkFrame(void); // Hook for frame (at end of tick, ie after overlays, precipitation, specials) -boolean LUAh_MobjHook(mobj_t *mo, enum hook which); -boolean LUAh_PlayerHook(player_t *plr, enum hook which); -#define LUAh_MobjSpawn(mo) LUAh_MobjHook(mo, hook_MobjSpawn) // Hook for P_SpawnMobj by mobj type -UINT8 LUAh_MobjCollideHook(mobj_t *thing1, mobj_t *thing2, enum hook which); -#define LUAh_MobjCollide(thing1, thing2) LUAh_MobjCollideHook(thing1, thing2, hook_MobjCollide) // Hook for PIT_CheckThing by (thing) mobj type -#define LUAh_MobjMoveCollide(thing1, thing2) LUAh_MobjCollideHook(thing1, thing2, hook_MobjMoveCollide) // Hook for PIT_CheckThing by (tmthing) mobj type -boolean LUAh_TouchSpecial(mobj_t *special, mobj_t *toucher); // Hook for P_TouchSpecialThing by mobj type -#define LUAh_MobjFuse(mo) LUAh_MobjHook(mo, hook_MobjFuse) // Hook for mobj->fuse == 0 by mobj type -boolean LUAh_MobjThinker(mobj_t *mo); // Hook for P_MobjThinker or P_SceneryThinker by mobj type -#define LUAh_BossThinker(mo) LUAh_MobjHook(mo, hook_BossThinker) // Hook for P_GenericBossThinker by mobj type -UINT8 LUAh_ShouldDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage); // Hook for P_DamageMobj by mobj type (Should mobj take damage?) -boolean LUAh_MobjDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage); // Hook for P_DamageMobj by mobj type (Mobj actually takes damage!) -boolean LUAh_MobjDeath(mobj_t *target, mobj_t *inflictor, mobj_t *source); // Hook for P_KillMobj by mobj type -#define LUAh_BossDeath(mo) LUAh_MobjHook(mo, hook_BossDeath) // Hook for A_BossDeath by mobj type -#define LUAh_MobjRemoved(mo) LUAh_MobjHook(mo, hook_MobjRemoved) // Hook for P_RemoveMobj by mobj type -#define LUAh_JumpSpecial(player) LUAh_PlayerHook(player, hook_JumpSpecial) // Hook for P_DoJumpStuff (Any-jumping) -#define LUAh_AbilitySpecial(player) LUAh_PlayerHook(player, hook_AbilitySpecial) // Hook for P_DoJumpStuff (Double-jumping) -#define LUAh_SpinSpecial(player) LUAh_PlayerHook(player, hook_SpinSpecial) // Hook for P_DoSpinDash (Spin button effect) -#define LUAh_JumpSpinSpecial(player) LUAh_PlayerHook(player, hook_JumpSpinSpecial) // Hook for P_DoJumpStuff (Spin button effect (mid-air)) -boolean LUAh_BotTiccmd(player_t *bot, ticcmd_t *cmd); // Hook for B_BuildTiccmd -boolean LUAh_BotAI(mobj_t *sonic, mobj_t *tails, ticcmd_t *cmd); // Hook for B_BuildTailsTiccmd by skin name -boolean LUAh_LinedefExecute(line_t *line, mobj_t *mo, sector_t *sector); // Hook for linedef executors -boolean LUAh_PlayerMsg(int source, int target, int flags, char *msg, int mute); // Hook for chat messages -boolean LUAh_HurtMsg(player_t *player, mobj_t *inflictor, mobj_t *source); // Hook for hurt messages -#define LUAh_PlayerSpawn(player) LUAh_PlayerHook(player, hook_PlayerSpawn) // Hook for G_SpawnPlayer -void LUAh_PlayerQuit(player_t *plr, int reason); // Hook for player quitting -boolean LUAh_MusicChange(const char *oldname, char *newname, UINT16 *mflags, boolean *looping, - UINT32 *position, UINT32 *prefadems, UINT32 *fadeinms); // Hook for music changes +void LUA_HookVoid(int hook); +void LUA_HookHUD(int hook, huddrawlist_h drawlist); -UINT8 LUAh_ShouldSpin(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Should player be spun out? -UINT8 LUAh_ShouldExplode(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Should player be exploded? -UINT8 LUAh_ShouldSquish(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Should player be squished? +int LUA_HookMobj(mobj_t *, int hook); +int LUA_Hook2Mobj(mobj_t *, mobj_t *, int hook); +void LUA_HookInt(INT32 integer, int hook); +//void LUA_HookBool(boolean value, int hook); +int LUA_HookPlayer(player_t *, int hook); +int LUA_HookTiccmd(player_t *, ticcmd_t *, int hook); -boolean LUAh_PlayerSpin(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Hook for K_SpinPlayer. Allows Lua to execute code and/or overwrite its behavior. -boolean LUAh_PlayerExplode(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Hook for K_ExplodePlayer. Allows Lua to execute code and/or overwrite its behavior. -boolean LUAh_PlayerSquish(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Hook for K_SquishPlayer. Allows Lua to execute code and/or overwrite its behavior. +void LUA_HookPreThinkFrame(void); +void LUA_HookThinkFrame(void); +void LUA_HookPostThinkFrame(void); +int LUA_HookTouchSpecial(mobj_t *special, mobj_t *toucher); +int LUA_HookShouldDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage); +int LUA_HookMobjDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage); +int LUA_HookMobjDeath(mobj_t *target, mobj_t *inflictor, mobj_t *source); +int LUA_HookBotAI(mobj_t *sonic, mobj_t *tails, ticcmd_t *cmd); +void LUA_HookLinedefExecute(line_t *, mobj_t *, sector_t *); +int LUA_HookPlayerMsg(int source, int target, int flags, char *msg, int mute); +int LUA_HookHurtMsg(player_t *, mobj_t *inflictor, mobj_t *source); +int LUA_HookPlayerCanDamage(player_t *, mobj_t *); +void LUA_HookPlayerQuit(player_t *, int); +int LUA_HookPlayerCmd(player_t *, ticcmd_t *); +int LUA_HookMusicChange(const char *oldname, struct MusicChange *); -void LUAh_ServerJoin(void); // SRB2KART - Saturn 32p: called by client when joining a server, allows lua to load any sort of config file +int LUA_HookShouldSpin(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Should player be spun out? +int LUA_HookShouldExplode(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Should player be exploded? +int LUA_HookShouldSquish(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Should player be squished? -boolean LUAh_PlayerCmd(player_t *player, ticcmd_t *cmd); // Allows to write to player cmd before the game does anything with them. - -void LUAh_IntermissionThinker(void); // Hook for Y_Ticker -void LUAh_VoteThinker(void); // Hook for Y_VoteTicker -#define LUAh_PlayerThink(player) LUAh_PlayerHook(player, hook_PlayerThink) // Hook for P_PlayerThink +boolean LUA_HookPlayerSpin(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Hook for K_SpinPlayer. Allows Lua to execute code and/or overwrite its behavior. +boolean LUA_HookPlayerExplode(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Hook for K_ExplodePlayer. Allows Lua to execute code and/or overwrite its behavior. +boolean LUA_HookPlayerSquish(player_t *player, mobj_t *inflictor, mobj_t *source); // SRB2KART: Hook for K_SquishPlayer. Allows Lua to execute code and/or overwrite its behavior. diff --git a/src/lua_hooklib.c b/src/lua_hooklib.c index 442c12f88..9276e61aa 100644 --- a/src/lua_hooklib.c +++ b/src/lua_hooklib.c @@ -24,1951 +24,1097 @@ #include "lua_hook.h" #include "lua_hud.h" // hud_running errors -static UINT8 hooksAvailable[(hook_MAX/8)+1]; +/* ========================================================================= + ABSTRACTION + ========================================================================= */ -const char *const hookNames[hook_MAX+1] = { - "NetVars", - "MapChange", - "MapLoad", - "PlayerJoin", - "PreThinkFrame", - "ThinkFrame", - "PostThinkFrame", - "MobjSpawn", - "MobjCollide", - "MobjMoveCollide", - "TouchSpecial", - "MobjFuse", - "MobjThinker", - "BossThinker", - "ShouldDamage", - "MobjDamage", - "MobjDeath", - "BossDeath", - "MobjRemoved", - "JumpSpecial", - "AbilitySpecial", - "SpinSpecial", - "JumpSpinSpecial", - "BotTiccmd", - "BotAI", - "LinedefExecute", - "PlayerMsg", - "HurtMsg", - "PlayerSpawn", - "PlayerQuit", - "PlayerThink", - "MusicChange", - "ShouldSpin", - "ShouldExplode", - "ShouldSquish", - "PlayerSpin", - "PlayerExplode", - "PlayerSquish", - "PlayerCmd", - "IntermissionThinker", - "VoteThinker", - "ServerJoin", - NULL -}; +#define LIST(id, M) \ + static const char * const id [] = { M (TOSTR) NULL } -// Hook metadata -struct hook_s +LIST (mobjHookNames, MOBJ_HOOK_LIST); +LIST (hookNames, HOOK_LIST); +LIST (hudHookNames, HUD_HOOK_LIST); +LIST (stringHookNames, STRING_HOOK_LIST); + +#undef LIST + +typedef struct { + int numHooks; + int *ids; +} hook_t; + +typedef struct { + int numGeneric; + int ref; +} stringhook_t; + +static hook_t hookIds[HOOK(MAX)]; +static hook_t hudHookIds[HUD_HOOK(MAX)]; +static hook_t mobjHookIds[NUMMOBJTYPES][MOBJ_HOOK(MAX)]; + +// Lua tables are used to lookup string hook ids. +static stringhook_t stringHooks[STRING_HOOK(MAX)]; + +// This will be indexed by hook id, the value of which fetches the registry. +static int * hookRefs; +static int nextid; + +// After a hook errors once, don't print the error again. +static UINT8 * hooksErrored; + +static int errorRef; + +static boolean mobj_hook_available(int hook_type, mobjtype_t mobj_type) { - struct hook_s *next; - enum hook type; - UINT16 id; - union { - mobjtype_t mt; - char *skinname; - char *funcname; - } s; - boolean error; -}; -typedef struct hook_s* hook_p; + return + ( + mobjHookIds [MT_NULL] [hook_type].numHooks > 0 || + (mobj_type < NUMMOBJTYPES && mobjHookIds[mobj_type][hook_type].numHooks > 0) + ); +} -// For each mobj type, a linked list to its thinker and collision hooks. -// That way, we don't have to iterate through all the hooks. -// We could do that with all other mobj hooks, but it would probably just be -// a waste of memory since they are only called occasionally. Probably... -static hook_p mobjthinkerhooks[NUMMOBJTYPES]; -static hook_p mobjcollidehooks[NUMMOBJTYPES]; +static unsigned hook_in_list +( + const char * const name, + const char * const * const list +){ + unsigned type; -// For each mobj type, a linked list for other mobj hooks -static hook_p mobjhooks[NUMMOBJTYPES]; + for (type = 0; list[type] != NULL; ++type) + { + if (strcmp(name, list[type]) == 0) + break; + } -// A linked list for player hooks -static hook_p playerhooks; + return type; +} -// A linked list for linedef executor hooks -static hook_p linedefexecutorhooks; +static void get_table(lua_State *L) +{ + lua_pushvalue(L, -1); + lua_rawget(L, -3); -// For other hooks, a unique linked list -hook_p roothook; + if (lua_isnil(L, -1)) + { + lua_pop(L, 1); + lua_createtable(L, 1, 0); + lua_pushvalue(L, -2); + lua_pushvalue(L, -2); + lua_rawset(L, -5); + } + + lua_remove(L, -2); +} + +static void add_hook_to_table(lua_State *L, int n) +{ + lua_pushnumber(L, nextid); + lua_rawseti(L, -2, n); +} + +static void add_string_hook(lua_State *L, int type) +{ + stringhook_t * hook = &stringHooks[type]; + + char * string = NULL; + + switch (type) + { + case STRING_HOOK(BotAI): + if (lua_isstring(L, 3)) + { // lowercase copy + string = Z_StrDup(lua_tostring(L, 3)); + strlwr(string); + } + + /*hook.s.skinname = NULL; + if (lua_isstring(L, 2)) + { // lowercase copy + const char *s = lua_tostring(L, 2); + char *p = hook.s.skinname = ZZ_Alloc(strlen(s)+1); + do { + *p = tolower(*s); + ++p; + } while(*(++s)); + *p = 0; + }*/ + break; + + case STRING_HOOK(LinedefExecute): + string = Z_StrDup(luaL_checkstring(L, 3)); + strupr(string); + + /*{ // uppercase copy + const char *s = luaL_checkstring(L, 2); + char *p = hook.s.funcname = ZZ_Alloc(strlen(s)+1); + do { + *p = toupper(*s); + ++p; + } while(*(++s)); + *p = 0; + }*/ + break; + } + + if (hook->ref > 0) + lua_getref(L, hook->ref); + else + { + lua_newtable(L); + lua_pushvalue(L, -1); + hook->ref = luaL_ref(L, LUA_REGISTRYINDEX); + } + + if (string) + { + lua_pushstring(L, string); + get_table(L); + add_hook_to_table(L, 1 + lua_objlen(L, -1)); + } + else + add_hook_to_table(L, ++hook->numGeneric); +} + +static void add_hook(hook_t *map) +{ + Z_Realloc(map->ids, (map->numHooks + 1) * sizeof *map->ids, + PU_STATIC, &map->ids); + map->ids[map->numHooks++] = nextid; +} + +static void add_mobj_hook(lua_State *L, int hook_type) +{ + mobjtype_t mobj_type = luaL_optnumber(L, 3, MT_NULL); + + luaL_argcheck(L, mobj_type < NUMMOBJTYPES, 3, "invalid mobjtype_t"); + + add_hook(&mobjHookIds[mobj_type][hook_type]); +} + +static void add_hud_hook(lua_State *L, int idx) +{ + add_hook(&hudHookIds[luaL_checkoption(L, + idx, "game", hudHookNames)]); +} + +static void add_hook_ref(lua_State *L, int idx) +{ + if (!(nextid & 7)) + { + Z_Realloc(hooksErrored, + BIT_ARRAY_SIZE (nextid + 1) * sizeof *hooksErrored, + PU_STATIC, &hooksErrored); + hooksErrored[nextid >> 3] = 0; + } + + Z_Realloc(hookRefs, (nextid + 1) * sizeof *hookRefs, PU_STATIC, &hookRefs); + + // set the hook function in the registry. + lua_pushvalue(L, idx); + hookRefs[nextid++] = luaL_ref(L, LUA_REGISTRYINDEX); +} // Takes hook, function, and additional arguments (mobj type to act on, etc.) static int lib_addHook(lua_State *L) { - static struct hook_s hook = {NULL, 0, 0, {0}, false}; - static UINT32 nextid; - hook_p hookp, *lastp; - - hook.type = luaL_checkoption(L, 1, NULL, hookNames); - lua_remove(L, 1); - - luaL_checktype(L, 1, LUA_TFUNCTION); + const char * name; + unsigned type; if (hud_running) return luaL_error(L, "HUD rendering code should not call this function!"); - switch(hook.type) + name = luaL_checkstring(L, 1); + luaL_checktype(L, 2, LUA_TFUNCTION); + + /* this is a very special case */ + if (( type = hook_in_list(name, stringHookNames) ) < STRING_HOOK(MAX)) { - // Take a mobjtype enum which this hook is specifically for. - case hook_MobjSpawn: - case hook_MobjCollide: - case hook_MobjMoveCollide: - case hook_TouchSpecial: - case hook_MobjFuse: - case hook_MobjThinker: - case hook_BossThinker: - case hook_ShouldDamage: - case hook_MobjDamage: - case hook_MobjDeath: - case hook_BossDeath: - case hook_MobjRemoved: - case hook_HurtMsg: - hook.s.mt = MT_NULL; - if (lua_isnumber(L, 2)) - hook.s.mt = lua_tonumber(L, 2); - luaL_argcheck(L, hook.s.mt < NUMMOBJTYPES, 2, "invalid mobjtype_t"); - break; - case hook_BotAI: - hook.s.skinname = NULL; - if (lua_isstring(L, 2)) - { // lowercase copy - const char *s = lua_tostring(L, 2); - char *p = hook.s.skinname = ZZ_Alloc(strlen(s)+1); - do { - *p = tolower(*s); - ++p; - } while(*(++s)); - *p = 0; - } - break; - case hook_LinedefExecute: // Linedef executor functions - { // uppercase copy - const char *s = luaL_checkstring(L, 2); - char *p = hook.s.funcname = ZZ_Alloc(strlen(s)+1); - do { - *p = toupper(*s); - ++p; - } while(*(++s)); - *p = 0; - } - break; - case hook_ShouldSpin: - case hook_ShouldExplode: - case hook_ShouldSquish: - case hook_PlayerSpin: - case hook_PlayerExplode: - case hook_PlayerSquish: - default: - break; + add_string_hook(L, type); } - lua_settop(L, 1); // lua stack contains only the function now. - - hooksAvailable[hook.type/8] |= 1<<(hook.type%8); - - // set hook.id to the highest id + 1 - hook.id = nextid++; - - // Special cases for some hook types (see the comments above mobjthinkerhooks declaration) - switch(hook.type) + else if (( type = hook_in_list(name, mobjHookNames) ) < MOBJ_HOOK(MAX)) { - case hook_MobjThinker: - lastp = &mobjthinkerhooks[hook.s.mt]; - break; - case hook_MobjCollide: - case hook_MobjMoveCollide: - lastp = &mobjcollidehooks[hook.s.mt]; - break; - case hook_MobjSpawn: - case hook_TouchSpecial: - case hook_MobjFuse: - case hook_BossThinker: - case hook_ShouldDamage: - case hook_MobjDamage: - case hook_MobjDeath: - case hook_BossDeath: - case hook_MobjRemoved: - lastp = &mobjhooks[hook.s.mt]; - break; - case hook_JumpSpecial: - case hook_AbilitySpecial: - case hook_SpinSpecial: - case hook_JumpSpinSpecial: - case hook_PlayerSpawn: - case hook_PlayerThink: - lastp = &playerhooks; - break; - case hook_LinedefExecute: - lastp = &linedefexecutorhooks; - break; - case hook_ShouldSpin: - case hook_ShouldExplode: - case hook_ShouldSquish: - case hook_PlayerSpin: - case hook_PlayerExplode: - case hook_PlayerSquish: - case hook_ServerJoin: - default: - lastp = &roothook; - break; + add_mobj_hook(L, type); + } + else if (( type = hook_in_list(name, hookNames) ) < HOOK(MAX)) + { + add_hook(&hookIds[type]); + } + /*else if (strcmp(name, "HUD") == 0) // ehh this is cool and all, but i dont want modders potentially breaking vanilla clients lol + { + add_hud_hook(L, 3); + }*/ + else + { + return luaL_argerror(L, 1, lua_pushfstring(L, "invalid hook " LUA_QS, name)); } - // iterate the hook metadata structs - // set lastp to the last hook struct's "next" pointer. - for (hookp = *lastp; hookp; hookp = hookp->next) - lastp = &hookp->next; - // allocate a permanent memory struct to stuff hook. - hookp = ZZ_Alloc(sizeof(struct hook_s)); - memcpy(hookp, &hook, sizeof(struct hook_s)); - // tack it onto the end of the linked list. - *lastp = hookp; + add_hook_ref(L, 2);/* the function */ - // set the hook function in the registry. - lua_getfield(L, LUA_REGISTRYINDEX, "hooks"); - lua_pushvalue(L, 1); - lua_rawseti(L, -2, hook.id); return 0; } int LUA_HookLib(lua_State *L) { - memset(hooksAvailable,0,sizeof(UINT8[(hook_MAX/8)+1])); - roothook = NULL; - lua_register(L, "addHook", lib_addHook); + lua_pushcfunction(L, LUA_GetErrorMessage); + errorRef = luaL_ref(L, LUA_REGISTRYINDEX); - lua_newtable(L); - lua_setfield(L, LUA_REGISTRYINDEX, "hooks"); + lua_register(L, "addHook", lib_addHook); return 0; } -boolean LUAh_MobjHook(mobj_t *mo, enum hook which) + +int lib_hudadd(lua_State *L);/* yeah compiler */ +int lib_hudadd(lua_State *L) { - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[which/8] & (1<<(which%8)))) + luaL_checktype(L, 1, LUA_TFUNCTION); + + add_hud_hook(L, 2); + add_hook_ref(L, 1); + + return 0; +} + +typedef struct Hook_State Hook_State; +typedef void (*Hook_Callback)(Hook_State *); + +struct Hook_State { + INT32 status;/* return status to calling function */ + void * userdata; + int hook_type; + mobjtype_t mobj_type;/* >0 if mobj hook */ + boolean force_mobj;// allows mobj_type equal 0 + const char * string;/* used to fetch table, ran first if set */ + int top;/* index of last argument passed to hook */ + int id;/* id to fetch ref */ + int values;/* num arguments passed to hook */ + int results;/* num values returned by hook */ + Hook_Callback results_handler;/* callback when hook successfully returns */ +}; + +enum { + EINDEX = 1,/* error handler */ + SINDEX = 2,/* string itself is pushed in case of string hook */ +}; + +static void push_error_handler(void) +{ + lua_getref(gL, errorRef); +} + +/* repush hook string */ +static void push_string(void) +{ + lua_pushvalue(gL, SINDEX); +} + +static boolean begin_hook_values(Hook_State *hook) +{ + hook->top = lua_gettop(gL); + return true; +} + +static void start_hook_stack(void) +{ + lua_settop(gL, 0); + push_error_handler(); +} + +static boolean init_hook_type +( + Hook_State * hook, + int status, + int hook_type, + mobjtype_t mobj_type, + const char * string, + int nonzero +){ + hook->status = status; + + if (nonzero) + { + start_hook_stack(); + hook->hook_type = hook_type; + hook->mobj_type = mobj_type; + hook->string = string; + return begin_hook_values(hook); + } + else return false; +} - I_Assert(mo->type < NUMMOBJTYPES); +static boolean prepare_hook +( + Hook_State * hook, + int default_status, + int hook_type +){ + hook->force_mobj = false; - if (!(mobjhooks[MT_NULL] || mobjhooks[mo->type])) + return init_hook_type(hook, default_status, + hook_type, 0, NULL, + hookIds[hook_type].numHooks); +} + +static boolean prepare_mobj_hook +( + Hook_State * hook, + int default_status, + int hook_type, + mobj_t * primary_mobj +){ + const mobjtype_t mobj_type = + primary_mobj ? primary_mobj->type : NUMMOBJTYPES; + + hook->force_mobj = true; + + return init_hook_type(hook, default_status, + hook_type, mobj_type, NULL, + mobj_hook_available(hook_type, mobj_type)); +} + +static boolean prepare_string_hook +( + Hook_State * hook, + int default_status, + int hook_type, + const char * string +){ + hook->force_mobj = false; + + if (init_hook_type(hook, default_status, + hook_type, 0, string, + stringHooks[hook_type].ref)) + { + lua_pushstring(gL, string); + return begin_hook_values(hook); + } + else return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // Look for all generic mobj hooks - for (hookp = mobjhooks[MT_NULL]; hookp; hookp = hookp->next) - { - if (hookp->type != which) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - LUA_PushUserdata(gL, mo, META_MOBJ); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - for (hookp = mobjhooks[mo->type]; hookp; hookp = hookp->next) - { - if (hookp->type != which) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - LUA_PushUserdata(gL, mo, META_MOBJ); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; } -boolean LUAh_PlayerHook(player_t *plr, enum hook which) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[which/8] & (1<<(which%8)))) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = playerhooks; hookp; hookp = hookp->next) - { - if (hookp->type != which) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - LUA_PushUserdata(gL, plr, META_PLAYER); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; +static void init_hook_call +( + Hook_State * hook, + int results, + Hook_Callback results_handler +){ + const int top = lua_gettop(gL); + hook->values = (top - hook->top); + hook->top = top; + hook->results = results; + hook->results_handler = results_handler; } -// Hook for map change (before load) -void LUAh_MapChange(INT16 mapnumber) +static void get_hook(Hook_State *hook, const int *ids, int n) { - hook_p hookp; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_MapChange/8] & (1<<(hook_MapChange%8)))) - return; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - lua_pushinteger(gL, mapnumber); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_MapChange) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 0, 1)) { - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - } - } - - lua_settop(gL, 0); + hook->id = ids[n]; + lua_getref(gL, hookRefs[hook->id]); } -// Hook for map load -void LUAh_MapLoad(void) +static void get_hook_from_table(Hook_State *hook, int n) { - hook_p hookp; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_MapLoad/8] & (1<<(hook_MapLoad%8)))) - return; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - lua_pushinteger(gL, gamemap); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_MapLoad) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 0, 1)) { - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - } - } - - lua_settop(gL, 0); + lua_rawgeti(gL, -1, n); + hook->id = lua_tonumber(gL, -1); + lua_pop(gL, 1); + lua_getref(gL, hookRefs[hook->id]); } -// Hook for Got_AddPlayer -void LUAh_PlayerJoin(int playernum) +static int call_single_hook_no_copy(Hook_State *hook) { - hook_p hookp; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_PlayerJoin/8] & (1<<(hook_PlayerJoin%8)))) - return; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - lua_pushinteger(gL, playernum); - - for (hookp = roothook; hookp; hookp = hookp->next) + if (lua_pcall(gL, hook->values, hook->results, EINDEX) == 0) { - if (hookp->type != hook_PlayerJoin) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 0, 1)) { - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - } - } - - lua_settop(gL, 0); -} - -// Hook for frame (before mobj and player thinkers) -void LUAh_PreThinkFrame(void) -{ - hook_p hookp; - int HOOKSINDEX; - // variables used by perf stats - int hook_index = 0; - precise_t time_taken = 0; - if (!gL || !(hooksAvailable[hook_PreThinkFrame/8] & (1<<(hook_PreThinkFrame%8)))) - return; - - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_PreThinkFrame) - continue; - - if (cv_perfstats.value == 4) - time_taken = I_GetPreciseTime(); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - } - if (cv_perfstats.value == 4) + if (hook->results > 0) { - lua_Debug ar; - time_taken = I_GetPreciseTime() - time_taken; - // we need the function, let's just retrieve it again - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_getinfo(gL, ">S", &ar); - PS_SetPreThinkFrameHookInfo(hook_index, time_taken, ar.short_src); - hook_index++; + (*hook->results_handler)(hook); + lua_pop(gL, hook->results); } } + else + { + /* print the error message once */ + if (cv_debug & DBG_LUA || !in_bit_array(hooksErrored, hook->id)) + { + CONS_Alert(CONS_WARNING, "%s\n", lua_tostring(gL, -1)); + set_bit_array(hooksErrored, hook->id); + } + lua_pop(gL, 1); + } - lua_pop(gL, 2); // Pop error handler and hooks table + return 1; } -// Hook for frame (after mobj and player thinkers) -void LUAh_ThinkFrame(void) +static int call_single_hook(Hook_State *hook) +{ + int i; + + for (i = -(hook->values) + 1; i <= 0; ++i) + lua_pushvalue(gL, hook->top + i); + + return call_single_hook_no_copy(hook); +} + +static int call_hook_table_for(Hook_State *hook, int n) +{ + int k; + + for (k = 1; k <= n; ++k) + { + get_hook_from_table(hook, k); + call_single_hook(hook); + } + + return n; +} + +static int call_hook_table(Hook_State *hook) +{ + return call_hook_table_for(hook, lua_objlen(gL, -1)); +} + +static int call_mapped(Hook_State *hook, const hook_t *map) +{ + int k; + + for (k = 0; k < map->numHooks; ++k) + { + get_hook(hook, map->ids, k); + call_single_hook(hook); + } + + return map->numHooks; +} + +static int call_string_hooks(Hook_State *hook) +{ + const stringhook_t *map = &stringHooks[hook->hook_type]; + + int calls = 0; + + lua_getref(gL, map->ref); + + /* call generic string hooks first */ + calls += call_hook_table_for(hook, map->numGeneric); + + push_string(); + lua_rawget(gL, -2); + calls += call_hook_table(hook); + + return calls; +} + +static int call_mobj_type_hooks(Hook_State *hook, mobjtype_t mobj_type) +{ + return call_mapped(hook, &mobjHookIds[mobj_type][hook->hook_type]); +} + +static int call_hooks +( + Hook_State * hook, + int results, + Hook_Callback results_handler +){ + int calls = 0; + + init_hook_call(hook, results, results_handler); + + if (hook->string) + { + calls += call_string_hooks(hook); + } + else if (hook->force_mobj) + { + /* call generic mobj hooks first */ + calls += call_mobj_type_hooks(hook, MT_NULL); + + if (hook->mobj_type < NUMMOBJTYPES) + calls += call_mobj_type_hooks(hook, hook->mobj_type); + + ps_lua_mobjhooks.value.i += calls; + } + else + calls += call_mapped(hook, &hookIds[hook->hook_type]); + + lua_settop(gL, 0); + + return calls; +} + +/* ========================================================================= + COMMON RESULT HANDLERS + ========================================================================= */ + +#define res_none NULL + +static void res_true(Hook_State *hook) +{ + if (lua_toboolean(gL, -1)) + hook->status = true; +} + +/*static void res_false(Hook_State *hook) +{ + if (!lua_isnil(gL, -1) && !lua_toboolean(gL, -1)) + hook->status = false; +}*/ + +static void res_force(Hook_State *hook) +{ + if (!lua_isnil(gL, -1)) + { + if (lua_toboolean(gL, -1)) + hook->status = 1; // Force yes + else + hook->status = 2; // Force no + } +} + +static void res_hud(Hook_State *hook) +{ + (void)hook; + + hud_interpolate = hud_interpstring = hud_interplatch = false; + hud_interpcounter++; +} + +/* ========================================================================= + GENERALISED HOOKS + ========================================================================= */ + +int LUA_HookMobj(mobj_t *mobj, int hook_type) +{ + Hook_State hook; + if (prepare_mobj_hook(&hook, false, hook_type, mobj)) + { + LUA_PushUserdata(gL, mobj, META_MOBJ); + call_hooks(&hook, 1, res_true); + } + return hook.status; +} + +int LUA_Hook2Mobj(mobj_t *t1, mobj_t *t2, int hook_type) +{ + Hook_State hook; + if (prepare_mobj_hook(&hook, 0, hook_type, t1)) + { + LUA_PushUserdata(gL, t1, META_MOBJ); + LUA_PushUserdata(gL, t2, META_MOBJ); + call_hooks(&hook, 1, res_force); + } + return hook.status; +} + +void LUA_HookVoid(int type) +{ + Hook_State hook; + if (prepare_hook(&hook, 0, type)) + call_hooks(&hook, 0, res_none); +} + +void LUA_HookInt(INT32 number, int hook_type) +{ + Hook_State hook; + if (prepare_hook(&hook, 0, hook_type)) + { + lua_pushinteger(gL, number); + call_hooks(&hook, 0, res_none); + } +} + +/*void LUA_HookBool(boolean value, int hook_type) +{ + Hook_State hook; + if (prepare_hook(&hook, 0, hook_type)) + { + //lua_pushboolean(gL, value); + call_hooks(&hook, 0, res_none); + } +}*/ + +int LUA_HookPlayer(player_t *player, int hook_type) +{ + Hook_State hook; + if (prepare_hook(&hook, false, hook_type)) + { + LUA_PushUserdata(gL, player, META_PLAYER); + call_hooks(&hook, 1, res_true); + } + return hook.status; +} + +int LUA_HookTiccmd(player_t *player, ticcmd_t *cmd, int hook_type) +{ + Hook_State hook; + if (prepare_hook(&hook, false, hook_type)) + { + LUA_PushUserdata(gL, player, META_PLAYER); + LUA_PushUserdata(gL, cmd, META_TICCMD); + + if (hook_type == HOOK(PlayerCmd)) + hook_cmd_running = true; + + call_hooks(&hook, 1, res_true); + + if (hook_type == HOOK(PlayerCmd)) + hook_cmd_running = false; + } + return hook.status; +} + +void LUA_HookHUD(int hook_type, huddrawlist_h list) +{ + const hook_t * map = &hudHookIds[hook_type]; + Hook_State hook; + if (map->numHooks > 0) + { + start_hook_stack(); + begin_hook_values(&hook); + + LUA_SetHudHook(hook_type, list); + + hud_running = true; // local hook + hud_interpcounter = 0; + hud_interpolate = hud_interpstring = hud_interplatch = false; + init_hook_call(&hook, 1, res_hud); + call_mapped(&hook, map); + lua_settop(gL, 0); // destroy le stack!! >:3 + hud_running = false; + + lua_pushnil(gL); + lua_setfield(gL, LUA_REGISTRYINDEX, "HUD_DRAW_LIST"); + } +} + +/* ========================================================================= + SPECIALIZED HOOKS + ========================================================================= */ + +static void hook_think_frame(int type) { - hook_p hookp; - int HOOKSINDEX; // variables used by perf stats int hook_index = 0; precise_t time_taken = 0; - if (!gL || !(hooksAvailable[hook_ThinkFrame/8] & (1<<(hook_ThinkFrame%8)))) - return; + Hook_State hook; - lua_pushcfunction(gL, LUA_GetErrorMessage); + const hook_t * map = &hookIds[type]; + int k; - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) + if (prepare_hook(&hook, 0, type)) { - if (hookp->type != hook_ThinkFrame) - continue; + init_hook_call(&hook, 0, res_none); - if (cv_perfstats.value == 3) - time_taken = I_GetPreciseTime(); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - } - if (cv_perfstats.value == 3) + for (k = 0; k < map->numHooks; ++k) { - lua_Debug ar; - time_taken = I_GetPreciseTime() - time_taken; - // we need the function, let's just retrieve it again - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_getinfo(gL, ">S", &ar); - PS_SetThinkFrameHookInfo(hook_index, time_taken, ar.short_src); - hook_index++; - } - } + get_hook(&hook, map->ids, k); - lua_pop(gL, 2); // Pop error handler and hooks table -} - -// Hook for frame (at end of tick, ie after overlays, precipitation, specials) -void LUAh_PostThinkFrame(void) -{ - hook_p hookp; - int HOOKSINDEX; - // variables used by perf stats - int hook_index = 0; - precise_t time_taken = 0; - if (!gL || !(hooksAvailable[hook_PostThinkFrame/8] & (1<<(hook_PostThinkFrame%8)))) - return; - - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_PostThinkFrame) - continue; - - if (cv_perfstats.value == 5) - time_taken = I_GetPreciseTime(); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - } - if (cv_perfstats.value == 5) - { - lua_Debug ar; - time_taken = I_GetPreciseTime() - time_taken; - // we need the function, let's just retrieve it again - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_getinfo(gL, ">S", &ar); - PS_SetPostThinkFrameHookInfo(hook_index, time_taken, ar.short_src); - hook_index++; - } - } - - lua_pop(gL, 2); // Pop error handler and hooks table -} - -// Hook for Y_Ticker -void LUAh_IntermissionThinker(void) -{ - hook_p hookp; - int HOOKSINDEX; - - if (!gL || !(hooksAvailable[hook_IntermissionThinker/8] & (1<<(hook_IntermissionThinker%8)))) - return; - - lua_pushcfunction(gL, LUA_GetErrorMessage);; - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_IntermissionThinker) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - } - } - - lua_pop(gL, 2); // Pop error handler and hooks table -} - -// Hook for Y_VoteTicker -void LUAh_VoteThinker(void) -{ - hook_p hookp; - int HOOKSINDEX; - - if (!gL || !(hooksAvailable[hook_VoteThinker/8] & (1<<(hook_VoteThinker%8)))) - return; - - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_VoteThinker) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - } - } - - lua_pop(gL, 2); // Pop error handler and hooks table -} - - -// Hook for mobj collisions -UINT8 LUAh_MobjCollideHook(mobj_t *thing1, mobj_t *thing2, enum hook which) -{ - hook_p hookp; - UINT8 shouldCollide = 0; // 0 = default, 1 = force yes, 2 = force no. - int HOOKSINDEX; - if (!gL || !(hooksAvailable[which/8] & (1<<(which%8)))) - return 0; - - I_Assert(thing1->type < NUMMOBJTYPES); - - if (!(mobjcollidehooks[MT_NULL] || mobjcollidehooks[thing1->type])) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // Look for all generic mobj collision hooks - for (hookp = mobjcollidehooks[MT_NULL]; hookp; hookp = hookp->next) - { - if (hookp->type != which) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, thing1, META_MOBJ); - LUA_PushUserdata(gL, thing2, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (!lua_isnil(gL, -1)) - { // if nil, leave shouldCollide = 0. - if (lua_toboolean(gL, -1)) - shouldCollide = 1; // Force yes - else - shouldCollide = 2; // Force no - } - lua_pop(gL, 1); - } - - for (hookp = mobjcollidehooks[thing1->type]; hookp; hookp = hookp->next) - { - if (hookp->type != which) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, thing1, META_MOBJ); - LUA_PushUserdata(gL, thing2, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (!lua_isnil(gL, -1)) - { // if nil, leave shouldCollide = 0. - if (lua_toboolean(gL, -1)) - shouldCollide = 1; // Force yes - else - shouldCollide = 2; // Force no - } - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return shouldCollide; -} - -// Hook for mobj thinkers -boolean LUAh_MobjThinker(mobj_t *mo) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_MobjThinker/8] & (1<<(hook_MobjThinker%8)))) - return false; - - I_Assert(mo->type < NUMMOBJTYPES); - - if (!(mobjthinkerhooks[MT_NULL] || mobjthinkerhooks[mo->type])) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // Look for all generic mobj thinker hooks - for (hookp = mobjthinkerhooks[MT_NULL]; hookp; hookp = hookp->next) - { - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - LUA_PushUserdata(gL, mo, META_MOBJ); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - for (hookp = mobjthinkerhooks[mo->type]; hookp; hookp = hookp->next) - { - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - LUA_PushUserdata(gL, mo, META_MOBJ); - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); - if (lua_pcall(gL, 1, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; -} - -// Hook for P_TouchSpecialThing by mobj type -boolean LUAh_TouchSpecial(mobj_t *special, mobj_t *toucher) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_TouchSpecial/8] & (1<<(hook_TouchSpecial%8)))) - return false; - - I_Assert(special->type < NUMMOBJTYPES); - - if (!(mobjhooks[MT_NULL] || mobjhooks[special->type])) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // Look for all generic touch special hooks - for (hookp = mobjhooks[MT_NULL]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_TouchSpecial) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, special, META_MOBJ); - LUA_PushUserdata(gL, toucher, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - for (hookp = mobjhooks[special->type]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_TouchSpecial) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, special, META_MOBJ); - LUA_PushUserdata(gL, toucher, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; -} - -// Hook for P_DamageMobj by mobj type (Should mobj take damage?) -UINT8 LUAh_ShouldDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage) -{ - hook_p hookp; - UINT8 shouldDamage = 0; // 0 = default, 1 = force yes, 2 = force no. - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_ShouldDamage/8] & (1<<(hook_ShouldDamage%8)))) - return 0; - - I_Assert(target->type < NUMMOBJTYPES); - - if (!(mobjhooks[MT_NULL] || mobjhooks[target->type])) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // Look for all generic should damage hooks - for (hookp = mobjhooks[MT_NULL]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_ShouldDamage) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, target, META_MOBJ); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - lua_pushinteger(gL, damage); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - if (lua_pcall(gL, 4, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (!lua_isnil(gL, -1)) - { - if (lua_toboolean(gL, -1)) - shouldDamage = 1; // Force yes - else - shouldDamage = 2; // Force no - } - lua_pop(gL, 1); - } - - for (hookp = mobjhooks[target->type]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_ShouldDamage) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, target, META_MOBJ); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - lua_pushinteger(gL, damage); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - if (lua_pcall(gL, 4, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (!lua_isnil(gL, -1)) - { - if (lua_toboolean(gL, -1)) - shouldDamage = 1; // Force yes - else - shouldDamage = 2; // Force no - } - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return shouldDamage; -} - -// Hook for P_DamageMobj by mobj type (Mobj actually takes damage!) -boolean LUAh_MobjDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_MobjDamage/8] & (1<<(hook_MobjDamage%8)))) - return false; - - I_Assert(target->type < NUMMOBJTYPES); - - if (!(mobjhooks[MT_NULL] || mobjhooks[target->type])) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // Look for all generic mobj damage hooks - for (hookp = mobjhooks[MT_NULL]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_MobjDamage) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, target, META_MOBJ); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - lua_pushinteger(gL, damage); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - if (lua_pcall(gL, 4, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - for (hookp = mobjhooks[target->type]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_MobjDamage) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, target, META_MOBJ); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - lua_pushinteger(gL, damage); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - lua_pushvalue(gL, -5); - if (lua_pcall(gL, 4, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; -} - -// Hook for P_KillMobj by mobj type -boolean LUAh_MobjDeath(mobj_t *target, mobj_t *inflictor, mobj_t *source) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_MobjDeath/8] & (1<<(hook_MobjDeath%8)))) - return false; - - I_Assert(target->type < NUMMOBJTYPES); - - if (!(mobjhooks[MT_NULL] || mobjhooks[target->type])) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // Look for all generic mobj death hooks - for (hookp = mobjhooks[MT_NULL]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_MobjDeath) - continue; - - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, target, META_MOBJ); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - for (hookp = mobjhooks[target->type]; hookp; hookp = hookp->next) - { - if (hookp->type != hook_MobjDeath) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, target, META_MOBJ); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; -} - -// Hook for B_BuildTiccmd -boolean LUAh_BotTiccmd(player_t *bot, ticcmd_t *cmd) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_BotTiccmd/8] & (1<<(hook_BotTiccmd%8)))) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_BotTiccmd) - continue; - - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, bot, META_PLAYER); - LUA_PushUserdata(gL, cmd, META_TICCMD); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; -} - -// Hook for G_BuildTicCmd -boolean hook_cmd_running = false; -boolean LUAh_PlayerCmd(player_t *player, ticcmd_t *cmd) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_PlayerCmd/8] & (1<<(hook_PlayerCmd%8)))) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - hook_cmd_running = true; - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_PlayerCmd) - continue; - - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, cmd, META_TICCMD); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - hook_cmd_running = false; - lua_settop(gL, 0); - return hooked; -} - -// Hook for B_BuildTailsTiccmd by skin name -boolean LUAh_BotAI(mobj_t *sonic, mobj_t *tails, ticcmd_t *cmd) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_BotAI/8] & (1<<(hook_BotAI%8)))) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_BotAI - || (hookp->s.skinname && strcmp(hookp->s.skinname, ((skin_t*)tails->skin)->name))) - continue; - - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, sonic, META_MOBJ); - LUA_PushUserdata(gL, tails, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 8, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - - // This turns forward, backward, left, right, jump, and spin into a proper ticcmd for tails. - if (lua_istable(gL, -8)) { - boolean forward=false, backward=false, left=false, right=false, strafeleft=false, straferight=false, jump=false, spin=false; -#define CHECKFIELD(field) \ - lua_getfield(gL, -8, #field);\ - if (lua_toboolean(gL, -1))\ - field = true;\ - lua_pop(gL, 1); - - CHECKFIELD(forward) - CHECKFIELD(backward) - CHECKFIELD(left) - CHECKFIELD(right) - CHECKFIELD(strafeleft) - CHECKFIELD(straferight) - CHECKFIELD(jump) - CHECKFIELD(spin) -#undef CHECKFIELD - B_KeysToTiccmd(tails, cmd, forward, backward, left, right, strafeleft, straferight, jump, spin); - } else - B_KeysToTiccmd(tails, cmd, lua_toboolean(gL, -8), lua_toboolean(gL, -7), lua_toboolean(gL, -6), lua_toboolean(gL, -5), lua_toboolean(gL, -4), lua_toboolean(gL, -3), lua_toboolean(gL, -2), lua_toboolean(gL, -1)); - - lua_pop(gL, 8); - hooked = true; - } - - lua_settop(gL, 0); - return hooked; -} - -// Hook for linedef executors -boolean LUAh_LinedefExecute(line_t *line, mobj_t *mo, sector_t *sector) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_LinedefExecute/8] & (1<<(hook_LinedefExecute%8)))) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = linedefexecutorhooks; hookp; hookp = hookp->next) - { - if (strcmp(hookp->s.funcname, line->text)) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, line, META_LINE); - LUA_PushUserdata(gL, mo, META_MOBJ); - LUA_PushUserdata(gL, sector, META_SECTOR); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 0, 1)) { - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - } - hooked = true; - } - - lua_settop(gL, 0); - return hooked; -} - -// Hook for player chat -// Added the "mute" field. It's set to true if the message was supposed to be eaten by spam protection. -// But for netgame consistency purposes, this hook is ran first reguardless, so this boolean allows for modders to adapt if they so desire. -boolean LUAh_PlayerMsg(int source, int target, int flags, char *msg, int mute) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_PlayerMsg/8] & (1<<(hook_PlayerMsg%8)))) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_PlayerMsg) - continue; - - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, &players[source], META_PLAYER); // Source player - if (flags & 2 /*HU_CSAY*/) { // csay TODO: make HU_CSAY accessible outside hu_stuff.c - lua_pushinteger(gL, 3); // type - lua_pushnil(gL); // target - } else if (target == -1) { // sayteam - lua_pushinteger(gL, 1); // type - lua_pushnil(gL); // target - } else if (target == 0) { // say - lua_pushinteger(gL, 0); // type - lua_pushnil(gL); // target - } else { // sayto - lua_pushinteger(gL, 2); // type - LUA_PushUserdata(gL, &players[target-1], META_PLAYER); // target + if (cv_perfstats.value >= 3) + { + lua_pushvalue(gL, -1);/* need the function again */ + time_taken = I_GetPreciseTime(); } - lua_pushstring(gL, msg); // msg - if (mute) - lua_pushboolean(gL, true); // the message was supposed to be eaten by spamprotecc. - else - lua_pushboolean(gL, false); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -6); - lua_pushvalue(gL, -6); - lua_pushvalue(gL, -6); - lua_pushvalue(gL, -6); - lua_pushvalue(gL, -6); - if (lua_pcall(gL, 5, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - lua_settop(gL, 0); - return hooked; + call_single_hook(&hook); + + if (cv_perfstats.value >= 3) + { + lua_Debug ar; + time_taken = I_GetPreciseTime() - time_taken; + lua_getinfo(gL, ">S", &ar); + if (type == 4) // sorry for magic numbers + PS_SetPreThinkFrameHookInfo(hook_index, time_taken, ar.short_src); + else if (type == 5) + PS_SetThinkFrameHookInfo(hook_index, time_taken, ar.short_src); + else if (type == 6) + PS_SetPostThinkFrameHookInfo(hook_index, time_taken, ar.short_src); + + hook_index++; + } + } + + lua_settop(gL, 0); + } } -// Hook for hurt messages -boolean LUAh_HurtMsg(player_t *player, mobj_t *inflictor, mobj_t *source) +void LUA_HookPreThinkFrame(void) { - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_HurtMsg/8] & (1<<(hook_HurtMsg%8)))) - return false; + hook_think_frame(HOOK(PreThinkFrame)); +} - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); +void LUA_HookThinkFrame(void) +{ + hook_think_frame(HOOK(ThinkFrame)); +} - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); +void LUA_HookPostThinkFrame(void) +{ + hook_think_frame(HOOK(PostThinkFrame)); +} - for (hookp = roothook; hookp; hookp = hookp->next) +int LUA_HookTouchSpecial(mobj_t *special, mobj_t *toucher) +{ + Hook_State hook; + if (prepare_mobj_hook(&hook, false, MOBJ_HOOK(TouchSpecial), special)) { - if (hookp->type != hook_HurtMsg - || (hookp->s.mt && !(inflictor && hookp->s.mt == inflictor->type))) - continue; + LUA_PushUserdata(gL, special, META_MOBJ); + LUA_PushUserdata(gL, toucher, META_MOBJ); + call_hooks(&hook, 1, res_true); + } + return hook.status; +} - if (lua_gettop(gL) == 2) +static int damage_hook +( + mobj_t *target, + mobj_t *inflictor, + mobj_t *source, + INT32 damage, + int hook_type, + Hook_Callback results_handler +){ + Hook_State hook; + if (prepare_mobj_hook(&hook, 0, hook_type, target)) + { + LUA_PushUserdata(gL, target, META_MOBJ); + LUA_PushUserdata(gL, inflictor, META_MOBJ); + LUA_PushUserdata(gL, source, META_MOBJ); + if (hook_type != MOBJ_HOOK(MobjDeath)) + lua_pushinteger(gL, damage); + call_hooks(&hook, 1, results_handler); + } + return hook.status; +} + +int LUA_HookShouldDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage) +{ + return damage_hook(target, inflictor, source, damage, + MOBJ_HOOK(ShouldDamage), res_force); +} + +int LUA_HookMobjDamage(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage) +{ + return damage_hook(target, inflictor, source, damage, + MOBJ_HOOK(MobjDamage), res_true); +} + +int LUA_HookMobjDeath(mobj_t *target, mobj_t *inflictor, mobj_t *source) +{ + return damage_hook(target, inflictor, source, 0, + MOBJ_HOOK(MobjDeath), res_true); +} + +typedef struct { + mobj_t * tails; + ticcmd_t * cmd; +} BotAI_State; + +static boolean checkbotkey(const char *field) +{ + return lua_toboolean(gL, -1) && strcmp(lua_tostring(gL, -2), field) == 0; +} + +static void res_botai(Hook_State *hook) +{ + BotAI_State *botai = hook->userdata; + + int k[8]; + + int fields = 0; + + // This turns forward, backward, left, right, jump, and spin into a proper ticcmd for tails. + if (lua_istable(gL, -8)) { + lua_pushnil(gL); // key + while (lua_next(gL, -9)) { +#define CHECK(n, f) (checkbotkey(f) ? (k[(n)-1] = 1) : 0) + if ( + CHECK(1, "forward") || CHECK(2, "backward") || + CHECK(3, "left") || CHECK(4, "right") || + CHECK(5, "strafeleft") || CHECK(6, "straferight") || + CHECK(7, "jump") || CHECK(8, "spin") + ){ + if (8 <= ++fields) + { + lua_pop(gL, 2); // pop key and value + break; + } + } + + lua_pop(gL, 1); // pop value +#undef CHECK + } + } else { + while (fields < 8) { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; -} - -void LUAh_NetArchiveHook(lua_CFunction archFunc, savebuffer_t *save) -{ - hook_p hookp; - int errorhandlerindex; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_NetVars/8] & (1<<(hook_NetVars%8)))) - return; - - // stack: tables - I_Assert(lua_gettop(gL) > 0); - I_Assert(lua_istable(gL, -1)); - - lua_pushcfunction(gL, LUA_GetErrorMessage); - errorhandlerindex = lua_gettop(gL); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // tables becomes an upvalue of archFunc - lua_pushvalue(gL, -3); - lua_pushlightuserdata(gL, save); - lua_pushcclosure(gL, archFunc, 2); - // stack: tables, savebuffer_t, archFunc - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_NetVars) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -2); // archFunc - if (lua_pcall(gL, 1, 0, errorhandlerindex)) { - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); + k[fields] = lua_toboolean(gL, -8 + fields); + fields++; } } - lua_pop(gL, 3); // Pop archFunc, error handler and hooks table - // stack: tables + B_KeysToTiccmd(botai->tails, botai->cmd, + k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7]); + + hook->status = true; } -void LUAh_PlayerQuit(player_t *plr, int reason) +int LUA_HookBotAI(mobj_t *sonic, mobj_t *tails, ticcmd_t *cmd) { - hook_p hookp; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_PlayerQuit/8] & (1<<(hook_PlayerQuit%8)))) - return; + const char *skin = ((skin_t *)tails->skin)->name; - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); + Hook_State hook; + BotAI_State botai; - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) + if (prepare_string_hook(&hook, false, STRING_HOOK(BotAI), skin)) { - if (hookp->type != hook_PlayerQuit) - continue; + LUA_PushUserdata(gL, sonic, META_MOBJ); + LUA_PushUserdata(gL, tails, META_MOBJ); - if (lua_gettop(gL) == 2) + botai.tails = tails; + botai.cmd = cmd; + + hook.userdata = &botai; + + call_hooks(&hook, 8, res_botai); + } + + return hook.status; +} + +void LUA_HookLinedefExecute(line_t *line, mobj_t *mo, sector_t *sector) +{ + Hook_State hook; + if (prepare_string_hook + (&hook, 0, STRING_HOOK(LinedefExecute), line->text)) + { + LUA_PushUserdata(gL, line, META_LINE); + LUA_PushUserdata(gL, mo, META_MOBJ); + LUA_PushUserdata(gL, sector, META_SECTOR); + ps_lua_mobjhooks.value.i += call_hooks(&hook, 0, res_none); + } +} + +int LUA_HookPlayerMsg(int source, int target, int flags, char *msg, int mute) +{ + Hook_State hook; + if (prepare_hook(&hook, false, HOOK(PlayerMsg))) + { + LUA_PushUserdata(gL, &players[source], META_PLAYER); // Source player + if (flags & 2 /*HU_CSAY*/) { // csay TODO: make HU_CSAY accessible outside hu_stuff.c + lua_pushinteger(gL, 3); // type + lua_pushnil(gL); // target + } else if (target == -1) { // sayteam + lua_pushinteger(gL, 1); // type + lua_pushnil(gL); // target + } else if (target == 0) { // say + lua_pushinteger(gL, 0); // type + lua_pushnil(gL); // target + } else { // sayto + lua_pushinteger(gL, 2); // type + LUA_PushUserdata(gL, &players[target-1], META_PLAYER); // target + } + lua_pushstring(gL, msg); // msg + if (mute) + lua_pushboolean(gL, true); // the message was supposed to be eaten by spamprotecc. + else + lua_pushboolean(gL, false); + call_hooks(&hook, 1, res_true); + } + return hook.status; +} + +int LUA_HookHurtMsg(player_t *player, mobj_t *inflictor, mobj_t *source) +{ + Hook_State hook; + if (prepare_mobj_hook(&hook, false, MOBJ_HOOK(HurtMsg), inflictor)) + { + LUA_PushUserdata(gL, player, META_PLAYER); + LUA_PushUserdata(gL, inflictor, META_MOBJ); + LUA_PushUserdata(gL, source, META_MOBJ); + call_hooks(&hook, 1, res_true); + } + return hook.status; +} + +void LUA_HookNetArchive(lua_CFunction archFunc) +{ + const hook_t * map = &hookIds[HOOK(NetVars)]; + Hook_State hook; + hook.force_mobj = false; + /* this is a remarkable case where the stack isn't reset */ + if (map->numHooks > 0) + { + // stack: tables + I_Assert(lua_gettop(gL) > 0); + I_Assert(lua_istable(gL, -1)); + + push_error_handler(); + lua_insert(gL, EINDEX); + + begin_hook_values(&hook); + + // tables becomes an upvalue of archFunc + lua_pushvalue(gL, -1); + lua_pushcclosure(gL, archFunc, 1); + // stack: tables, archFunc + + init_hook_call(&hook, 0, res_none); + call_mapped(&hook, map); + + lua_pop(gL, 1); // pop archFunc + lua_remove(gL, EINDEX); // pop error handler + // stack: tables + } +} + +void LUA_HookPlayerQuit(player_t *plr, int reason) +{ + Hook_State hook; + if (prepare_hook(&hook, 0, HOOK(PlayerQuit))) + { + LUA_PushUserdata(gL, plr, META_PLAYER); // Player that quit + lua_pushinteger(gL, reason); // Reason for quitting + call_hooks(&hook, 0, res_none); + } +} + +boolean hook_cmd_running = false; + +static void update_music_name(struct MusicChange *musicchange) +{ + size_t length; + const char * new = lua_tolstring(gL, -6, &length); + + if (length < 7) + { + strcpy(musicchange->newname, new); + lua_pushvalue(gL, -6);/* may as well keep it for next call */ + } + else + { + memcpy(musicchange->newname, new, 6); + musicchange->newname[6] = '\0'; + lua_pushlstring(gL, new, 6); + } + + lua_replace(gL, -7); +} + +static void res_musicchange(Hook_State *hook) +{ + struct MusicChange *musicchange = hook->userdata; + + // output 1: true, false, or string musicname override + if (lua_isstring(gL, -6)) + update_music_name(musicchange); + else if (lua_isboolean(gL, -6) && lua_toboolean(gL, -6)) + hook->status = true; + + // output 2: mflags override + if (lua_isnumber(gL, -5)) + *musicchange->mflags = lua_tonumber(gL, -5); + // output 3: looping override + if (lua_isboolean(gL, -4)) + *musicchange->looping = lua_toboolean(gL, -4); + // output 4: position override + if (lua_isnumber(gL, -3)) + *musicchange->position = lua_tonumber(gL, -3); + // output 5: prefadems override + if (lua_isnumber(gL, -2)) + *musicchange->prefadems = lua_tonumber(gL, -2); + // output 6: fadeinms override + if (lua_isnumber(gL, -1)) + *musicchange->fadeinms = lua_tonumber(gL, -1); +} + +int LUA_HookMusicChange(const char *oldname, struct MusicChange *param) +{ + const int type = HOOK(MusicChange); + const hook_t * map = &hookIds[type]; + + Hook_State hook; + + int k; + + if (prepare_hook(&hook, false, type)) + { + init_hook_call(&hook, 6, res_musicchange); + hook.values = 7;/* values pushed later */ + hook.userdata = param; + + lua_pushstring(gL, oldname);/* the only constant value */ + lua_pushstring(gL, param->newname);/* semi constant */ + + for (k = 0; k < map->numHooks; ++k) { - LUA_PushUserdata(gL, plr, META_PLAYER); // Player that quit - lua_pushinteger(gL, reason); // Reason for quitting - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -3); - lua_pushvalue(gL, -3); - if (lua_pcall(gL, 2, 0, 1)) { - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); + get_hook(&hook, map->ids, k); + + lua_pushvalue(gL, -3); + lua_pushvalue(gL, -3); + lua_pushinteger(gL, *param->mflags); + lua_pushboolean(gL, *param->looping); + lua_pushinteger(gL, *param->position); + lua_pushinteger(gL, *param->prefadems); + lua_pushinteger(gL, *param->fadeinms); + + call_single_hook_no_copy(&hook); } + + lua_settop(gL, 0); } - lua_settop(gL, 0); + return hook.status; } -// Hook for music changes -boolean LUAh_MusicChange(const char *oldname, char *newname, UINT16 *mflags, boolean *looping, - UINT32 *position, UINT32 *prefadems, UINT32 *fadeinms) -{ - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - - if (!gL || !(hooksAvailable[hook_MusicChange/8] & (1<<(hook_MusicChange%8)))) - return false; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - for (hookp = roothook; hookp; hookp = hookp->next) +static int kartdamage_hook +( + player_t *player, + mobj_t *inflictor, + mobj_t *source, + int hook_type, + Hook_Callback results_handler +){ + Hook_State hook; + if (prepare_hook(&hook, 0, hook_type)) { - if (hookp->type != hook_MusicChange) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushstring(gL, oldname); - lua_pushstring(gL, newname); - lua_pushinteger(gL, *mflags); - lua_pushboolean(gL, *looping); - lua_pushinteger(gL, *position); - lua_pushinteger(gL, *prefadems); - lua_pushinteger(gL, *fadeinms); - if (lua_pcall(gL, 7, 6, 1)) { - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL,-1)); - lua_pop(gL, 1); - continue; - } - - // output 1: true, false, or string musicname override - if (lua_isboolean(gL, -6) && lua_toboolean(gL, -6)) - hooked = true; - else if (lua_isstring(gL, -6)) - strncpy(newname, lua_tostring(gL, -6), 7); - // output 2: mflags override - if (lua_isnumber(gL, -5)) - *mflags = lua_tonumber(gL, -5); - // output 3: looping override - if (lua_isboolean(gL, -4)) - *looping = lua_toboolean(gL, -4); - // output 4: position override - if (lua_isnumber(gL, -3)) - *position = lua_tonumber(gL, -3); - // output 5: prefadems override - if (lua_isnumber(gL, -2)) - *prefadems = lua_tonumber(gL, -2); - // output 6: fadeinms override - if (lua_isnumber(gL, -1)) - *fadeinms = lua_tonumber(gL, -1); - - lua_pop(gL, 6); + LUA_PushUserdata(gL, player, META_PLAYER); + LUA_PushUserdata(gL, inflictor, META_MOBJ); + LUA_PushUserdata(gL, source, META_MOBJ); + call_hooks(&hook, 1, results_handler); } - - lua_settop(gL, 0); - newname[6] = 0; - return hooked; + return hook.status; } // Hook for K_SpinPlayer. Determines if yes or no we should get damaged reguardless of circumstances. -UINT8 LUAh_ShouldSpin(player_t *player, mobj_t *inflictor, mobj_t *source) +int LUA_HookShouldSpin(player_t *player, mobj_t *inflictor, mobj_t *source) { - hook_p hookp; - UINT8 shouldDamage = 0; // 0 = default, 1 = force yes, 2 = force no. - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_ShouldSpin/8] & (1<<(hook_ShouldSpin%8)))) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // We can afford not to check for mobj type because it will always be MT_PLAYER in this case. - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_ShouldSpin) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (!lua_isnil(gL, -1)) - { - if (lua_toboolean(gL, -1)) - shouldDamage = 1; // Force yes - else - shouldDamage = 2; // Force no - } - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return shouldDamage; + return kartdamage_hook(player, inflictor, source, HOOK(ShouldSpin), res_force); } // Hook for K_ExplodePlayer. Determines if yes or no we should get damaged reguardless of circumstances. -UINT8 LUAh_ShouldExplode(player_t *player, mobj_t *inflictor, mobj_t *source) +int LUA_HookShouldExplode(player_t *player, mobj_t *inflictor, mobj_t *source) { - hook_p hookp; - UINT8 shouldDamage = 0; // 0 = default, 1 = force yes, 2 = force no. - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_ShouldExplode/8] & (1<<(hook_ShouldExplode%8)))) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // We can afford not to check for mobj type because it will always be MT_PLAYER in this case. - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_ShouldExplode) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (!lua_isnil(gL, -1)) - { - if (lua_toboolean(gL, -1)) - shouldDamage = 1; // Force yes - else - shouldDamage = 2; // Force no - } - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return shouldDamage; + return kartdamage_hook(player, inflictor, source, HOOK(ShouldExplode), res_force); } // Hook for K_SquishPlayer. Determines if yes or no we should get damaged reguardless of circumstances. -UINT8 LUAh_ShouldSquish(player_t *player, mobj_t *inflictor, mobj_t *source) +int LUA_HookShouldSquish(player_t *player, mobj_t *inflictor, mobj_t *source) { - hook_p hookp; - UINT8 shouldDamage = 0; // 0 = default, 1 = force yes, 2 = force no. - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_ShouldSquish/8] & (1<<(hook_ShouldSquish%8)))) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // We can afford not to check for mobj type because it will always be MT_PLAYER in this case. - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_ShouldSquish) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (!lua_isnil(gL, -1)) - { - if (lua_toboolean(gL, -1)) - shouldDamage = 1; // Force yes - else - shouldDamage = 2; // Force no - } - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return shouldDamage; + return kartdamage_hook(player, inflictor, source, HOOK(ShouldSquish), res_force); } // Hook for K_SpinPlayer. This is used when the player has actually been spun out, but before anything has actually been done. This allows Lua to overwrite the behavior or to just perform actions. -boolean LUAh_PlayerSpin(player_t *player, mobj_t *inflictor, mobj_t *source) +boolean LUA_HookPlayerSpin(player_t *player, mobj_t *inflictor, mobj_t *source) { - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_PlayerSpin/8] & (1<<(hook_PlayerSpin%8)))) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // We can afford not to look for target->type because it will always be MT_PLAYER. - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_PlayerSpin) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; + return kartdamage_hook(player, inflictor, source, HOOK(PlayerSpin), res_true); } // Hook for K_SquishPlayer. This is used when the player has actually been spun out, but before anything has actually been done. This allows Lua to overwrite the behavior or to just perform actions. -boolean LUAh_PlayerSquish(player_t *player, mobj_t *inflictor, mobj_t *source) +boolean LUA_HookPlayerSquish(player_t *player, mobj_t *inflictor, mobj_t *source) { - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_PlayerSquish/8] & (1<<(hook_PlayerSquish%8)))) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // We can afford not to look for target->type because it will always be MT_PLAYER. - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_PlayerSquish) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; + return kartdamage_hook(player, inflictor, source, HOOK(PlayerSquish), res_true); } // Hook for K_ExplodePlayer. This is used when the player has actually been spun out, but before anything has actually been done. This allows Lua to overwrite the behavior or to just perform actions. -boolean LUAh_PlayerExplode(player_t *player, mobj_t *inflictor, mobj_t *source) +boolean LUA_HookPlayerExplode(player_t *player, mobj_t *inflictor, mobj_t *source) { - hook_p hookp; - boolean hooked = false; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_PlayerExplode/8] & (1<<(hook_PlayerExplode%8)))) - return 0; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // We can afford not to look for target->type because it will always be MT_PLAYER. - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_PlayerExplode) - continue; - - ps_lua_mobjhooks.value.i++; - if (lua_gettop(gL) == 2) - { - LUA_PushUserdata(gL, player, META_PLAYER); - LUA_PushUserdata(gL, inflictor, META_MOBJ); - LUA_PushUserdata(gL, source, META_MOBJ); - } - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - lua_pushvalue(gL, -4); - if (lua_pcall(gL, 3, 1, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - if (lua_toboolean(gL, -1)) - hooked = true; - lua_pop(gL, 1); - } - - lua_settop(gL, 0); - return hooked; -} - -void LUAh_ServerJoin(void) -{ - hook_p hookp; - int HOOKSINDEX; - if (!gL || !(hooksAvailable[hook_ServerJoin/8] & (1<<(hook_ServerJoin%8)))) - return; - - lua_settop(gL, 0); - lua_pushcfunction(gL, LUA_GetErrorMessage); - - lua_getfield(gL, LUA_REGISTRYINDEX, "hooks"); - HOOKSINDEX = lua_gettop(gL); - I_Assert(lua_istable(L, HOOKSINDEX)); - - // We can afford not to look for target->type because it will always be MT_PLAYER. - - for (hookp = roothook; hookp; hookp = hookp->next) - { - if (hookp->type != hook_ServerJoin) - continue; - - lua_rawgeti(gL, HOOKSINDEX, hookp->id); - if (lua_pcall(gL, 0, 0, 1)) { - if (!hookp->error || cv_debug & DBG_LUA) - CONS_Alert(CONS_WARNING,"%s\n",lua_tostring(gL, -1)); - lua_pop(gL, 1); - hookp->error = true; - continue; - } - } - - lua_settop(gL, 0); + return kartdamage_hook(player, inflictor, source, HOOK(PlayerExplode), res_true); } diff --git a/src/lua_hud.h b/src/lua_hud.h index 5d1f41c83..76ce9eb48 100644 --- a/src/lua_hud.h +++ b/src/lua_hud.h @@ -50,9 +50,6 @@ extern boolean hud_interplatch; // string mode was toggled boolean LUA_HudEnabled(enum hud option); -void LUAh_GameHUD(huddrawlist_h list); -void LUAh_ScoresHUD(huddrawlist_h list); -void LUAh_IntermissionHUD(huddrawlist_h list); -void LUAh_VoteHUD(huddrawlist_h list); +void LUA_SetHudHook(int hook, huddrawlist_h list); #endif // __LUA_HUD_H__ diff --git a/src/lua_hudlib.c b/src/lua_hudlib.c index 0af7f2c36..f3c01f4eb 100644 --- a/src/lua_hudlib.c +++ b/src/lua_hudlib.c @@ -28,6 +28,7 @@ #include "lua_script.h" #include "lua_libs.h" #include "lua_hud.h" +#include "lua_hook.h" #define HUDONLY if (!hud_running) return luaL_error(L, "HUD rendering code should not be called outside of rendering hooks!"); @@ -40,8 +41,6 @@ boolean hud_interpstring = false; boolean hud_interplatch = false; static UINT8 hud_enabled[(hud_MAX/8)+1]; -static UINT8 hudAvailable; // hud hooks field - static UINT8 camnum = 1; // must match enum hud in lua_hud.h @@ -93,19 +92,6 @@ static const char *const patch_opt[] = { "topoffset", NULL}; -enum hudhook { - hudhook_game = 0, - hudhook_scores = 1, - hudhook_intermission = 2, - hudhook_vote = 3, -}; -static const char *const hudhook_opt[] = { - "game", - "scores", - "intermission", - "vote", - NULL}; - static int patch_fields_ref = LUA_NOREF; // alignment types for v.drawString @@ -503,7 +489,7 @@ static int libd_getSpritePatch(lua_State *L) angle = (angle & 7); // modulus angle by 8 // rotsprite????? - if (lua_isnumber(L, 4) && (cv_spriteroll.value)) + if (lua_isnumber(L, 4) && cv_sloperoll.value) { angle_t rollangle = luaL_checkangle(L, 4); INT32 rot = R_GetRollAngle(rollangle); @@ -591,26 +577,16 @@ static int libd_drawOnMinimap(lua_State *L) UINT8 *colormap = NULL; // do we want to colormap this patch? boolean centered; // the patch is centered and doesn't need readjusting on x/y coordinates. huddrawlist_h list; - - // variables used to replicate k_kart's mmap drawer: - INT32 lumpnum; - patch_t *AutomapPic; - INT32 mx, my; - INT32 splitflags, minimaptrans; + patch_t *AutomapPic = NULL; // base position of the minimap which also takes splits into account: INT32 MM_X, MM_Y; // variables used for actually drawing the icon: + INT32 splitflags, minimaptrans; fixed_t amnumxpos, amnumypos; - INT32 amxpos, amypos; - - node_t *bsp = &nodes[numnodes-1]; - fixed_t maxx, minx, maxy, miny; - - fixed_t mapwidth, mapheight; - fixed_t xoffset, yoffset; - fixed_t xscale, yscale, zoom; + fixed_t amxpos, amypos; + INT32 mm_x, mm_y; fixed_t patchw, patchh; HUDONLY // only run this function in hud hooks @@ -622,8 +598,6 @@ static int libd_drawOnMinimap(lua_State *L) colormap = *((UINT8 **)luaL_checkudata(L, 5, META_COLORMAP)); centered = lua_optboolean(L, 6); - // replicate exactly what source does for its minimap drawer; AKA hardcoded garbo. - // first, check what position the mmap is supposed to be in (pasted from k_kart.c): MM_X = BASEVIDWIDTH - 50 + cv_mini_xoffset.value; // 270 MM_Y = (BASEVIDHEIGHT/2)-16 + cv_mini_yoffset.value; // 84 @@ -658,7 +632,6 @@ static int libd_drawOnMinimap(lua_State *L) else return 0; - minimaptrans = ((10-minimaptrans)<width/2); - my = MM_Y - (AutomapPic->height/2); + // Handle offsets and stuff. + mm_x = MM_X - (SHORT(AutomapPic->width)/2); + mm_y = MM_Y - (SHORT(AutomapPic->height)/2); // let offsets transfer to the heads, too! if (encoremode) - mx += SHORT(AutomapPic->leftoffset); + { + mm_x += SHORT(AutomapPic->leftoffset); + } else - mx -= SHORT(AutomapPic->leftoffset); - my -= SHORT(AutomapPic->topoffset); + { + mm_x -= SHORT(AutomapPic->leftoffset); + } - // now that we have replicated this behavior, we can draw an icon from our supplied x, y coordinates by replicating k_kart.c's totally understandable uncommented code!!! - - // get map boundaries using nodes - maxx = maxy = INT32_MAX; - minx = miny = INT32_MIN; - minx = bsp->bbox[0][BOXLEFT]; - maxx = bsp->bbox[0][BOXRIGHT]; - miny = bsp->bbox[0][BOXBOTTOM]; - maxy = bsp->bbox[0][BOXTOP]; - - if (bsp->bbox[1][BOXLEFT] < minx) - minx = bsp->bbox[1][BOXLEFT]; - if (bsp->bbox[1][BOXRIGHT] > maxx) - maxx = bsp->bbox[1][BOXRIGHT]; - if (bsp->bbox[1][BOXBOTTOM] < miny) - miny = bsp->bbox[1][BOXBOTTOM]; - if (bsp->bbox[1][BOXTOP] > maxy) - maxy = bsp->bbox[1][BOXTOP]; - - // You might be wondering why these are being bitshift here - // it's because mapwidth and height would otherwise overflow for maps larger than half the size possible... - // map boundaries and sizes will ALWAYS be whole numbers thankfully - // later calculations take into consideration that these are actually not in terms of FRACUNIT though - minx >>= FRACBITS; - maxx >>= FRACBITS; - miny >>= FRACBITS; - maxy >>= FRACBITS; - - // these are our final map boundaries: - mapwidth = maxx - minx; - mapheight = maxy - miny; - - // These should always be small enough to be bitshift back right now - xoffset = (minx + mapwidth/2)<width, mapwidth); - yscale = FixedDiv(AutomapPic->height, mapheight); - zoom = FixedMul(min(xscale, yscale), FRACUNIT-FRACUNIT/20); - - amnumxpos = (FixedMul(x, zoom) - FixedMul(xoffset, zoom)); - amnumypos = -(FixedMul(y, zoom) - FixedMul(yoffset, zoom)); - - if (encoremode) - amnumxpos = -amnumxpos; + mm_y -= SHORT(AutomapPic->topoffset); // scale patch coords - patchw = patch->width*scale /2; - patchh = patch->height*scale /2; + patchw = (SHORT(patch->width) * scale / 2); + patchh = (SHORT(patch->height) * scale / 2); if (centered) + { patchw = patchh = 0; // patch is supposedly already centered, don't butt in. + } - amxpos = amnumxpos + ((mx + AutomapPic->width/2)<height/2)<width) / 2)<height) / 2)<snext; } diff --git a/src/lua_script.c b/src/lua_script.c index 7a66d3656..cb28cc906 100644 --- a/src/lua_script.c +++ b/src/lua_script.c @@ -1312,7 +1312,8 @@ void LUA_Archive(savebuffer_t *save, boolean network) LUAh_NetArchiveHook(NetArchive, save); // call the NetArchive hook in archive mode } - ArchiveTables(&save->p); + LUA_HookNetArchive(NetArchive); // call the NetArchive hook in archive mode + ArchiveTables(); if (gL) lua_pop(gL, 1); // pop tables diff --git a/src/lua_script.h b/src/lua_script.h index f0b77e80e..cf17ccbfa 100644 --- a/src/lua_script.h +++ b/src/lua_script.h @@ -63,7 +63,7 @@ void Got_Luacmd(UINT8 **cp, INT32 playernum); // lua_consolelib.c void LUA_CVarChanged(const char *name); // lua_consolelib.c int Lua_optoption(lua_State *L, int narg, int def, int list_ref); int Lua_CreateFieldTable(lua_State *L, const char *const lst[]); -void LUAh_NetArchiveHook(lua_CFunction archFunc, savebuffer_t *save); +void LUA_HookNetArchive(lua_CFunction archFunc); // Console wrapper void COM_Lua_f(void); diff --git a/src/lzf.c b/src/lzf.c index d5a837888..f81c3ee0a 100644 --- a/src/lzf.c +++ b/src/lzf.c @@ -37,8 +37,9 @@ /* * Sacrifice very little compression quality in favour of compression speed. * This gives almost the same compression as the default code, and is - * (very roughly) 15% faster. This is the preferred mode of operation. + * (very roughly) 15% faster. This is the preferable mode of operation. */ + #ifndef VERY_FAST # define VERY_FAST 1 #endif @@ -47,7 +48,7 @@ * Sacrifice some more compression quality in favour of compression speed. * (roughly 1-2% worse compression for large blocks and * 9-10% for small, redundant, blocks and >>20% better speed in both cases) - * In short: when in need for speed, enable this for binary data, + * In INT16: when in need for speed, enable this for binary data, * possibly disable this for text data. */ #ifndef ULTRA_FAST @@ -65,10 +66,21 @@ #endif #endif +/* + * Use string functions to copy memory. + * this is usually a loss, even with glibc's optimized memcpy + */ +#ifndef USE_MEMCPY +#ifdef _MSC_VER +# define USE_MEMCPY 0 +#else +# define USE_MEMCPY 1 +#endif +#endif + /* * You may choose to pre-set the hash table (might be faster on some - * modern cpus and large (>>64k) blocks, and also makes compression - * deterministic/repeatable when the configuration otherwise is the same). + * modern cpus and large (>>64k) blocks) */ #ifndef INIT_HTAB # define INIT_HTAB 1 @@ -76,15 +88,15 @@ /* * Avoid assigning values to errno variable? for some embedding purposes - * (linux kernel for example), this is necessary. NOTE: this breaks - * the documentation in lzf.h. Avoiding errno has no speed impact. + * (linux kernel for example), this is neccessary. NOTE: this breaks + * the documentation in lzf.h. */ #ifndef AVOID_ERRNO # define AVOID_ERRNO 0 #endif /* - * Whether to pass the LZF_STATE variable as argument, or allocate it + * Wether to pass the LZF_STATE variable as argument, or allocate it * on the stack. For small-stack environments, define this to 1. * NOTE: this breaks the prototype in lzf.h. */ @@ -93,108 +105,50 @@ #endif /* - * Whether to add extra checks for input validity in lzf_decompress + * Wether to add extra checks for input validity in lzf_decompress * and return EINVAL if the input stream has been corrupted. This * only shields against overflowing the input buffer and will not * detect most corrupted streams. - * This check is not normally noticeable on modern hardware + * This check is not normally noticable on modern hardware * (<1% slowdown), but might slow down older cpus considerably. */ #ifndef CHECK_INPUT # define CHECK_INPUT 1 #endif -/* - * Whether the target CPU has a slow multiplication. This affects - * the default hash function for the compressor, and enables a slightly - * worse hash function that needs only shifts. - */ -#ifndef MULTIPLICATION_IS_SLOW -# define MULTIPLICATION_IS_SLOW 0 -#endif - -/* - * If defined, then this data type will be used for storing offsets. - * This can be useful if you want to use a huge hashtable, want to - * conserve memory, or both, and your data fits into e.g. 64kb. - * If instead you want to compress data > 4GB, then it's better to - * to "#define LZF_USE_OFFSETS 0" instead. - */ -/*#define LZF_HSLOT unsigned short*/ - -/* - * Whether to store pointers or offsets inside the hash table. On - * 64 bit architetcures, pointers take up twice as much space, - * and might also be slower. Default is to autodetect. - */ -/*#define LZF_USE_OFFSETS autodetect */ - -/* - * Whether to optimise code for size, at the expense of speed. Use - * this when you are extremely tight on memory, perhaps in combination - * with AVOID_ERRNO 1 and CHECK_INPUT 0. - */ -#ifndef OPTIMISE_SIZE -# ifdef __OPTIMIZE_SIZE__ -# define OPTIMISE_SIZE 1 -# else -# define OPTIMISE_SIZE 0 -# endif -#endif - /*****************************************************************************/ /* nothing should be changed below */ -# include -# include - -#if ULTRA_FAST -# undef VERY_FAST -#endif - -#ifndef LZF_USE_OFFSETS -# ifdef _WIN32 -# define LZF_USE_OFFSETS defined(_M_X64) -# else -# include -# define LZF_USE_OFFSETS (UINTPTR_MAX > 0xffffffffU) -# endif -#endif - typedef unsigned char u8; -#ifdef LZF_HSLOT -# define LZF_HSLOT_BIAS ((const u8 *)in_data) -#else -# ifdef LZF_USE_OFFSETS -# define LZF_HSLOT_BIAS ((const u8 *)in_data) - typedef unsigned int LZF_HSLOT; +typedef const u8 *LZF_STATE[1 << (HLOG)]; + +#if !STRICT_ALIGN +/* for unaligned accesses we need a 16 bit datatype. */ +# include +# if USHRT_MAX == 65535 + typedef unsigned short u16; +# elif UINT_MAX == 65535 + typedef unsigned int u16; # else -# define LZF_HSLOT_BIAS 0 - typedef const u8 *LZF_HSLOT; +# undef STRICT_ALIGN +# define STRICT_ALIGN 1 # endif #endif -#if USHRT_MAX == 65535 - typedef unsigned short u16; -#elif UINT_MAX == 65535 - typedef unsigned int u16; -#else -# undef STRICT_ALIGN -# define STRICT_ALIGN 1 +#if ULTRA_FAST +# if defined(VERY_FAST) +# undef VERY_FAST +# endif #endif -#define LZF_MAX_LIT (1 << 5) -#define LZF_MAX_OFF (1 << 13) -#define LZF_MAX_REF ((1 << 8) + (1 << 3)) - -typedef LZF_HSLOT LZF_STATE[1 << (HLOG)]; - -typedef struct -{ - const u8 *first [1 << (6+8)]; /* most recent occurance of a match */ - u16 prev [LZF_MAX_OFF]; /* how many bytes to go backwards for the next match */ -} LZF_STATE_BEST[1]; +#if USE_MEMCPY || INIT_HTAB +# ifdef __cplusplus +# include +# else +# include +# endif +#endif #endif @@ -210,31 +164,14 @@ typedef struct # define SET_ERRNO(n) errno = (n) #endif -#ifndef USE_REP_MOVSB -#if (defined (__i386) || defined (__amd64)) && __GNUC__ >= 3 -#define USE_REP_MOVSB 1 -#else -#define USE_REP_MOVSB 0 // Default to 0 if not defined elsewhere -#endif -#endif - -#if USE_REP_MOVSB /* small win on amd, big loss on intel */ -#if (defined (__i386) || defined (__amd64)) && __GNUC__ >= 3 -# define lzf_movsb(dst, src, len) \ - asm ("rep movsb" \ - : "=D" (dst), "=S" (src), "=c" (len) \ - : "0" (dst), "1" (src), "2" (len)); -#endif -#endif - size_t lzf_decompress (const void *const in_data, size_t in_len, - void *out_data, size_t out_len) + void *out_data, size_t out_len) { u8 const *ip = (const u8 *)in_data; - u8 *op = (u8 *)out_data; + u8 *op = (u8 *)out_data; u8 const *const in_end = ip + in_len; - u8 *const out_end = op + out_len; + u8 *const out_end = op + out_len; do { @@ -258,23 +195,14 @@ lzf_decompress (const void *const in_data, size_t in_len, } #endif -#ifdef lzf_movsb - lzf_movsb (op, ip, ctrl); -#elif OPTIMISE_SIZE - while (ctrl--) - *op++ = *ip++; +#if USE_MEMCPY + M_Memcpy (op, ip, ctrl); + op += ctrl; + ip += ctrl; #else - switch (ctrl) - { - case 32: *op++ = *ip++; case 31: *op++ = *ip++; case 30: *op++ = *ip++; case 29: *op++ = *ip++; - case 28: *op++ = *ip++; case 27: *op++ = *ip++; case 26: *op++ = *ip++; case 25: *op++ = *ip++; - case 24: *op++ = *ip++; case 23: *op++ = *ip++; case 22: *op++ = *ip++; case 21: *op++ = *ip++; - case 20: *op++ = *ip++; case 19: *op++ = *ip++; case 18: *op++ = *ip++; case 17: *op++ = *ip++; - case 16: *op++ = *ip++; case 15: *op++ = *ip++; case 14: *op++ = *ip++; case 13: *op++ = *ip++; - case 12: *op++ = *ip++; case 11: *op++ = *ip++; case 10: *op++ = *ip++; case 9: *op++ = *ip++; - case 8: *op++ = *ip++; case 7: *op++ = *ip++; case 6: *op++ = *ip++; case 5: *op++ = *ip++; - case 4: *op++ = *ip++; case 3: *op++ = *ip++; case 2: *op++ = *ip++; case 1: *op++ = *ip++; - } + do + *op++ = *ip++; + while (--ctrl); #endif } else /* back reference */ @@ -316,49 +244,12 @@ lzf_decompress (const void *const in_data, size_t in_len, return 0; } -#ifdef lzf_movsb - len += 2; - lzf_movsb (op, ref, len); -#elif OPTIMISE_SIZE - len += 2; + *op++ = *ref++; + *op++ = *ref++; do *op++ = *ref++; while (--len); -#else - switch (len) - { - default: - len += 2; - - if (op >= ref + len) - { - /* disjunct areas */ - memcpy (op, ref, len); - op += len; - } - else - { - /* overlapping, use octet by octet copying */ - do - *op++ = *ref++; - while (--len); - } - break; - - case 9: *op++ = *ref++; - case 8: *op++ = *ref++; - case 7: *op++ = *ref++; - case 6: *op++ = *ref++; - case 5: *op++ = *ref++; - case 4: *op++ = *ref++; - case 3: *op++ = *ref++; - case 2: *op++ = *ref++; - case 1: *op++ = *ref++; - case 0: *op++ = *ref++; /* two octets more */ - *op++ = *ref++; - } -#endif } } while (ip < in_end); @@ -375,29 +266,23 @@ lzf_decompress (const void *const in_data, size_t in_len, /* * don't play with this unless you benchmark! - * the data format is not dependent on the hash function. - * the hash function might seem strange, just believe me, + * decompression is not dependent on the hash function + * the hashing function might seem strange, just believe me * it works ;) */ #ifndef FRST # define FRST(p) (((p[0]) << 8) | p[1]) # define NEXT(v,p) (((v) << 8) | p[2]) -# if MULTIPLICATION_IS_SLOW -# if ULTRA_FAST -# define IDX(h) ((( h >> (3*8 - HLOG)) - h ) & (HSIZE - 1)) -# elif VERY_FAST -# define IDX(h) ((( h >> (3*8 - HLOG)) - h*5) & (HSIZE - 1)) -# else -# define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) - h*5) & (HSIZE - 1)) -# endif -# else -/* this one was developed with sesse, - * and is very similar to the one in snappy. - * it does need a modern enough cpu with a fast multiplication. - */ -# define IDX(h) (((h * 0x1e35a7bdU) >> (32 - HLOG - 8)) & (HSIZE - 1)) -# endif +# define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) - h*5) & (HSIZE - 1)) #endif +/* + * IDX works because it is very similar to a multiplicative hash, e.g. + * ((h * 57321 >> (3*8 - HLOG)) & (HSIZE - 1)) + * the latter is also quite fast on newer CPUs, and sligthly better + * + * the next one is also quite good, albeit slow ;) + * (int)(cos(h & 0xffffff) * 1e6) + */ #if 0 /* original lzv-like hash function, much worse and thus slower */ @@ -406,214 +291,177 @@ lzf_decompress (const void *const in_data, size_t in_len, # define IDX(h) ((h) & (HSIZE - 1)) #endif -#if __GNUC__ >= 3 -# define expect(expr,value) __builtin_expect ((expr),(value)) -# define inline inline -#else -# define expect(expr,value) (expr) -# define inline static -#endif - -#define expect_false(expr) expect ((expr) != 0, 0) -#define expect_true(expr) expect ((expr) != 0, 1) +#define MAX_LIT (1 << 5) +#define MAX_OFF (1 << 13) +#define MAX_REF ((1 << 8) + (1 << 3)) /* * compressed format * - * 000LLLLL ; literal, L+1=1..33 octets - * LLLooooo oooooooo ; backref L+1=1..7 octets, o+1=1..4096 offset - * 111ooooo LLLLLLLL oooooooo ; backref L+8 octets, o+1=1..4096 offset + * 000LLLLL ; literal + * LLLooooo oooooooo ; backref L + * 111ooooo LLLLLLLL oooooooo ; backref L+7 * */ size_t -lzf_compress (const void *const in_data, size_t in_len, - void *out_data, size_t out_len +lzf_compress (const void *const in_data,size_t in_len, + void *out_data, size_t out_len #if LZF_STATE_ARG - , LZF_STATE htab + , LZF_STATE *htab #endif - ) + ) { #if !LZF_STATE_ARG LZF_STATE htab; #endif + const u8 **hslot; const u8 *ip = (const u8 *)in_data; - u8 *op = (u8 *)out_data; + u8 *op = (u8 *)out_data; const u8 *in_end = ip + in_len; - u8 *out_end = op + out_len; - const u8 *ref; - - /* - * off requires a type wide enough to hold a general pointer difference. - * ISO C doesn't have that (size_t might not be enough and ptrdiff_t only - * works for differences within a single object). We also assume that - * no bit pattern traps. Since the only platform that is both non-POSIX - * and fails to support both assumptions is windows 64 bit, we make a - * special workaround for it. - */ + u8 *out_end = op + out_len; + const u8 *ref = NULL; + unsigned int hval = FRST (ip); size_t off; - unsigned int hval; - int lit; - - if (!in_len || !out_len) - return 0; + int lit = 0; #if INIT_HTAB +# if USE_MEMCPY memset (htab, 0, sizeof (htab)); +# else + for (hslot = htab; hslot < htab + HSIZE; hslot++) + *hslot++ = ip; +# endif #endif - lit = 0; op++; /* start run */ - - hval = FRST (ip); - while (ip < in_end - 2) + for (;;) { - LZF_HSLOT *hslot; - - hval = NEXT (hval, ip); - hslot = htab + IDX (hval); - ref = *hslot + LZF_HSLOT_BIAS; *hslot = ip - LZF_HSLOT_BIAS; - - if (1 -#if INIT_HTAB - && ref < ip /* the next test will actually take care of this, but this is faster */ -#endif - && (off = ip - ref - 1) < LZF_MAX_OFF - && ref > (const u8 *)in_data - && ref[2] == ip[2] -#if STRICT_ALIGN - && ((ref[1] << 8) | ref[0]) == ((ip[1] << 8) | ip[0]) -#else - && *(const u16 *)ref == *(const u16 *)ip -#endif - ) + if (ip < in_end - 2) { - /* match found at *ref++ */ - unsigned int len = 2; - size_t maxlen = in_end - ip - len; - maxlen = maxlen > LZF_MAX_REF ? LZF_MAX_REF : maxlen; + hval = NEXT (hval, ip); + hslot = htab + IDX (hval); + ref = *hslot; *hslot = ip; - if (expect_false (op + 3 + 1 >= out_end)) /* first a faster conservative test */ - if (op - !lit + 3 + 1 >= out_end) /* second the exact but rare test */ - return 0; - - op [- lit - 1] = lit - 1; /* stop run */ - op -= !lit; /* undo run if length is zero */ - - for (;;) + if ( +#if INIT_HTAB && !USE_MEMCPY + ref < ip /* the next test will actually take care of this, but this is faster */ + && +#endif + (off = ip - ref - 1) < MAX_OFF + && ip + 4 < in_end + && ref > (const u8 *)in_data +#if STRICT_ALIGN + && ref[0] == ip[0] + && ref[1] == ip[1] + && ref[2] == ip[2] +#else + && *(const u16 *)ref == *(const u16 *)ip + && ref[2] == ip[2] +#endif + ) { - if (expect_true (maxlen > 16)) - { - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; + /* match found at *ref++ */ + unsigned int len = 2; + size_t maxlen = in_end - ip - len; + maxlen = maxlen > MAX_REF ? MAX_REF : maxlen; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - len++; if (ref [len] != ip [len]) break; - } + if (op + lit + 1 + 3 >= out_end) + return 0; do len++; while (len < maxlen && ref[len] == ip[len]); - break; - } + if (lit) + { + *op++ = (u8)(lit - 1); + lit = -lit; + do + *op++ = ip[lit]; + while (++lit); + } - len -= 2; /* len is now #octets - 1 */ - ip++; + len -= 2; + ip++; - if (len < 7) - { - *op++ = (off >> 8) + (len << 5); - } - else - { - *op++ = (off >> 8) + ( 7 << 5); - *op++ = len - 7; - } + if (len < 7) + { + *op++ = (u8)((off >> 8) + (len << 5)); + } + else + { + *op++ = (u8)((off >> 8) + ( 7 << 5)); + *op++ = (u8)(len - 7); + } - *op++ = off; - - lit = 0; op++; /* start run */ - - ip += len + 1; - - if (expect_false (ip >= in_end - 2)) - break; + *op++ = (u8)off; #if ULTRA_FAST || VERY_FAST - --ip; -# if VERY_FAST && !ULTRA_FAST - --ip; -# endif - hval = FRST (ip); - - hval = NEXT (hval, ip); - htab[IDX (hval)] = ip - LZF_HSLOT_BIAS; - ip++; - -# if VERY_FAST && !ULTRA_FAST - hval = NEXT (hval, ip); - htab[IDX (hval)] = ip - LZF_HSLOT_BIAS; - ip++; -# endif -#else - ip -= len + 1; - - do - { - hval = NEXT (hval, ip); - htab[IDX (hval)] = ip - LZF_HSLOT_BIAS; - ip++; - } - while (len--); + ip += len; +#if VERY_FAST && !ULTRA_FAST + --ip; #endif + hval = FRST (ip); + + hval = NEXT (hval, ip); + htab[IDX (hval)] = ip; + ip++; + +#if VERY_FAST && !ULTRA_FAST + hval = NEXT (hval, ip); + htab[IDX (hval)] = ip; + ip++; +#endif +#else + do + { + hval = NEXT (hval, ip); + htab[IDX (hval)] = ip; + ip++; + } + while (len--); +#endif + continue; + } } - else + else if (ip == in_end) + break; + + /* one more literal byte we must copy */ + lit++; + ip++; + + if (lit == MAX_LIT) { - /* one more literal byte we must copy */ - if (expect_false (op >= out_end)) + if (op + 1 + MAX_LIT >= out_end) return 0; - lit++; *op++ = *ip++; - - if (expect_false (lit == LZF_MAX_LIT)) - { - op [- lit - 1] = lit - 1; /* stop run */ - lit = 0; op++; /* start run */ - } + *op++ = MAX_LIT - 1; +#if USE_MEMCPY + M_Memcpy (op, ip - MAX_LIT, MAX_LIT); + op += MAX_LIT; + lit = 0; +#else + lit = -lit; + do + *op++ = ip[lit]; + while (++lit); +#endif } } - if (op + 3 > out_end) /* at most 3 bytes can be missing here */ - return 0; - - while (ip < in_end) + if (lit) { - lit++; *op++ = *ip++; + if (op + lit + 1 >= out_end) + return 0; - if (expect_false (lit == LZF_MAX_LIT)) - { - op [- lit - 1] = lit - 1; /* stop run */ - lit = 0; op++; /* start run */ - } + *op++ = (u8)(lit - 1); + lit = -lit; + do + *op++ = ip[lit]; + while (++lit); } - op [- lit - 1] = lit - 1; /* end run */ - op -= !lit; /* undo run if length is zero */ - - return op - (u8 *)out_data; + return op - (u8 *) out_data; } diff --git a/src/lzf.h b/src/lzf.h index dae8b131c..85daf255e 100644 --- a/src/lzf.h +++ b/src/lzf.h @@ -1,6 +1,6 @@ // SONIC ROBO BLAST 2 //----------------------------------------------------------------------------- -// Copyright (c) 2000-2010 Marc Alexander Lehmann +// Copyright (C) 2000-2005 by Marc Alexander Lehmann // // This program is free software distributed under the // terms of the GNU General Public License, version 2. @@ -22,7 +22,7 @@ ** ***********************************************************************/ -#define LZF_VERSION 0x0106 /* 1.6 */ +#define LZF_VERSION 0x0105 /* 1.5 */ /* * Compress in_len bytes stored at the memory block starting at diff --git a/src/m_cheat.c b/src/m_cheat.c index abada4be5..5f8648cbd 100644 --- a/src/m_cheat.c +++ b/src/m_cheat.c @@ -1091,7 +1091,7 @@ void OP_ObjectplaceMovement(player_t *player) { ticcmd_t *cmd = &player->cmd; - if (!player->climbing && (netgame || !cv_analog.value || (player->pflags & PF_SPINNING))) + if (!player->climbing && (netgame || (player->pflags & PF_SPINNING))) player->mo->angle = (cmd->angleturn<<16 /* not FRACBITS */); ticruned++; diff --git a/src/m_fixed.h b/src/m_fixed.h index d67777162..3f1acd7ae 100644 --- a/src/m_fixed.h +++ b/src/m_fixed.h @@ -247,6 +247,35 @@ FUNCMATH FUNCINLINE static ATTRINLINE fixed_t FixedRound(fixed_t x) return INT32_MAX; } +/** \brief The xs_CRoundToInt function + + \param val double number + + \return Round toward nearest, but ties round toward even +*/ +#if defined(SRB2_BIG_ENDIAN) + #define _xs_iexp_ 0 + #define _xs_iman_ 1 +#else + #define _xs_iexp_ 1 //intel is little endian + #define _xs_iman_ 0 +#endif //BigEndian_ + +typedef double real64; + +typedef union _xs_doubleints +{ + real64 val; + unsigned ival[2]; +} _xs_doubleints; + +FUNCMATH FUNCINLINE static ATTRINLINE int xs_CRoundToInt(real64 val) +{ + _xs_doubleints uval; + uval.val = val + 6755399441055744.0; + return uval.ival[_xs_iman_]; +} + typedef struct { fixed_t x; diff --git a/src/m_menu.c b/src/m_menu.c index 94b5f8f3b..a4121d448 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -1160,7 +1160,7 @@ static menuitem_t OP_ControlsMenu[] = {IT_CALL | IT_STRING, NULL, "Player 3 Controls...", &M_Setup3PControlsMenu, 30}, {IT_CALL | IT_STRING, NULL, "Player 4 Controls...", &M_Setup4PControlsMenu, 40}, - + {IT_SUBMENU | IT_STRING, NULL, "Mouse Options...", &OP_MouseOptionsDef, 60}, {IT_STRING | IT_CVAR, NULL, "Controls per key", &cv_controlperkey, 80}, @@ -1224,19 +1224,19 @@ static menuitem_t OP_AllControlsMenu[] = static menuitem_t OP_Joystick1Menu[] = { {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup1PJoystickMenu, 10}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis , 20}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis , 25}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis , 30}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis , 35}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis , 40}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis , 45}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis , 50}, - {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis , 60}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis , 65}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis , 70}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone , 75}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone , 80}, + {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[0] , 20}, + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[0] , 25}, + {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[0] , 30}, + {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[0] , 35}, + {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[0] , 40}, + {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[0] , 45}, + {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[0] , 50}, + {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis[0] , 55}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[0] , 60}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[0] , 65}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[0] , 70}, + {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[0] , 75}, + {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[0] , 80}, {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[0] , 90}, {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[0] , 95}, @@ -1246,19 +1246,19 @@ static menuitem_t OP_Joystick1Menu[] = static menuitem_t OP_Joystick2Menu[] = { {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup2PJoystickMenu, 10}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis2 , 20}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis2 , 25}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis2 , 30}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis2 , 35}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis2 , 40}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis2 , 45}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis2 , 50}, - {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis2 , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis2 , 60}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis2 , 65}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis2 , 70}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone2 , 75}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone2 , 80}, + {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[1] , 20}, + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[1] , 25}, + {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[1] , 30}, + {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[1] , 35}, + {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[1] , 40}, + {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[1] , 45}, + {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[1] , 50}, + {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis[1] , 55}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[1] , 60}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[1] , 65}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[1] , 70}, + {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[1] , 75}, + {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[1] , 80}, {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[1] , 90}, {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[1] , 95}, @@ -1268,19 +1268,19 @@ static menuitem_t OP_Joystick2Menu[] = static menuitem_t OP_Joystick3Menu[] = { {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup3PJoystickMenu, 10}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis3 , 20}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis3 , 25}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis3 , 30}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis3 , 35}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis3 , 40}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis3 , 45}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis3 , 50}, - {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis3 , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis3 , 60}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis3 , 65}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis3 , 70}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone3 , 75}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone3 , 80}, + {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[2] , 20}, + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[2] , 25}, + {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[2] , 30}, + {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[2] , 35}, + {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[2] , 40}, + {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[2] , 45}, + {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[2] , 50}, + {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis[2] , 55}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[2] , 60}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[2] , 65}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[2] , 70}, + {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[2] , 75}, + {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[2] , 80}, {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[2] , 90}, {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[2] , 95}, @@ -1290,19 +1290,19 @@ static menuitem_t OP_Joystick3Menu[] = static menuitem_t OP_Joystick4Menu[] = { {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup4PJoystickMenu, 10}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis4 , 20}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis4 , 25}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis4 , 30}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis4 , 35}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis4 , 40}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis4 , 45}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis4 , 50}, - {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis4 , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis4 , 60}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis4 , 65}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis4 , 70}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone4 , 75}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone4 , 80}, + {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[3] , 20}, + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[3] , 25}, + {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[3] , 30}, + {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[3] , 35}, + {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[3] , 40}, + {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[3] , 45}, + {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[3] , 50}, + {IT_STRING | IT_CVAR, NULL, "Spec. Look Up/Down" , &cv_lookaxis[3] , 55}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[3] , 60}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[3] , 65}, + {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[3] , 70}, + {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[3] , 75}, + {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[3] , 80}, {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[3] , 90}, {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[3] , 95}, @@ -1372,7 +1372,7 @@ static menuitem_t OP_VideoOptionsMenu[] = {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_globalsaturation , 40}, - + {IT_SUBMENU|IT_STRING, NULL, "Advanced Color Settings...", &OP_ColorOptionsDef, 50}, {IT_STRING | IT_CVAR, NULL, "Draw Distance", &cv_drawdist, 65}, @@ -1484,7 +1484,7 @@ static menuitem_t OP_ColorOptionsMenu[] = static menuitem_t OP_ExpOptionsMenu[] = { {IT_HEADER, NULL, "Advanced Video Options", NULL, 10}, - {IT_STRING|IT_CVAR, NULL, "Interpolation Distance", &cv_grmaxinterpdist, 30}, + {IT_STRING|IT_CVAR, NULL, "Interpolation Distance", &cv_maxinterpdist, 30}, {IT_STRING | IT_CVAR, NULL, "Weather Interpolation", &cv_precipinterp, 40}, {IT_STRING | IT_CVAR, NULL, "Scale Weather with Mobjscale", &cv_mobjscaleprecip, 60}, @@ -1492,15 +1492,15 @@ static menuitem_t OP_ExpOptionsMenu[] = {IT_STRING | IT_CVAR, NULL, "Skyboxes", &cv_skybox, 80}, -#ifdef HWRENDER - {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_grscreentextures, 100}, -#ifdef USE_FBO_OGL - {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_grframebuffer, 110}, -#endif - {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_grpalettedepth, 130}, + {IT_STRING | IT_CVAR, NULL, "FPS counter sampling", &cv_accuratefps, 90}, - {IT_STRING | IT_CVAR, NULL, "Splitwall/Slope texture fix", &cv_splitwallfix, 150}, -#endif +#ifdef HWRENDER + {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 110}, +#ifdef USE_FBO_OGL + {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_glframebuffer, 120}, +#endif + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 140}, +#endif }; static const char* OP_ExpTooltips[] = @@ -1511,13 +1511,13 @@ static const char* OP_ExpTooltips[] = "Should weather be scaled with Mapobjectscale?.", "When weather is on this will cut the object amount used in half.", "Toggle being able to see the sky.", + "Change the FPS counter sampling method\nInaccurate updates slower and might miss frame drops and such\nAccurate updates faster and is more accurate, but might be less readable", // how to ingles?? #ifdef HWRENDER "Should the game do Screen Textures? Provides a good boost to frames\nat the cost of some visual effects not working when disabled.", #ifdef USE_FBO_OGL "Allows the game to downsample from a higher resolution than your display\nin OpenGL renderer mode. Requires a GPU with atleast OpenGL 3.0 support.", #endif "Change the depth of the Palette in Palette rendering mode\n 16 bits is like software looks ingame\nwhile 24 bits is how software looks in screenshots.", - "Fixes issues that resulted in Textures sticking from the ground sometimes.\n This may be CPU heavy and result in worse performance in some cases.", #endif }; @@ -1529,13 +1529,13 @@ enum op_exp_precipmoscale, op_exp_lessprecip, op_exp_skybox, + op_exp_accuratefps, #ifdef HWRENDER - op_exp_grscrtx, + op_exp_glscrtx, #ifdef USE_FBO_OGL op_exp_fbo, #endif op_exp_paldepth, - op_exp_spltwal, #endif }; @@ -1543,24 +1543,24 @@ enum #ifdef HWRENDER static menuitem_t OP_OpenGLOptionsMenu[] = { - {IT_STRING | IT_CVAR, NULL, "3D Models", &cv_grmdls, 15}, - {IT_STRING | IT_CVAR, NULL, "Fallback Player 3D Model", &cv_grfallbackplayermodel, 20}, - {IT_STRING | IT_CVAR, NULL, "Shaders", &cv_grshaders, 25}, - {IT_STRING | IT_CVAR, NULL, "Palette Rendering", &cv_grpaletterendering, 30}, - {IT_STRING | IT_CVAR, NULL, "Flashpals in Palette Renderer", &cv_grflashpal, 35}, - {IT_STRING | IT_CVAR, NULL, "Min Shader Brightness", &cv_secbright, 40}, + {IT_STRING | IT_CVAR, NULL, "3D Models", &cv_glmdls, 15}, + {IT_STRING | IT_CVAR, NULL, "Fallback Player 3D Model", &cv_glfallbackplayermodel, 20}, + {IT_STRING | IT_CVAR, NULL, "Shaders", &cv_glshaders, 25}, + {IT_STRING | IT_CVAR, NULL, "Palette Rendering", &cv_glpaletterendering, 30}, + {IT_STRING | IT_CVAR, NULL, "Palette Rendering Flashpals",&cv_glflashpal, 35}, + {IT_STRING | IT_CVAR, NULL, "Min Shader Brightness", &cv_glsecbright, 40}, - {IT_STRING|IT_CVAR, NULL, "Texture Quality", &cv_scr_depth, 50}, - {IT_STRING|IT_CVAR, NULL, "Texture Filter", &cv_grfiltermode, 55}, - {IT_STRING|IT_CVAR, NULL, "Anisotropic", &cv_granisotropicmode, 60}, - {IT_STRING|IT_CVAR, NULL, "Visual Portals", &cv_grportals, 65}, + {IT_STRING | IT_CVAR, NULL, "Texture Quality", &cv_scr_depth, 50}, + {IT_STRING | IT_CVAR, NULL, "Texture Filter", &cv_glfiltermode, 55}, + {IT_STRING | IT_CVAR, NULL, "Anisotropic", &cv_glanisotropicmode, 60}, + {IT_STRING | IT_CVAR, NULL, "Visual Portals", &cv_glportals, 65}, - {IT_STRING|IT_CVAR, NULL, "Wall Contrast Style", &cv_grfakecontrast, 75}, - {IT_STRING|IT_CVAR, NULL, "Slope Contrast", &cv_grslopecontrast, 80}, - {IT_STRING | IT_CVAR, NULL, "Dithered Lightning", &cv_lightdither, 85}, - {IT_STRING|IT_CVAR, NULL, "Sprite Billboarding", &cv_grspritebillboarding, 90}, - {IT_STRING|IT_CVAR, NULL, "Software Perspective", &cv_grshearing, 95}, - {IT_STRING|IT_CVAR, NULL, "Rendering Distance", &cv_grrenderdistance, 100}, + {IT_STRING | IT_CVAR, NULL, "Wall Contrast Style", &cv_glfakecontrast, 75}, + {IT_STRING | IT_CVAR, NULL, "Slope Contrast", &cv_glslopecontrast, 80}, + {IT_STRING | IT_CVAR, NULL, "Dithered Lightning", &cv_gllightdither, 85}, + {IT_STRING | IT_CVAR, NULL, "Sprite Billboarding", &cv_glspritebillboarding, 90}, + {IT_STRING | IT_CVAR, NULL, "Software Perspective", &cv_glshearing, 95}, + {IT_STRING | IT_CVAR, NULL, "Rendering Distance", &cv_glrenderdistance, 100}, }; static const char* OP_OpenGLTooltips[] = @@ -1577,11 +1577,32 @@ static const char* OP_OpenGLTooltips[] = "Recreates an effect from software mode that is used on some maps.", "The look of the wall contrast effect.", "Wall contrast but for slopes.", - "Should OpenGL lightning be dithered?", + "Should shader lightning be dithered?", "Should sprites always face the camera?", "Recreates the look of software mode camera perspective.", "How far the game world should be drawn.", }; + +enum +{ + op_gl_mdls, + op_gl_falbckmdls, + op_gl_shader, + op_gl_palrender, + op_gl_flashpal, + op_gl_secbright, + op_gl_scrdepth, + op_gl_filter, + op_gl_anis, + op_gl_portal, + op_gl_wallcont, + op_gl_slopecont, + op_gl_lightdither, + op_gl_bill, + op_gl_shearing, + op_gl_renderdist, +}; + #endif static menuitem_t OP_SoundOptionsMenu[] = @@ -1608,7 +1629,7 @@ static menuitem_t OP_SoundOptionsMenu[] = {IT_STRING|IT_CVAR, NULL, "Character voices", &cv_kartvoices, 75}, {IT_STRING|IT_CVAR, NULL, "Hit Em Delay", &cv_karthitemdialog, 85}, {IT_STRING|IT_CVAR, NULL, "Powerup Warning", &cv_kartinvinsfx, 95}, - + {IT_KEYHANDLER|IT_STRING, NULL, "Sound Test", M_HandleSoundTest, 105}, {IT_STRING|IT_CALL, NULL, "Music Test", M_MusicTest, 115}, @@ -1622,7 +1643,7 @@ static menuitem_t OP_SoundOptionsMenu[] = {IT_STRING|IT_CVAR, NULL, "Character voices", &cv_kartvoices, 85}, {IT_STRING|IT_CVAR, NULL, "Hit Em Delay", &cv_karthitemdialog, 95}, {IT_STRING|IT_CVAR, NULL, "Powerup Warning", &cv_kartinvinsfx, 105}, - + {IT_KEYHANDLER|IT_STRING, NULL, "Sound Test", M_HandleSoundTest, 115}, {IT_STRING|IT_CALL, NULL, "Music Test", M_MusicTest, 125}, @@ -1683,7 +1704,7 @@ static const char* OP_SoundAdvancedTooltips[] = { #ifdef HAVE_OPENMPT NULL, - + "Filter used to resample tracker instruments.", "Resample tracker modules to sound similar to Paula hardware.", #if OPENMPT_API_VERSION_MAJOR < 1 && OPENMPT_API_VERSION_MINOR > 4 @@ -1796,7 +1817,7 @@ static menuitem_t OP_HUDOptionsMenu[] = { {IT_STRING | IT_CVAR, NULL, "Show HUD (F3)", &cv_showhud, 10}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "HUD Visibility", &cv_translucenthud, 20}, + NULL, "HUD Visibility", &cv_translucenthud, 20}, {IT_STRING | IT_SUBMENU, NULL, "Online HUD options...", &OP_ChatOptionsDef, 35}, {IT_STRING | IT_CVAR, NULL, "Background Glass", &cons_backcolor, 45}, @@ -1812,9 +1833,9 @@ static menuitem_t OP_HUDOptionsMenu[] = {IT_STRING | IT_CVAR, NULL, "Console Text Size", &cv_constextsize, 120}, {IT_STRING | IT_CVAR, NULL, "Show Track Addon Name", &cv_showtrackaddon, 135}, - + {IT_STRING | IT_CVAR, NULL, "Show All Maps", &cv_showallmaps, 145}, - + {IT_STRING | IT_CVAR, NULL, "Show \"FOCUS LOST\"", &cv_showfocuslost, 155}, {IT_STRING | IT_CVAR, NULL, "2D character select", &cv_skinselectmenu, 165}, @@ -1851,52 +1872,52 @@ static menuitem_t OP_Player1CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 1 Camera Options", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam, 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist, 40}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height, 50}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed, 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam_rotspeed, 70}, + {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[0], 30}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[0], 40}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[0], 50}, + {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[0], 60}, + {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam_rotspeed[0], 70}, - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam, 85}, + {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[0], 85}, }; static menuitem_t OP_Player2CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 2 Camera Options", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam2, 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam2_dist, 40}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam2_height, 50}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam2_speed, 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam2_rotspeed, 70}, + {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[1], 30}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[1], 40}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[1], 50}, + {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[1], 60}, + {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam_rotspeed[1], 70}, - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam2, 85}, + {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[1], 85}, }; static menuitem_t OP_Player3CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 3 Camera Options", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam3, 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam3_dist, 40}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam3_height, 50}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam3_speed, 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam3_rotspeed, 70}, + {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[2], 30}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[2], 40}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[2], 50}, + {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[2], 60}, + {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam_rotspeed[2], 70}, - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam3, 85}, + {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[2], 85}, }; static menuitem_t OP_Player4CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 4 Camera Options", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam4, 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam4_dist, 40}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam4_height, 50}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam4_speed, 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam4_rotspeed, 70}, + {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[3], 30}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[3], 40}, + {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[3], 50}, + {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[3], 60}, + {IT_STRING | IT_CVAR, NULL, "Camera Rotation Speed", &cv_cam_rotspeed[3], 70}, - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam4, 85}, + {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[3], 85}, }; static const char* OP_PlayerCamOptionsTooltips[] = @@ -2066,7 +2087,7 @@ static menuitem_t OP_AdvServerOptionsMenu[] = }; static const char* OP_AdvServerOptionsTooltips[] = -{ +{ "Server used for master server.", "Attempts to resynchronise player to server.", #ifdef SATURNSYNCH @@ -2203,22 +2224,20 @@ static menuitem_t OP_PlayerDistortMenu[] = { {IT_HEADER, NULL, "Sprite Distortion", NULL, 0}, - {IT_STRING | IT_CVAR, NULL, "Sprite Rotation", &cv_spriteroll, 15}, - {IT_STRING | IT_CVAR, NULL, "Sprite Slope Rotation", &cv_sloperoll, 30}, - {IT_STRING | IT_CVAR, NULL, "Slope Rotation Distance", &cv_sloperolldist, 45}, - {IT_STRING | IT_CVAR, NULL, "Rotate Players when Sliptiding", &cv_sliptideroll, 60}, - {IT_STRING | IT_CVAR, NULL, "Rotate Sparks and Boost Trails", &cv_sparkroll, 75}, - {IT_STRING | IT_CVAR, NULL, "Player Stretch Factor", &cv_gravstretch, 90}, - {IT_STRING | IT_CVAR, NULL, "Squish Sound Effect", &cv_slamsound, 105}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop", &cv_saltyhop, 120}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop Sound Effect", &cv_saltyhopsfx, 135}, - {IT_STRING | IT_CVAR, NULL, "Saltyhop Squish", &cv_saltysquish, 150}, + {IT_STRING | IT_CVAR, NULL, "Sprite Slope Rotation", &cv_sloperoll, 15}, + {IT_STRING | IT_CVAR, NULL, "Slope Rotation Distance", &cv_sloperolldist, 30}, + {IT_STRING | IT_CVAR, NULL, "Rotate Players when Sliptiding", &cv_sliptideroll, 45}, + {IT_STRING | IT_CVAR, NULL, "Rotate Sparks and Boost Trails", &cv_sparkroll, 60}, + {IT_STRING | IT_CVAR, NULL, "Player Stretch Factor", &cv_gravstretch, 75}, + {IT_STRING | IT_CVAR, NULL, "Squish Sound Effect", &cv_slamsound, 90}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop", &cv_saltyhop, 105}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop Sound Effect", &cv_saltyhopsfx, 120}, + {IT_STRING | IT_CVAR, NULL, "Saltyhop Squish", &cv_saltysquish, 135}, }; static const char* OP_PlayerDistortTooltips[] = { NULL, - "Sprite rotation features.", "Sprite rotation on slopes. Can either be just players or all objects.", "Distance object rotation should be visable.", "Player rotation when sliptiding.", @@ -2233,7 +2252,6 @@ static const char* OP_PlayerDistortTooltips[] = enum { spriteheader, - spriterotate, sloperotate, slrotatedist, sliptide, @@ -2330,7 +2348,6 @@ enum sh_hudoffsets, }; - static menuitem_t OP_HudOffsetMenu[] = { {IT_HEADER, NULL, "Kart Hud Offsets", NULL, 0}, @@ -2384,7 +2401,7 @@ static menuitem_t OP_SaturnCreditsMenu[] = {IT_STRING2+IT_SPACE, NULL, "xyzzy", NULL, 70}, {IT_STRING2+IT_SPACE, NULL, "Chearii", NULL, 80}, - {IT_STRING+IT_SPACE, NULL, "", NULL, 83}, // dummy text + {IT_STRING+IT_SPACE, NULL, "", NULL, 83}, // dummy text {IT_STRING2+IT_SPACE, NULL, "Sunflower aka AnimeSonic", NULL, 90}, {IT_STRING2+IT_SPACE, NULL, "Yuz aka Yuzler", NULL, 100}, @@ -3377,7 +3394,7 @@ void Addons_option_Onchange(void) void PDistort_menu_Onchange(void) { - if (!cv_spriteroll.value) + if (!cv_sloperoll.value) { OP_PlayerDistortMenu[sloperotate].status = IT_GRAYEDOUT; OP_PlayerDistortMenu[sliptide].status = IT_GRAYEDOUT; @@ -3388,15 +3405,10 @@ void PDistort_menu_Onchange(void) OP_PlayerDistortMenu[sliptide].status = IT_STRING | IT_CVAR; } - if ((cv_sloperoll.value) && (cv_spriteroll.value)) //enable/disable sloperotate distance + if (cv_sloperoll.value) //enable/disable sloperotate distance OP_PlayerDistortMenu[slrotatedist].status = IT_STRING | IT_CVAR; else OP_PlayerDistortMenu[slrotatedist].status = IT_GRAYEDOUT; - - if ((cv_sloperoll.value == 2) && (cv_spriteroll.value)) //enable/disable sparkroll depending on which setting - OP_PlayerDistortMenu[sparkrotate].status = IT_STRING | IT_CVAR; - else - OP_PlayerDistortMenu[sparkrotate].status = IT_GRAYEDOUT; } void Bird_menu_Onchange(void) @@ -3421,7 +3433,7 @@ void Bird_menu_Onchange(void) OP_AdvancedBirdMenu[fadegrow].status = status; OP_AdvancedBirdMenu[respawnfadeout].status = status; OP_AdvancedBirdMenu[respawnfadein].status = status; - + if (cv_birdmusic.value) { OP_BirdMenu[lvlresum].status = IT_STRING | IT_CVAR; @@ -3433,7 +3445,7 @@ void Bird_menu_Onchange(void) OP_BirdMenu[lvlresum].status = IT_GRAYEDOUT; OP_BirdMenu[spclresum].status = IT_GRAYEDOUT; OP_BirdMenu[advmusic].status = IT_GRAYEDOUT; - } + } } //menu code is nice @@ -3445,11 +3457,30 @@ void SaturnHud_menu_Onchange(void) status = IT_STRING | IT_CVAR; else status = IT_GRAYEDOUT; - + OP_SaturnHudMenu[sh_coloritem].status = status; OP_SaturnHudMenu[sh_colorhud_customcolor].status = status; } +#ifdef HWRENDER +void M_UpdateOGLMenu(void) +{ +#ifdef USE_FBO_OGL + OP_ExpOptionsMenu[op_exp_fbo].status = (!supportFBO || cv_glscreentextures.value != 2) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; +#endif + OP_ExpOptionsMenu[op_exp_paldepth].status = (!HWR_ShouldUsePaletteRendering()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; + + OP_OpenGLOptionsMenu[op_gl_falbckmdls].status = (!cv_glmdls.value) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; + + OP_OpenGLOptionsMenu[op_gl_lightdither].status = (!HWR_UseShader()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; + OP_OpenGLOptionsMenu[op_gl_secbright].status = (!HWR_UseShader()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; + + OP_OpenGLOptionsMenu[op_gl_palrender].status = (cv_glscreentextures.value != 2 || !HWR_UseShader()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; + OP_OpenGLOptionsMenu[op_gl_flashpal].status = (!HWR_ShouldUsePaletteRendering()) ? IT_GRAYEDOUT : IT_STRING | IT_CVAR; +} +#endif + + // ========================================================================== // END ORGANIZATION STUFF. // ========================================================================== @@ -3709,14 +3740,14 @@ boolean M_Responder(event_t *ev) tic_t thistime = I_GetTime(); if (ev->type == ev_joystick) { - const INT32 jxdeadzone = ((JOYAXISRANGE-1) * max(cv_xdeadzone.value, FRACUNIT/2)) >> FRACBITS; - const INT32 jydeadzone = ((JOYAXISRANGE-1) * max(cv_ydeadzone.value, FRACUNIT/2)) >> FRACBITS; - INT32 accelaxis = abs(cv_moveaxis.value); + const INT32 jxdeadzone = ((JOYAXISRANGE-1) * max(cv_xdeadzone[0].value, FRACUNIT/2)) >> FRACBITS; + const INT32 jydeadzone = ((JOYAXISRANGE-1) * max(cv_ydeadzone[0].value, FRACUNIT/2)) >> FRACBITS; + INT32 accelaxis = abs(cv_moveaxis[0].value); if (ev->data1 == 0) { if (ev->data3 != INT32_MAX) { - if (Joystick.bGamepadStyle || abs(ev->data3) > jydeadzone) + if (Joystick[0].bGamepadStyle || abs(ev->data3) > jydeadzone) { if (joywaity < thistime && (pjoyy == 0 || (ev->data3 < 0) != (pjoyy < 0))) // no previous direction OR change direction @@ -3732,7 +3763,7 @@ boolean M_Responder(event_t *ev) if (ev->data2 != INT32_MAX && joywaitx < thistime) { - if (Joystick.bGamepadStyle || abs(ev->data2) > jxdeadzone) + if (Joystick[0].bGamepadStyle || abs(ev->data2) > jxdeadzone) { if (joywaitx < thistime && (pjoyx == 0 || (ev->data2 < 0) != (pjoyx < 0))) // no previous direction OR change direction @@ -3760,10 +3791,10 @@ boolean M_Responder(event_t *ev) retaxis = xmode ? ev->data2 : ev->data3; if (retaxis != INT32_MAX) { - if (cv_moveaxis.value < 0) + if (cv_moveaxis[0].value < 0) retaxis = -retaxis; - if (Joystick.bGamepadStyle || retaxis > jacceldeadzone) + if (Joystick[0].bGamepadStyle || retaxis > jacceldeadzone) { if (joywaitaccel < thistime && retaxis > pjoyaccel) // only on upwards event { @@ -4320,9 +4351,9 @@ void M_Drawer(void) #ifdef HWRENDER if (rendermode == render_opengl) V_DrawThinString(0, 0, V_GREENMAP|V_SNAPTOTOP|V_SNAPTOLEFT|V_TRANSLUCENT|V_ALLOWLOWERCASE, ("Opengl")); -#endif +#endif if (rendermode == render_soft) - V_DrawThinString(0, 0, V_REDMAP|V_SNAPTOTOP|V_SNAPTOLEFT|V_TRANSLUCENT|V_ALLOWLOWERCASE, ("Software")); + V_DrawThinString(0, 0, V_REDMAP|V_SNAPTOTOP|V_SNAPTOLEFT|V_TRANSLUCENT|V_ALLOWLOWERCASE, ("Software")); } } } @@ -4413,18 +4444,18 @@ void M_StartControlPanel(void) MPauseMenu[mpause_psetup].status = IT_DISABLED; MISC_ChangeTeamMenu[0].status = IT_DISABLED; MISC_ChangeSpectateMenu[0].status = IT_DISABLED; - + MPauseMenu[mpause_addlocalskins].status = IT_STRING | IT_CALL; MPauseMenu[mpause_localskin].status = IT_STRING | IT_CALL; // Reset these in case splitscreen messes things up MPauseMenu[mpause_addons].alphaKey = 8; - + if (IsPlayerAdmin(consoleplayer)) MPauseMenu[mpause_addlocalskins].alphaKey = 16; else MPauseMenu[mpause_addlocalskins].alphaKey = 24; - + MPauseMenu[mpause_scramble].alphaKey = 8; MPauseMenu[mpause_switchmap].alphaKey = 24; @@ -4445,17 +4476,17 @@ void M_StartControlPanel(void) if (G_GametypeHasTeams()) MPauseMenu[mpause_scramble].status = IT_STRING | IT_SUBMENU; } - + if (server || (!cv_showlocalskinmenus.value)) { MPauseMenu[mpause_addlocalskins].status = IT_DISABLED; MPauseMenu[mpause_localskin].status = IT_DISABLED; - + MPauseMenu[mpause_options].alphaKey = 64; MPauseMenu[mpause_title].alphaKey = 80; MPauseMenu[mpause_quit].alphaKey = 88; } - + if (splitscreen) { @@ -4720,11 +4751,12 @@ void M_Init(void) if (rendermode == render_soft) { OP_VideoOptionsMenu[op_video_ogl].status = IT_DISABLED; - OP_ExpOptionsMenu[op_exp_grscrtx].status = IT_DISABLED; + + OP_ExpOptionsMenu[op_exp_glscrtx].status = IT_DISABLED; #ifdef USE_FBO_OGL OP_ExpOptionsMenu[op_exp_fbo].status = IT_DISABLED; #endif - OP_ExpOptionsMenu[op_exp_spltwal].status = IT_DISABLED; + OP_ExpOptionsMenu[op_exp_paldepth].status = IT_DISABLED; } if (rendermode == render_opengl) @@ -4733,15 +4765,25 @@ void M_Init(void) if (!supportFBO) OP_ExpOptionsMenu[op_exp_fbo].status = IT_GRAYEDOUT; #endif + if (!gl_shadersavailable) + { + OP_OpenGLOptionsMenu[op_gl_shader].status = IT_GRAYEDOUT; + OP_OpenGLOptionsMenu[op_gl_lightdither].status = IT_GRAYEDOUT; + OP_OpenGLOptionsMenu[op_gl_secbright].status = IT_GRAYEDOUT; + OP_OpenGLOptionsMenu[op_gl_palrender].status = IT_GRAYEDOUT; + OP_OpenGLOptionsMenu[op_gl_flashpal].status = IT_GRAYEDOUT; + + OP_ExpOptionsMenu[op_exp_paldepth].status = IT_GRAYEDOUT; + } } #endif if (!xtra_speedo && !kartzspeedo && !achi_speedo) // why bother? OP_SaturnHudMenu[sh_speedometer].status = IT_GRAYEDOUT; - + //if (!xtra_speedo && kartzspeedo) //OP_SaturnMenu[sm_speedometer].text = "Speedometer (No Small)"; - + //if (xtra_speedo && !kartzspeedo) //OP_SaturnMenu[sm_speedometer].text = "Speedometer (No PMeter)"; // idk i dont wanna bother with this tbh lmao @@ -4973,7 +5015,7 @@ static void M_CentreText(INT32 y, const char *string) INT32 x; //added : 02-02-98 : centre on 320, because V_DrawString centers on vid.width... x = (BASEVIDWIDTH - V_StringWidth(string, V_OLDSPACING))>>1; - V_DrawString(x,y,V_OLDSPACING,string); + V_DrawString(x,y,V_OLDSPACING|MENUCAPS,string); } // @@ -5077,7 +5119,7 @@ static void M_DrawSplitText(INT32 x, INT32 y, INT32 option, const char* str, INT yoffset = (((5*10 - num_lines*10))); // Draw BG first,,, - for (int i = 0; i < num_lines; i++) + for (int i = 0; i < num_lines; i++) { V_DrawFill(0, (y + yoffset - 6)+5, vid.width, 11, 239|V_SNAPTOBOTTOM|V_SNAPTOLEFT); yoffset += 11; @@ -5086,7 +5128,7 @@ static void M_DrawSplitText(INT32 x, INT32 y, INT32 option, const char* str, INT yoffset = (((5*10 - num_lines*10))); // THEN the text - for (int i = 0; i < num_lines; i++) + for (int i = 0; i < num_lines; i++) { V_DrawCenteredThinString(x, y + yoffset, option, clines[i]); V_DrawCenteredThinString(x, y + yoffset, option|V_YELLOWMAP|((9 - alpha) << V_ALPHASHIFT), clines[i]); @@ -5102,8 +5144,6 @@ static void M_DrawSplitText(INT32 x, INT32 y, INT32 option, const char* str, INT static void M_DrawGenericMenu(void) { INT32 x, y, w, i, cursory = 0; - - INT32 lowercase = !cv_menucaps.value ? V_ALLOWLOWERCASE : 0; // DRAW MENU x = currentMenu->x; @@ -5150,9 +5190,9 @@ static void M_DrawGenericMenu(void) cursory = y; if ((currentMenu->menuitems[i].status & IT_DISPLAY)==IT_STRING) - V_DrawString(x, y, lowercase, currentMenu->menuitems[i].text); + V_DrawString(x, y, MENUCAPS, currentMenu->menuitems[i].text); else - V_DrawString(x, y, lowercase|highlightflags, currentMenu->menuitems[i].text); + V_DrawString(x, y, MENUCAPS|highlightflags, currentMenu->menuitems[i].text); // Cvar specific handling switch (currentMenu->menuitems[i].status & IT_TYPE) @@ -5179,7 +5219,7 @@ static void M_DrawGenericMenu(void) default: w = V_StringWidth(cv->string, 0); V_DrawString(BASEVIDWIDTH - x - w, y, - ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? warningflags : highlightflags)|lowercase, cv->string); + ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? warningflags : highlightflags)|MENUCAPS, cv->string); if (i == itemOn) { V_DrawCharacter(BASEVIDWIDTH - x - 10 - w - (skullAnimCounter/5), y, @@ -5194,7 +5234,7 @@ static void M_DrawGenericMenu(void) y += STRINGHEIGHT; break; case IT_STRING2: - V_DrawString(((BASEVIDWIDTH - V_StringWidth(currentMenu->menuitems[i].text, 0))>>1), y, lowercase, currentMenu->menuitems[i].text); + V_DrawString(((BASEVIDWIDTH - V_StringWidth(currentMenu->menuitems[i].text, 0))>>1), y, MENUCAPS, currentMenu->menuitems[i].text); /* FALLTHRU */ case IT_DYLITLSPACE: y += SMALLLINEHEIGHT; @@ -5210,21 +5250,21 @@ static void M_DrawGenericMenu(void) y = currentMenu->y+currentMenu->menuitems[i].alphaKey; /* FALLTHRU */ case IT_TRANSTEXT2: - V_DrawString(x, y, V_TRANSLUCENT|lowercase, currentMenu->menuitems[i].text); + V_DrawString(x, y, V_TRANSLUCENT|MENUCAPS, currentMenu->menuitems[i].text); y += SMALLLINEHEIGHT; break; case IT_QUESTIONMARKS: if (currentMenu->menuitems[i].alphaKey) y = currentMenu->y+currentMenu->menuitems[i].alphaKey; - V_DrawString(x, y, V_TRANSLUCENT|V_OLDSPACING|lowercase, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); + V_DrawString(x, y, V_TRANSLUCENT|V_OLDSPACING|MENUCAPS, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); y += SMALLLINEHEIGHT; break; case IT_HEADERTEXT: // draws 16 pixels to the left, in yellow text if (currentMenu->menuitems[i].alphaKey) y = currentMenu->y+currentMenu->menuitems[i].alphaKey; - V_DrawString(x-16, y, highlightflags|lowercase, currentMenu->menuitems[i].text); + V_DrawString(x-16, y, highlightflags|MENUCAPS, currentMenu->menuitems[i].text); y += SMALLLINEHEIGHT; break; } @@ -5241,7 +5281,7 @@ static void M_DrawGenericMenu(void) { V_DrawScaledPatch(currentMenu->x - 24, cursory, 0, W_CachePatchName("M_CURSOR", PU_CACHE)); - V_DrawString(currentMenu->x, cursory, lowercase|highlightflags, currentMenu->menuitems[itemOn].text); + V_DrawString(currentMenu->x, cursory, MENUCAPS|highlightflags, currentMenu->menuitems[itemOn].text); } // dumb hack @@ -5318,8 +5358,6 @@ static void M_DrawGenericScrollMenu(void) // draw title (or big pic) M_DrawMenuTitle(); - - INT32 lowercase = !cv_menucaps.value ? V_ALLOWLOWERCASE : 0; for (; i < max; i++) { @@ -5337,9 +5375,9 @@ static void M_DrawGenericScrollMenu(void) case IT_STRING: case IT_WHITESTRING: if (i != itemOn && (currentMenu->menuitems[i].status & IT_DISPLAY)==IT_STRING) - V_DrawString(x, y, lowercase, currentMenu->menuitems[i].text); + V_DrawString(x, y, MENUCAPS, currentMenu->menuitems[i].text); else - V_DrawString(x, y, lowercase|highlightflags, currentMenu->menuitems[i].text); + V_DrawString(x, y, MENUCAPS|highlightflags, currentMenu->menuitems[i].text); // Cvar specific handling switch (currentMenu->menuitems[i].status & IT_TYPE) @@ -5361,12 +5399,12 @@ static void M_DrawGenericScrollMenu(void) if (itemOn == i) M_DrawTextInput(x + 8, y + 12, &menuinput, 0); else - V_DrawString(x + 8, y + 12, lowercase, cv->string); + V_DrawString(x + 8, y + 12, MENUCAPS, cv->string); break; default: V_DrawRightAlignedString(BASEVIDWIDTH - x, y, - ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? V_REDMAP : highlightflags)|lowercase, cv->string); + ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? V_REDMAP : highlightflags)|MENUCAPS, cv->string); if (i == itemOn) { V_DrawCharacter(BASEVIDWIDTH - x - 10 - V_StringWidth(cv->string, 0) - (skullAnimCounter/5), y, @@ -5380,13 +5418,13 @@ static void M_DrawGenericScrollMenu(void) } break; case IT_TRANSTEXT: - V_DrawString(x, y, V_TRANSLUCENT|lowercase, currentMenu->menuitems[i].text); + V_DrawString(x, y, V_TRANSLUCENT|MENUCAPS, currentMenu->menuitems[i].text); break; case IT_QUESTIONMARKS: - V_DrawString(x, y, lowercase|V_TRANSLUCENT|V_OLDSPACING, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); + V_DrawString(x, y, MENUCAPS|V_TRANSLUCENT|V_OLDSPACING, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); break; case IT_HEADERTEXT: - V_DrawString(x-16, y, highlightflags|lowercase, currentMenu->menuitems[i].text); + V_DrawString(x-16, y, highlightflags|MENUCAPS, currentMenu->menuitems[i].text); break; } } @@ -5440,8 +5478,6 @@ static void M_DrawCenteredMenu(void) // draw title (or big pic) M_DrawMenuTitle(); - - INT32 lowercase = !cv_menucaps.value ? V_ALLOWLOWERCASE : 0; for (i = 0; i < currentMenu->numitems; i++) { @@ -5481,9 +5517,9 @@ static void M_DrawCenteredMenu(void) cursory = y; if ((currentMenu->menuitems[i].status & IT_DISPLAY)==IT_STRING) - V_DrawCenteredString(x, y, lowercase, currentMenu->menuitems[i].text); + V_DrawCenteredString(x, y, MENUCAPS, currentMenu->menuitems[i].text); else - V_DrawCenteredString(x, y, highlightflags|lowercase, currentMenu->menuitems[i].text); + V_DrawCenteredString(x, y, highlightflags|MENUCAPS, currentMenu->menuitems[i].text); // Cvar specific handling switch(currentMenu->menuitems[i].status & IT_TYPE) @@ -5508,7 +5544,7 @@ static void M_DrawCenteredMenu(void) break; default: V_DrawString(BASEVIDWIDTH - x - V_StringWidth(cv->string, 0), y, - ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? warningflags : highlightflags)|lowercase, cv->string); + ((cv->flags & CV_CHEAT) && !CV_IsSetToDefault(cv) ? warningflags : highlightflags)|MENUCAPS, cv->string); break; } break; @@ -5516,7 +5552,7 @@ static void M_DrawCenteredMenu(void) y += STRINGHEIGHT; break; case IT_STRING2: - V_DrawCenteredString(x, y, lowercase, currentMenu->menuitems[i].text); + V_DrawCenteredString(x, y, MENUCAPS, currentMenu->menuitems[i].text); /* FALLTHRU */ case IT_DYLITLSPACE: y += SMALLLINEHEIGHT; @@ -5525,7 +5561,7 @@ static void M_DrawCenteredMenu(void) if (currentMenu->menuitems[i].alphaKey) y = currentMenu->y+currentMenu->menuitems[i].alphaKey; - V_DrawCenteredString(x, y, V_TRANSLUCENT|V_OLDSPACING|lowercase, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); + V_DrawCenteredString(x, y, V_TRANSLUCENT|V_OLDSPACING|MENUCAPS, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); y += SMALLLINEHEIGHT; break; case IT_GRAYPATCH: @@ -5548,7 +5584,7 @@ static void M_DrawCenteredMenu(void) { V_DrawScaledPatch(x - V_StringWidth(currentMenu->menuitems[itemOn].text, 0)/2 - 24, cursory, 0, W_CachePatchName("M_CURSOR", PU_CACHE)); - V_DrawCenteredString(x, cursory, highlightflags|lowercase, currentMenu->menuitems[itemOn].text); + V_DrawCenteredString(x, cursory, highlightflags|MENUCAPS, currentMenu->menuitems[itemOn].text); } } @@ -5924,12 +5960,12 @@ static void M_DrawImageDef(void) { INT32 x = BASEVIDWIDTH>>1, y = (BASEVIDHEIGHT>>1) - 4; x += (itemOn ? 1 : -1)*((BASEVIDWIDTH>>2) + 10); - V_DrawCenteredString(x, y-10, highlightflags, "USE ARROW KEYS"); + V_DrawCenteredString(x, y-10, highlightflags|MENUCAPS, "Use arrow keys"); V_DrawCharacter(x - 10 - (skullAnimCounter/5), y, '\x1C' | highlightflags, false); // left arrow V_DrawCharacter(x + 2 + (skullAnimCounter/5), y, '\x1D' | highlightflags, false); // right arrow - V_DrawCenteredString(x, y+10, highlightflags, "TO LEAF THROUGH"); + V_DrawCenteredString(x, y+10, highlightflags|MENUCAPS, "to leaf through"); } } @@ -6327,16 +6363,14 @@ static void M_DrawAddons(void) y = BASEVIDHEIGHT - currentMenu->y + 1; M_DrawTextBox(x - (21 + 5), y, MAXSTRINGLENGTH, 1); - if (menusearch[0]) - V_DrawString(x - 18, y + 8, V_ALLOWLOWERCASE, menusearch+1); + + if (menusearch.length) + M_DrawTextInput(x - 18, y + 8, &menusearch, 0); else V_DrawString(x - 18, y + 8, V_ALLOWLOWERCASE|V_TRANSLUCENT, "Type to search..."); - if (skullAnimCounter < 4) - V_DrawCharacter(x - 18 + V_StringWidth(menusearch+1, 0), y + 8, - '_' | 0x80, false); x -= (21 + 5 + 16); - V_DrawSmallScaledPatch(x, y + 4, (menusearch[0] ? 0 : V_TRANSLUCENT), addonsp[NUM_EXT+3]); + V_DrawSmallScaledPatch(x, y + 4, (menusearch.length ? 0 : V_TRANSLUCENT), addonsp[NUM_EXT+3]); x = BASEVIDWIDTH - x - 16; V_DrawSmallScaledPatch(x, y + 4, ((!majormods) ? 0 : V_TRANSLUCENT), addonsp[NUM_EXT+4]); @@ -6369,7 +6403,7 @@ static void M_AddonAutoLoad(INT32 ch) S_StartSound(NULL, sfx_s26d); return; } - + // first, find the file // path = va("%s"PATHSEP"%s", srb2home, AUTOLOADCONFIGFILENAME); autoloadconfigfile = fopen(path, "a"); @@ -6384,7 +6418,7 @@ static void M_AddonAutoLoad(INT32 ch) case EXT_CFG: CONS_Printf("Added the \x82%s\x80 console script to the autoload configuration list.\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); fprintf(autoloadconfigfile, "%s\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); - + S_StartSound(NULL, sfx_s221); break; case EXT_LUA: @@ -6397,7 +6431,7 @@ static void M_AddonAutoLoad(INT32 ch) { CONS_Printf("Added \x82%s\x80 to the autoload configuration list.\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); fprintf(autoloadconfigfile, "%s\n", dirmenu[dir_on[menudepthleft]]+DIR_STRING); - + S_StartSound(NULL, sfx_s221); } else @@ -6407,48 +6441,11 @@ static void M_AddonAutoLoad(INT32 ch) } break; } - + // lastly, do some last things and close the autoload config file // fclose(autoloadconfigfile); } -#define len menusearch[0] -static boolean M_ChangeStringAddons(INT32 choice) -{ - choice = M_ShiftChar(choice); - - switch (choice) - { - case KEY_DEL: - if (len) - { - len = menusearch[1] = 0; - return true; - } - break; - case KEY_BACKSPACE: - if (len) - { - menusearch[1+--len] = 0; - return true; - } - break; - default: - if (choice >= 32 && choice <= 127) - { - if (len < MAXSTRINGLENGTH - 1) - { - menusearch[1+len++] = (char)choice; - menusearch[1+len] = 0; - return true; - } - } - break; - } - return false; -} -#undef len - // i hate myself static boolean DumbStartsWith(const char *pre, const char *str) { @@ -6461,8 +6458,10 @@ static void M_HandleAddons(INT32 choice) { boolean exitmenu = false; // exit to previous menu - if (M_ChangeStringAddons(choice)) + if (M_TextInputHandle(&menusearch, choice)) { + S_StartSound(NULL,sfx_menu1); + char *tempname = NULL; if (dirmenu && dirmenu[dir_on[menudepthleft]]) tempname = Z_StrDup(dirmenu[dir_on[menudepthleft]]+DIR_STRING); // don't need to I_Error if can't make - not important, just QoL @@ -6611,7 +6610,7 @@ static void M_HandleAddons(INT32 choice) || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, AUTOLOADCONFIGFILENAME) == 0) || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartserv.cfg") == 0) || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartexec.cfg") == 0)) - { + { M_StartMessage(va("%c%s\x80\nYou can't autoload this builds' base console scripts, silly!\n They're already autoloaded on startup! \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); S_StartSound(NULL, sfx_s26d); } @@ -7054,11 +7053,11 @@ static void DrawReplayHutReplayInfo(void) switch (demolist[dir_on[menudepthleft]].type) { case MD_NOTLOADED: - V_DrawCenteredString(160, 40, V_SNAPTOTOP, "Loading replay information..."); + V_DrawCenteredString(160, 40, V_SNAPTOTOP|MENUCAPS, "Loading replay information..."); break; case MD_INVALID: - V_DrawCenteredString(160, 40, V_SNAPTOTOP|warningflags, "This replay cannot be played."); + V_DrawCenteredString(160, 40, V_SNAPTOTOP|warningflags|MENUCAPS, "This replay cannot be played."); break; case MD_SUBDIR: @@ -7100,7 +7099,7 @@ static void DrawReplayHutReplayInfo(void) if (mapheaderinfo[demolist[dir_on[menudepthleft]].map-1]) { char *title = G_BuildMapTitle(demolist[dir_on[menudepthleft]].map); - V_DrawString(x, y, V_SNAPTOTOP, title); + V_DrawString(x, y, V_SNAPTOTOP|MENUCAPS, title); Z_Free(title); } else @@ -7117,26 +7116,24 @@ static void DrawReplayHutReplayInfo(void) { // No standings were loaded! V_DrawString(x, y+39, V_SNAPTOTOP|V_ALLOWLOWERCASE|V_TRANSLUCENT, "No standings available."); - - break; } - V_DrawThinString(x, y+29, V_SNAPTOTOP|highlightflags, "WINNER"); + V_DrawThinString(x, y+29, V_SNAPTOTOP|highlightflags|MENUCAPS, "Winner"); V_DrawString(x+38, y+30, V_SNAPTOTOP|V_ALLOWLOWERCASE, demolist[dir_on[menudepthleft]].standings[0].name); if (demolist[dir_on[menudepthleft]].gametype == GT_RACE) { - V_DrawThinString(x, y+39, V_SNAPTOTOP|highlightflags, "TIME"); + V_DrawThinString(x, y+39, V_SNAPTOTOP|highlightflags|MENUCAPS, "Time"); } else { - V_DrawThinString(x, y+39, V_SNAPTOTOP|highlightflags, "SCORE"); + V_DrawThinString(x, y+39, V_SNAPTOTOP|highlightflags|MENUCAPS, "Score"); } if (demolist[dir_on[menudepthleft]].standings[0].timeorscore == (UINT32_MAX-1)) { - V_DrawThinString(x+32, y+40-1, V_SNAPTOTOP, "NO CONTEST"); + V_DrawThinString(x+32, y+40-1, V_SNAPTOTOP|MENUCAPS, "No Contest"); } else if (demolist[dir_on[menudepthleft]].gametype == GT_RACE) { @@ -7344,7 +7341,7 @@ static void M_DrawReplayHut(void) static void M_DrawReplayStartMenu(void) { - const char *warning; + const char *warning = ""; UINT8 i; M_DrawGenericBackgroundMenu(); @@ -7447,7 +7444,8 @@ static void M_DrawReplayStartMenu(void) return; } - V_DrawSmallString(4, BASEVIDHEIGHT-14, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, warning); + if (warning) + V_DrawSmallString(4, BASEVIDHEIGHT-14, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, warning); } static boolean M_QuitReplayHut(void) @@ -7882,7 +7880,7 @@ static void M_Options(INT32 choice) OP_MainMenu[5].status = OP_MainMenu[6].status = (Playing() && !(server || IsPlayerAdmin(consoleplayer))) ? (IT_GRAYEDOUT) : (IT_STRING|IT_SUBMENU); OP_MainMenu[10].status = (Playing()) ? (IT_GRAYEDOUT) : (IT_STRING|IT_CALL); // Play credits - + OP_MainMenu[13].status = (!cv_showlocalskinmenus.value) ? (IT_DISABLED) : (IT_CALL|IT_STRING); #ifdef HAVE_DISCORDRPC @@ -8142,7 +8140,7 @@ static void M_DrawChecklist(void) ++line; secretname = M_CreateSecretMenuOption(unlockables[i].name); - V_DrawString(8, (line*8), V_RETURN8|(unlockables[i].unlocked ? recommendedflags : warningflags), (secret ? secretname : unlockables[i].name)); + V_DrawString(8, (line*8), V_RETURN8|MENUCAPS|(unlockables[i].unlocked ? recommendedflags : warningflags), (secret ? secretname : unlockables[i].name)); if (conditionSets[unlockables[i].conditionset - 1].numconditions) { @@ -8456,14 +8454,14 @@ static void M_DrawMusicTest(void) if (curplaying && curplaying->authors[0]) V_DrawRightAlignedThinString(BASEVIDWIDTH-16, 46, V_ALLOWLOWERCASE, curplaying->authors); - + if (curplaying) { if (!curplaying->usage[0]) V_DrawString(vid.dupx, vid.height - 10*vid.dupy, V_NOSCALESTART|V_ALLOWLOWERCASE, va("%.6s", curplaying->name)); else V_DrawSmallString(vid.dupx, vid.height - 5*vid.dupy, V_NOSCALESTART|V_ALLOWLOWERCASE, va("%.6s - %.255s\n", curplaying->name, curplaying->usage)); - + if (cv_showmusicfilename.value) V_DrawSmallString(0, 0, V_SNAPTOTOP|V_SNAPTOLEFT|V_ALLOWLOWERCASE, curplaying->filename); } @@ -8609,7 +8607,7 @@ static void M_HandleMusicTest(INT32 choice) case KEY_ENTER: S_StopSounds(); S_StopMusic(); - curplaying = soundtestdefs[st_sel]; + curplaying = soundtestdefs[st_sel]; S_ChangeMusicInternal(curplaying->name, true); break; @@ -8700,8 +8698,8 @@ static void M_DrawStatsMaps(int location) } else if (dotopname) { - V_DrawString(20, y, highlightflags, "LEVEL NAME"); - V_DrawString(256, y, highlightflags, "MEDALS"); + V_DrawString(20, y, highlightflags|MENUCAPS, "Level name"); + V_DrawString(256, y, highlightflags|MENUCAPS, "Medals"); y += 8; dotopname = false; } @@ -8710,11 +8708,11 @@ static void M_DrawStatsMaps(int location) M_DrawMapEmblems(mnum+1, 295, y); if (mapheaderinfo[mnum]->levelflags & LF_NOZONE) - V_DrawString(20, y, 0, va("%s %s", + V_DrawString(20, y, MENUCAPS, va("%s %s", mapheaderinfo[mnum]->lvlttl, mapheaderinfo[mnum]->actnum)); else - V_DrawString(20, y, 0, va("%s %s %s", + V_DrawString(20, y, MENUCAPS, va("%s %s %s", mapheaderinfo[mnum]->lvlttl, (mapheaderinfo[mnum]->zonttl[0] ? mapheaderinfo[mnum]->zonttl : "Zone"), mapheaderinfo[mnum]->actnum)); @@ -8726,8 +8724,8 @@ static void M_DrawStatsMaps(int location) } if (dotopname && !location) { - V_DrawString(20, y, highlightflags, "LEVEL NAME"); - V_DrawString(256, y, highlightflags, "MEDALS"); + V_DrawString(20, y, highlightflags|MENUCAPS, "Level name"); + V_DrawString(256, y, highlightflags|MENUCAPS, "Medals"); y += 8; } else if (location) @@ -8738,7 +8736,7 @@ static void M_DrawStatsMaps(int location) { if (i == -1) { - V_DrawString(20, y, highlightflags, "EXTRA MEDALS"); + V_DrawString(20, y, highlightflags|MENUCAPS, "Extra medals"); if (location) { y += 8; @@ -8761,7 +8759,7 @@ static void M_DrawStatsMaps(int location) else V_DrawSmallScaledPatch(295, y, 0, W_CachePatchName("NEEDIT", PU_CACHE)); - V_DrawString(20, y, 0, va("%s", exemblem->description)); + V_DrawString(20, y, MENUCAPS, va("%s", exemblem->description)); } y += 8; @@ -8786,13 +8784,13 @@ static void M_DrawLevelStats(void) M_DrawMenuTitle(); - V_DrawString(20, 24, highlightflags, "Total Play Time:"); - V_DrawCenteredString(BASEVIDWIDTH/2, 32, 0, va("%i hours, %i minutes, %i seconds", + V_DrawString(20, 24, highlightflags|MENUCAPS, "Total Play Time:"); + V_DrawCenteredString(BASEVIDWIDTH/2, 32, MENUCAPS, va("%i hours, %i minutes, %i seconds", G_TicsToHours(totalplaytime), G_TicsToMinutes(totalplaytime, false), G_TicsToSeconds(totalplaytime))); - V_DrawString(20, 42, highlightflags, "Total Matches:"); - V_DrawRightAlignedString(BASEVIDWIDTH-16, 42, 0, va("%i played", matchesplayed)); + V_DrawString(20, 42, highlightflags|MENUCAPS, "Total Matches:"); + V_DrawRightAlignedString(BASEVIDWIDTH-16, 42, MENUCAPS, va("%i played", matchesplayed)); for (i = 0; i < NUMMAPS; i++) { @@ -8808,17 +8806,17 @@ static void M_DrawLevelStats(void) besttime += mainrecords[i]->time; } - V_DrawString(20, 62, highlightflags, "Combined time records:"); + V_DrawString(20, 62, highlightflags|MENUCAPS, "Combined time records:"); sprintf(beststr, "%i:%02i:%02i.%02i", G_TicsToHours(besttime), G_TicsToMinutes(besttime, false), G_TicsToSeconds(besttime), G_TicsToCentiseconds(besttime)); V_DrawRightAlignedString(BASEVIDWIDTH-16, 62, (mapsunfinished ? warningflags : 0), beststr); if (mapsunfinished) - V_DrawRightAlignedString(BASEVIDWIDTH-16, 70, warningflags, va("(%d unfinished)", mapsunfinished)); + V_DrawRightAlignedString(BASEVIDWIDTH-16, 70, warningflags|MENUCAPS, va("(%d unfinished)", mapsunfinished)); else - V_DrawRightAlignedString(BASEVIDWIDTH-16, 70, recommendedflags, "(complete)"); + V_DrawRightAlignedString(BASEVIDWIDTH-16, 70, recommendedflags|MENUCAPS, "(complete)"); - V_DrawString(32, 70, 0, va("x %d/%d", M_CountEmblems(), numemblems+numextraemblems)); + V_DrawString(32, 70, MENUCAPS, va("x %d/%d", M_CountEmblems(), numemblems+numextraemblems)); V_DrawSmallScaledPatch(20, 70, 0, W_CachePatchName("GOTITA", PU_STATIC)); M_DrawStatsMaps(statsLocation); @@ -8906,7 +8904,7 @@ void M_DrawTimeAttackMenu(void) if (i == itemOn) cursory = y; - V_DrawString(x, y, (dispstatus == IT_WHITESTRING) ? highlightflags : 0 , currentMenu->menuitems[i].text); + V_DrawString(x, y, ((dispstatus == IT_WHITESTRING) ? highlightflags : 0)|MENUCAPS, currentMenu->menuitems[i].text); // Cvar specific handling if ((currentMenu->menuitems[i].status & IT_TYPE) == IT_CVAR) @@ -8931,7 +8929,7 @@ void M_DrawTimeAttackMenu(void) soffset = 0; // Should see nothing but strings - V_DrawString(BASEVIDWIDTH - x - soffset - strw, y, highlightflags, str); + V_DrawString(BASEVIDWIDTH - x - soffset - strw, y, highlightflags|MENUCAPS, str); if (i == itemOn) { @@ -8961,7 +8959,7 @@ void M_DrawTimeAttackMenu(void) // DRAW THE SKULL CURSOR V_DrawScaledPatch(x - 24, cursory, 0, W_CachePatchName("M_CURSOR", PU_CACHE)); - V_DrawString(x, cursory, highlightflags, currentMenu->menuitems[itemOn].text); + V_DrawString(x, cursory, highlightflags|MENUCAPS, currentMenu->menuitems[itemOn].text); // Level record list if (cv_nextmap.value) @@ -8976,10 +8974,10 @@ void M_DrawTimeAttackMenu(void) V_DrawFill((BASEVIDWIDTH - dupadjust)>>1, 78, dupadjust, 36, 239); - V_DrawRightAlignedString(149, 80, highlightflags, "BEST LAP:"); + V_DrawRightAlignedString(149, 80, highlightflags|MENUCAPS, "Best Lap:"); K_drawKartTimestamp(lap, 19, 86, 0, 2); - V_DrawRightAlignedString(292, 80, highlightflags, "BEST TIME:"); + V_DrawRightAlignedString(292, 80, highlightflags|MENUCAPS, "Best Time:"); K_drawKartTimestamp(time, 162, 86, cv_nextmap.value, 1); } @@ -8991,7 +8989,7 @@ void M_DrawTimeAttackMenu(void) for (i = 0; i < 4; ++i) { y = currentMenu->y+SP_TimeAttackMenu[i].alphaKey; - V_DrawString(x, y, V_TRANSLUCENT, SP_TimeAttackMenu[i].text); + V_DrawString(x, y, V_TRANSLUCENT|MENUCAPS, SP_TimeAttackMenu[i].text); ncv = (consvar_t *)SP_TimeAttackMenu[i].itemaction; if (SP_TimeAttackMenu[i].status & IT_CV_STRING) { @@ -9008,7 +9006,7 @@ void M_DrawTimeAttackMenu(void) soffset = 0; // Should see nothing but strings - V_DrawString(BASEVIDWIDTH - x - soffset - strw, y, highlightflags|V_TRANSLUCENT, str); + V_DrawString(BASEVIDWIDTH - x - soffset - strw, y, highlightflags|V_TRANSLUCENT|MENUCAPS, str); } } } @@ -9474,10 +9472,10 @@ static void M_Connect(INT32 choice) { // do not call menuexitfunc M_ClearMenus(false); - + CV_Set(&cv_lastserver, I_GetNodeAddress(serverlist[choice-FIRSTSERVERLINE + serverlistpage * SERVERS_PER_PAGE].node)); - - COM_BufAddText(va("connect node %d\n", serverlist[choice-FIRSTSERVERLINE + serverlistpage * SERVERS_PER_PAGE].node)); + + COM_BufAddText(va("connect node %d\n", serverlist[choice-FIRSTSERVERLINE + serverlistpage * SERVERS_PER_PAGE].node)); } static void M_Refresh(INT32 choice) @@ -9723,7 +9721,7 @@ void M_SortServerList(void) #ifndef NONET #ifdef UPDATE_ALERT -#ifdef MASTERSERVER +#ifdef MASTERSERVER static void M_CheckMODVersion(int id) { char updatestring[500]; @@ -9998,9 +9996,9 @@ static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade) const char *item2 = gamecontrol[gc_fire][1] != 0 ? G_KeynumToString(gamecontrol[gc_fire][1]) : NULL; if (item1 != NULL && item2 != NULL) - snprintf(encoretoggle, 32, "%s/%s: Toggle Encore", item1, item2); + snprintf(encoretoggle, 32, "%s/%s - Toggle Encore", item1, item2); else - snprintf(encoretoggle, 32, "%s: Toggle Encore", item1 != NULL ? item1 : item2 != NULL ? item2 : "Item"); + snprintf(encoretoggle, 32, "%s - Toggle Encore", item1 != NULL ? item1 : item2 != NULL ? item2 : "Item"); V_DrawThinString(1, BASEVIDHEIGHT-8-1, V_SNAPTOLEFT|V_SNAPTOBOTTOM|V_TRANSLUCENT|V_ALLOWLOWERCASE, encoretoggle); } @@ -10038,10 +10036,10 @@ static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade) len = strlen(addonname); #define charsonside 14 if (len > charlimit) - V_DrawThinString(x+w+5, y+i-8, V_TRANSLUCENT, va("%.*s...%s", charsonside, addonname, addonname+((len-charlimit) + charsonside))); // variable reuse... + V_DrawThinString(x+w+5, y+i-8, V_TRANSLUCENT|MENUCAPS, va("%.*s...%s", charsonside, addonname, addonname+((len-charlimit) + charsonside))); // variable reuse... #undef charsonside else - V_DrawThinString(x+w+5, y+i-8, V_TRANSLUCENT, addonname); // variable reuse... + V_DrawThinString(x+w+5, y+i-8, V_TRANSLUCENT|MENUCAPS, addonname); // variable reuse... } if (!cv_kartencore.value || gamestate == GS_TIMEATTACK || cv_newgametype.value != GT_RACE) @@ -10223,19 +10221,17 @@ static void M_DrawMPMainMenu(void) // use generic drawer for cursor, items and title M_DrawGenericMenu(); - - INT32 lowercase = !cv_menucaps.value ? V_ALLOWLOWERCASE : 0; #ifndef NONET #if MAXPLAYERS != 16 Update the maxplayers label... #endif V_DrawRightAlignedString(BASEVIDWIDTH-x, y+MP_MainMenu[4].alphaKey, - ((itemOn == 4) ? highlightflags : 0)|lowercase, "(2-16 Players)"); + ((itemOn == 4) ? highlightflags : 0)|MENUCAPS, "(2-16 Players)"); #endif V_DrawRightAlignedString(BASEVIDWIDTH-x, y+MP_MainMenu[5].alphaKey, - ((itemOn == 5) ? highlightflags : 0)|lowercase, + ((itemOn == 5) ? highlightflags : 0)|MENUCAPS, "(2-4 players)" ); @@ -10430,7 +10426,7 @@ static void M_ConnectLastServer(INT32 choice) } M_ClearMenus(true); - COM_BufAddText(va("connect \"%s\"\n", cv_lastserver.string)); + COM_BufAddText(va("connect \"%s\"\n", cv_lastserver.string)); } // Tails 11-19-2002 @@ -10601,11 +10597,11 @@ static void M_DrawSetupMultiPlayerMenu(void) statoffset = 0; tw = V_StringWidth("Character", 0);//V_StringWidth(GETSELECTEDSKINNAME, 0); st = V_StringWidth(GETSELECTEDSKINNAME, 0); - + INT32 selectedskin = (itemOn == 1 && setupm_skinselect < numskins ? skinsorted[setupm_skinselect] : setupm_fakeskin); speed = skins[selectedskin].kartspeed; - weight = skins[selectedskin].kartweight; - + weight = skins[selectedskin].kartweight; + V_DrawString((mx+(tw/2)) - (st/2), my + 37, ((MP_PlayerSetupMenu[2].status & IT_TYPE) == IT_SPACE ? V_TRANSLUCENT : 0) | highlightflags | V_ALLOWLOWERCASE, GETSELECTEDSKINNAME); @@ -10613,7 +10609,7 @@ static void M_DrawSetupMultiPlayerMenu(void) statoffset = 50; else statoffset = 113; - + V_DrawString(statx - statoffset, staty - 10, V_6WIDTHSPACE, va("\x84%dS \x87%dW", GETSELECTEDSPEED, GETSELECTEDWEIGHT)); #undef GETSELECTEDSKINNAME #undef GETSELECTEDSPEED @@ -10678,7 +10674,7 @@ static void M_DrawSetupMultiPlayerMenu(void) V_DrawCharacter(mx + 2 + st + (skullAnimCounter/5), my + 164, '\x1D' | highlightflags, false); // right arrow } - break; + break; case SKINMENUTYPE_GRID: case SKINMENUTYPE_2D: V_DrawString(mx, my + 152, highlightflags | V_ALLOWLOWERCASE, KartColor_Names[setupm_fakecolor]); // SRB2kart @@ -10722,8 +10718,8 @@ static void M_DrawSetupMultiPlayerMenu(void) { //Background V_DrawScaledPatch(statx - 50, staty + 4, 0, W_CachePatchName("K_STATNB", PU_CACHE)); - - //Speed + + //Speed for (i = 0; i < GETSELECTEDSPEED; i++) // draw the stat bars { if (i == 0) @@ -10733,11 +10729,11 @@ static void M_DrawSetupMultiPlayerMenu(void) else V_DrawScaledPatch(statx - 45, staty + 63 -(5 *i), 0, W_CachePatchName("K_STATN2", PU_CACHE)); } - + //Weight for (i = 0; i < GETSELECTEDWEIGHT; i++) // draw the stat bars { - + if (i == 0) V_DrawScaledPatch(statx - 30, staty + 63, 0, W_CachePatchName("K_STATN4", PU_CACHE)); else if (i == GETSELECTEDWEIGHT -1) @@ -11013,10 +11009,10 @@ static void M_DrawSetupMultiPlayerMenu(void) #define indexwidth 8 { INT32 colwidth = ((BASEVIDWIDTH-(2*mx))-charw)/(2*indexwidth); - + if (cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED) colwidth = colwidth - 10; - + INT32 j = -colwidth; INT16 col = setupm_fakecolor - colwidth; INT32 x = mx; @@ -11150,7 +11146,7 @@ static void M_DrawSetupMultiPlayerMenu(void) frame = 0; // Try to use standing frame sprframe = &sprdef->spriteframes[frame]; - + //minenice's speen css, it's a piece of shit but hey //patch = W_CachePatchNum(sprframe->lumppat[1], PU_CACHE); speenframe = (I_GetTime()*cv_skinselectspin.value/TICRATE + 1)%8; @@ -11220,7 +11216,7 @@ static void M_HandleSetupMultiPlayer(INT32 choice) if (setupm_skinselect < ROUNDSKINSUPTO8 - SKINGRIDWIDTH) //if we arent at the bottom of the menu { setupm_skinselect += SKINGRIDWIDTH; - + if (cv_skinselectmenu.value == SKINMENUTYPE_GRID){ if (setupm_skinselect >= ((setupm_skinypos-1)+SKINGRIDHEIGHT)*8 && setupm_skinypos < (ROUNDSKINSUPTO8/8)-SKINGRIDHEIGHT) setupm_skinypos++; @@ -11293,9 +11289,9 @@ static void M_HandleSetupMultiPlayer(INT32 choice) else if (cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED){ setupm_skinypos = (((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)-2) > 0 ? ((numskins / SKINGRIDWIDTH) - (SKINGRIDHEIGHT-1)-2) : 0); M_PrevOpt(); - + } - + } else M_PrevOpt(); @@ -11756,7 +11752,7 @@ static boolean M_QuitMultiPlayerMenu(void) } // you know what? always putting these in the buffer won't hurt anything. COM_BufAddText (va("%s \"%s\"\n",setupm_cvskin->name,skins[setupm_fakeskin].name)); - COM_BufAddText (va("%s %d\n",setupm_cvcolor->name,setupm_fakecolor)); + COM_BufAddText (va("%s %d\n",setupm_cvcolor->name,setupm_fakecolor)); return true; } @@ -11841,30 +11837,30 @@ static void M_DrawJoystick(void) //M_DrawSaveLoadBorder(OP_JoystickSetDef.x, OP_JoystickSetDef.y+LINEHEIGHT*i); #ifdef JOYSTICK_HOTPLUG - if (atoi(cv_usejoystick4.string) > I_NumJoys()) - compareval4 = atoi(cv_usejoystick4.string); + if (atoi(cv_usejoystick[3].string) > I_NumJoys()) + compareval4 = atoi(cv_usejoystick[3].string); else - compareval4 = cv_usejoystick4.value; + compareval4 = cv_usejoystick[3].value; - if (atoi(cv_usejoystick3.string) > I_NumJoys()) - compareval3 = atoi(cv_usejoystick3.string); + if (atoi(cv_usejoystick[2].string) > I_NumJoys()) + compareval3 = atoi(cv_usejoystick[2].string); else - compareval3 = cv_usejoystick3.value; + compareval3 = cv_usejoystick[2].value; - if (atoi(cv_usejoystick2.string) > I_NumJoys()) - compareval2 = atoi(cv_usejoystick2.string); + if (atoi(cv_usejoystick[1].string) > I_NumJoys()) + compareval2 = atoi(cv_usejoystick[1].string); else - compareval2 = cv_usejoystick2.value; + compareval2 = cv_usejoystick[1].value; - if (atoi(cv_usejoystick.string) > I_NumJoys()) - compareval = atoi(cv_usejoystick.string); + if (atoi(cv_usejoystick[0].string) > I_NumJoys()) + compareval = atoi(cv_usejoystick[0].string); else - compareval = cv_usejoystick.value; + compareval = cv_usejoystick[0].value; #else - compareval4 = cv_usejoystick4.value; - compareval3 = cv_usejoystick3.value; - compareval2 = cv_usejoystick2.value; - compareval = cv_usejoystick.value; + compareval4 = cv_usejoystick[3].value; + compareval3 = cv_usejoystick[2].value; + compareval2 = cv_usejoystick[1].value; + compareval = cv_usejoystick[0].value; #endif if ((setupcontrolplayer == 4 && (i == compareval4)) @@ -11902,14 +11898,14 @@ void M_SetupJoystickMenu(INT32 choice) // // Update cv_usejoystick.string here so that the user can // properly change this value. - if (i == cv_usejoystick.value) - CV_SetValue(&cv_usejoystick, i); - if (i == cv_usejoystick2.value) - CV_SetValue(&cv_usejoystick2, i); - if (i == cv_usejoystick3.value) - CV_SetValue(&cv_usejoystick3, i); - if (i == cv_usejoystick4.value) - CV_SetValue(&cv_usejoystick4, i); + if (i == cv_usejoystick[0].value) + CV_SetValue(&cv_usejoystick[0], i); + if (i == cv_usejoystick[1].value) + CV_SetValue(&cv_usejoystick[1], i); + if (i == cv_usejoystick[2].value) + CV_SetValue(&cv_usejoystick[2], i); + if (i == cv_usejoystick[3].value) + CV_SetValue(&cv_usejoystick[3], i); #endif } @@ -11952,27 +11948,27 @@ static void M_AssignJoystick(INT32 choice) if (setupcontrolplayer == 4) { - oldchoice = oldstringchoice = atoi(cv_usejoystick4.string) > numjoys ? atoi(cv_usejoystick4.string) : cv_usejoystick4.value; - CV_SetValue(&cv_usejoystick4, choice); + oldchoice = oldstringchoice = atoi(cv_usejoystick[3].string) > numjoys ? atoi(cv_usejoystick[3].string) : cv_usejoystick[3].value; + CV_SetValue(&cv_usejoystick[3], choice); // Just in case last-minute changes were made to cv_usejoystick.value, // update the string too // But don't do this if we're intentionally setting higher than numjoys if (choice <= numjoys) { - CV_SetValue(&cv_usejoystick4, cv_usejoystick4.value); + CV_SetValue(&cv_usejoystick[3], cv_usejoystick[3].value); // reset this so the comparison is valid if (oldchoice > numjoys) - oldchoice = cv_usejoystick4.value; + oldchoice = cv_usejoystick[3].value; if (oldchoice != choice) { if (choice && oldstringchoice > numjoys) // if we did not select "None", we likely selected a used device - CV_SetValue(&cv_usejoystick4, (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); + CV_SetValue(&cv_usejoystick[3], (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); if (oldstringchoice == - (atoi(cv_usejoystick4.string) > numjoys ? atoi(cv_usejoystick4.string) : cv_usejoystick4.value)) + (atoi(cv_usejoystick[3].string) > numjoys ? atoi(cv_usejoystick[3].string) : cv_usejoystick[3].value)) M_StartMessage("This joystick is used by another\n" "player. Reset the joystick\n" "for that player first.\n\n" @@ -11982,27 +11978,27 @@ static void M_AssignJoystick(INT32 choice) } else if (setupcontrolplayer == 3) { - oldchoice = oldstringchoice = atoi(cv_usejoystick3.string) > numjoys ? atoi(cv_usejoystick3.string) : cv_usejoystick3.value; - CV_SetValue(&cv_usejoystick3, choice); + oldchoice = oldstringchoice = atoi(cv_usejoystick[2].string) > numjoys ? atoi(cv_usejoystick[2].string) : cv_usejoystick[2].value; + CV_SetValue(&cv_usejoystick[2], choice); // Just in case last-minute changes were made to cv_usejoystick.value, // update the string too // But don't do this if we're intentionally setting higher than numjoys if (choice <= numjoys) { - CV_SetValue(&cv_usejoystick3, cv_usejoystick3.value); + CV_SetValue(&cv_usejoystick[2], cv_usejoystick[2].value); // reset this so the comparison is valid if (oldchoice > numjoys) - oldchoice = cv_usejoystick3.value; + oldchoice = cv_usejoystick[2].value; if (oldchoice != choice) { if (choice && oldstringchoice > numjoys) // if we did not select "None", we likely selected a used device - CV_SetValue(&cv_usejoystick3, (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); + CV_SetValue(&cv_usejoystick[2], (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); if (oldstringchoice == - (atoi(cv_usejoystick3.string) > numjoys ? atoi(cv_usejoystick3.string) : cv_usejoystick3.value)) + (atoi(cv_usejoystick[2].string) > numjoys ? atoi(cv_usejoystick[2].string) : cv_usejoystick[2].value)) M_StartMessage("This joystick is used by another\n" "player. Reset the joystick\n" "for that player first.\n\n" @@ -12012,27 +12008,27 @@ static void M_AssignJoystick(INT32 choice) } else if (setupcontrolplayer == 2) { - oldchoice = oldstringchoice = atoi(cv_usejoystick2.string) > numjoys ? atoi(cv_usejoystick2.string) : cv_usejoystick2.value; - CV_SetValue(&cv_usejoystick2, choice); + oldchoice = oldstringchoice = atoi(cv_usejoystick[1].string) > numjoys ? atoi(cv_usejoystick[1].string) : cv_usejoystick[1].value; + CV_SetValue(&cv_usejoystick[1], choice); // Just in case last-minute changes were made to cv_usejoystick.value, // update the string too // But don't do this if we're intentionally setting higher than numjoys if (choice <= numjoys) { - CV_SetValue(&cv_usejoystick2, cv_usejoystick2.value); + CV_SetValue(&cv_usejoystick[1], cv_usejoystick[1].value); // reset this so the comparison is valid if (oldchoice > numjoys) - oldchoice = cv_usejoystick2.value; + oldchoice = cv_usejoystick[1].value; if (oldchoice != choice) { if (choice && oldstringchoice > numjoys) // if we did not select "None", we likely selected a used device - CV_SetValue(&cv_usejoystick2, (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); + CV_SetValue(&cv_usejoystick[1], (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); if (oldstringchoice == - (atoi(cv_usejoystick2.string) > numjoys ? atoi(cv_usejoystick2.string) : cv_usejoystick2.value)) + (atoi(cv_usejoystick[1].string) > numjoys ? atoi(cv_usejoystick[1].string) : cv_usejoystick[1].value)) M_StartMessage("This joystick is used by another\n" "player. Reset the joystick\n" "for that player first.\n\n" @@ -12042,27 +12038,27 @@ static void M_AssignJoystick(INT32 choice) } else if (setupcontrolplayer == 1) { - oldchoice = oldstringchoice = atoi(cv_usejoystick.string) > numjoys ? atoi(cv_usejoystick.string) : cv_usejoystick.value; - CV_SetValue(&cv_usejoystick, choice); + oldchoice = oldstringchoice = atoi(cv_usejoystick[0].string) > numjoys ? atoi(cv_usejoystick[0].string) : cv_usejoystick[0].value; + CV_SetValue(&cv_usejoystick[0], choice); // Just in case last-minute changes were made to cv_usejoystick.value, // update the string too // But don't do this if we're intentionally setting higher than numjoys if (choice <= numjoys) { - CV_SetValue(&cv_usejoystick, cv_usejoystick.value); + CV_SetValue(&cv_usejoystick[0], cv_usejoystick[0].value); // reset this so the comparison is valid if (oldchoice > numjoys) - oldchoice = cv_usejoystick.value; + oldchoice = cv_usejoystick[0].value; if (oldchoice != choice) { if (choice && oldstringchoice > numjoys) // if we did not select "None", we likely selected a used device - CV_SetValue(&cv_usejoystick, (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); + CV_SetValue(&cv_usejoystick[0], (oldstringchoice > numjoys ? oldstringchoice : oldchoice)); if (oldstringchoice == - (atoi(cv_usejoystick.string) > numjoys ? atoi(cv_usejoystick.string) : cv_usejoystick.value)) + (atoi(cv_usejoystick[0].string) > numjoys ? atoi(cv_usejoystick[0].string) : cv_usejoystick[0].value)) M_StartMessage("This joystick is used by another\n" "player. Reset the joystick\n" "for that player first.\n\n" @@ -12072,13 +12068,13 @@ static void M_AssignJoystick(INT32 choice) } #else if (setupcontrolplayer == 4) - CV_SetValue(&cv_usejoystick4, choice); + CV_SetValue(&cv_usejoystick[3], choice); else if (setupcontrolplayer == 3) - CV_SetValue(&cv_usejoystick3, choice); + CV_SetValue(&cv_usejoystick[2], choice); else if (setupcontrolplayer == 2) - CV_SetValue(&cv_usejoystick2, choice); + CV_SetValue(&cv_usejoystick[1], choice); else if (setupcontrolplayer == 1) - CV_SetValue(&cv_usejoystick, choice); + CV_SetValue(&cv_usejoystick[0], choice); #endif } @@ -12432,49 +12428,49 @@ static void M_ResetControlsResponse(INT32 ch) switch (setupcontrolplayer) { case 4: - CV_StealthSet(&cv_usejoystick4, cv_usejoystick4.defaultvalue); - CV_StealthSet(&cv_turnaxis4, cv_turnaxis4.defaultvalue); - CV_StealthSet(&cv_moveaxis4, cv_moveaxis4.defaultvalue); - CV_StealthSet(&cv_brakeaxis4, cv_brakeaxis4.defaultvalue); - CV_StealthSet(&cv_aimaxis4, cv_aimaxis4.defaultvalue); - CV_StealthSet(&cv_lookaxis4, cv_lookaxis4.defaultvalue); - CV_StealthSet(&cv_fireaxis4, cv_fireaxis4.defaultvalue); - CV_StealthSet(&cv_driftaxis4, cv_driftaxis4.defaultvalue); - CV_StealthSet(&cv_lookbackaxis4, cv_lookbackaxis4.defaultvalue); + CV_StealthSet(&cv_usejoystick[3], cv_usejoystick[3].defaultvalue); + CV_StealthSet(&cv_turnaxis[3], cv_turnaxis[3].defaultvalue); + CV_StealthSet(&cv_moveaxis[3], cv_moveaxis[3].defaultvalue); + CV_StealthSet(&cv_brakeaxis[3], cv_brakeaxis[3].defaultvalue); + CV_StealthSet(&cv_aimaxis[3], cv_aimaxis[3].defaultvalue); + CV_StealthSet(&cv_lookaxis[3], cv_lookaxis[3].defaultvalue); + CV_StealthSet(&cv_fireaxis[3], cv_fireaxis[3].defaultvalue); + CV_StealthSet(&cv_driftaxis[3], cv_driftaxis[3].defaultvalue); + CV_StealthSet(&cv_lookbackaxis[3], cv_lookbackaxis[3].defaultvalue); break; case 3: - CV_StealthSet(&cv_usejoystick3, cv_usejoystick3.defaultvalue); - CV_StealthSet(&cv_turnaxis3, cv_turnaxis3.defaultvalue); - CV_StealthSet(&cv_moveaxis3, cv_moveaxis3.defaultvalue); - CV_StealthSet(&cv_brakeaxis3, cv_brakeaxis3.defaultvalue); - CV_StealthSet(&cv_aimaxis3, cv_aimaxis3.defaultvalue); - CV_StealthSet(&cv_lookaxis3, cv_lookaxis3.defaultvalue); - CV_StealthSet(&cv_fireaxis3, cv_fireaxis3.defaultvalue); - CV_StealthSet(&cv_driftaxis3, cv_driftaxis3.defaultvalue); - CV_StealthSet(&cv_lookbackaxis3, cv_lookbackaxis3.defaultvalue); + CV_StealthSet(&cv_usejoystick[2], cv_usejoystick[2].defaultvalue); + CV_StealthSet(&cv_turnaxis[2], cv_turnaxis[2].defaultvalue); + CV_StealthSet(&cv_moveaxis[2], cv_moveaxis[2].defaultvalue); + CV_StealthSet(&cv_brakeaxis[2], cv_brakeaxis[2].defaultvalue); + CV_StealthSet(&cv_aimaxis[2], cv_aimaxis[2].defaultvalue); + CV_StealthSet(&cv_lookaxis[2], cv_lookaxis[2].defaultvalue); + CV_StealthSet(&cv_fireaxis[2], cv_fireaxis[2].defaultvalue); + CV_StealthSet(&cv_driftaxis[2], cv_driftaxis[2].defaultvalue); + CV_StealthSet(&cv_lookbackaxis[2], cv_lookbackaxis[2].defaultvalue); break; case 2: - CV_StealthSet(&cv_usejoystick2, cv_usejoystick2.defaultvalue); - CV_StealthSet(&cv_turnaxis2, cv_turnaxis2.defaultvalue); - CV_StealthSet(&cv_moveaxis2, cv_moveaxis2.defaultvalue); - CV_StealthSet(&cv_brakeaxis2, cv_brakeaxis2.defaultvalue); - CV_StealthSet(&cv_aimaxis2, cv_aimaxis2.defaultvalue); - CV_StealthSet(&cv_lookaxis2, cv_lookaxis2.defaultvalue); - CV_StealthSet(&cv_fireaxis2, cv_fireaxis2.defaultvalue); - CV_StealthSet(&cv_driftaxis2, cv_driftaxis2.defaultvalue); - CV_StealthSet(&cv_lookbackaxis2, cv_lookbackaxis2.defaultvalue); + CV_StealthSet(&cv_usejoystick[1], cv_usejoystick[1].defaultvalue); + CV_StealthSet(&cv_turnaxis[1], cv_turnaxis[1].defaultvalue); + CV_StealthSet(&cv_moveaxis[1], cv_moveaxis[1].defaultvalue); + CV_StealthSet(&cv_brakeaxis[1], cv_brakeaxis[1].defaultvalue); + CV_StealthSet(&cv_aimaxis[1], cv_aimaxis[1].defaultvalue); + CV_StealthSet(&cv_lookaxis[1], cv_lookaxis[1].defaultvalue); + CV_StealthSet(&cv_fireaxis[1], cv_fireaxis[1].defaultvalue); + CV_StealthSet(&cv_driftaxis[1], cv_driftaxis[1].defaultvalue); + CV_StealthSet(&cv_lookbackaxis[1], cv_lookbackaxis[1].defaultvalue); break; case 1: default: - CV_StealthSet(&cv_usejoystick, cv_usejoystick.defaultvalue); - CV_StealthSet(&cv_turnaxis, cv_turnaxis.defaultvalue); - CV_StealthSet(&cv_moveaxis, cv_moveaxis.defaultvalue); - CV_StealthSet(&cv_brakeaxis, cv_brakeaxis.defaultvalue); - CV_StealthSet(&cv_aimaxis, cv_aimaxis.defaultvalue); - CV_StealthSet(&cv_lookaxis, cv_lookaxis.defaultvalue); - CV_StealthSet(&cv_fireaxis, cv_fireaxis.defaultvalue); - CV_StealthSet(&cv_driftaxis, cv_driftaxis.defaultvalue); - CV_StealthSet(&cv_lookbackaxis, cv_lookbackaxis.defaultvalue); + CV_StealthSet(&cv_usejoystick[0], cv_usejoystick[0].defaultvalue); + CV_StealthSet(&cv_turnaxis[0], cv_turnaxis[0].defaultvalue); + CV_StealthSet(&cv_moveaxis[0], cv_moveaxis[0].defaultvalue); + CV_StealthSet(&cv_brakeaxis[0], cv_brakeaxis[0].defaultvalue); + CV_StealthSet(&cv_aimaxis[0], cv_aimaxis[0].defaultvalue); + CV_StealthSet(&cv_lookaxis[0], cv_lookaxis[0].defaultvalue); + CV_StealthSet(&cv_fireaxis[0], cv_fireaxis[0].defaultvalue); + CV_StealthSet(&cv_driftaxis[0], cv_driftaxis[0].defaultvalue); + CV_StealthSet(&cv_lookbackaxis[0], cv_lookbackaxis[0].defaultvalue); break; } @@ -12581,11 +12577,9 @@ static void M_VideoModeMenu(INT32 choice) static void M_DrawVideoMenu(void) { M_DrawGenericMenu(); - - INT32 lowercase = !cv_menucaps.value ? V_ALLOWLOWERCASE : 0; V_DrawRightAlignedString(BASEVIDWIDTH - currentMenu->x, currentMenu->y + OP_VideoOptionsMenu[0].alphaKey, - (SCR_IsAspectCorrect(vid.width, vid.height) ? recommendedflags : highlightflags)|lowercase, + (SCR_IsAspectCorrect(vid.width, vid.height) ? recommendedflags : highlightflags)|MENUCAPS, va("%dx%d", vid.width, vid.height)); } @@ -12674,7 +12668,7 @@ static void M_DrawLocalSkinMenu(void) else multi_tics += multi_state->tics * FRACUNIT; } - + // skin 0 is default player sprite if (R_AnySkinAvailable(cv_fakelocalskin.string) != -1) { @@ -12683,7 +12677,7 @@ static void M_DrawLocalSkinMenu(void) } else { - // ATTEMPT TO FIND REAL SKIN + // ATTEMPT TO FIND REAL SKIN if (R_AnySkinAvailable(cv_skin.string) != -1) { sprdef = &allskins[R_AnySkinAvailable(cv_skin.string)].spritedef; @@ -12750,17 +12744,17 @@ static void M_DrawVideoMode(void) M_DrawMenuTitle(); V_DrawCenteredString(BASEVIDWIDTH/2, OP_VideoModeDef.y, - highlightflags, "Choose mode, reselect to change default"); + highlightflags|MENUCAPS, "Choose mode, reselect to change default"); row = 41; col = OP_VideoModeDef.y + 14; for (i = 0; i < vidm_nummodes; i++) { if (i == vidm_selected) - V_DrawString(row, col, highlightflags, modedescs[i].desc); + V_DrawString(row, col, highlightflags|MENUCAPS, modedescs[i].desc); // Show multiples of 320x200 as green. else - V_DrawString(row, col, (modedescs[i].goodratio) ? recommendedflags : 0, modedescs[i].desc); + V_DrawString(row, col, ((modedescs[i].goodratio) ? recommendedflags : 0)|MENUCAPS, modedescs[i].desc); col += 8; if ((i % vidm_column_size) == (vidm_column_size-1)) @@ -12798,11 +12792,11 @@ static void M_DrawVideoMode(void) cv_scr_width.value, cv_scr_height.value)); V_DrawCenteredString(BASEVIDWIDTH/2, OP_VideoModeDef.y + 138, - recommendedflags, "Marked modes are recommended."); + recommendedflags|MENUCAPS, "Marked modes are recommended."); V_DrawCenteredString(BASEVIDWIDTH/2, OP_VideoModeDef.y + 146, - highlightflags, "Other modes may have visual errors."); + highlightflags|MENUCAPS, "Other modes may have visual errors."); V_DrawCenteredString(BASEVIDWIDTH/2, OP_VideoModeDef.y + 158, - highlightflags, "Larger modes may have performance issues."); + highlightflags|MENUCAPS, "Larger modes may have performance issues."); } // Draw the cursor for the VidMode menu @@ -12870,9 +12864,9 @@ static void M_DrawColorMenu(void) case IT_STRING: case IT_WHITESTRING: if (i != itemOn && (currentMenu->menuitems[i].status & IT_DISPLAY)==IT_STRING) - V_DrawString(x, y, 0, currentMenu->menuitems[i].text); + V_DrawString(x, y, MENUCAPS, currentMenu->menuitems[i].text); else - V_DrawString(x, y, V_YELLOWMAP, currentMenu->menuitems[i].text); + V_DrawString(x, y, V_YELLOWMAP|MENUCAPS, currentMenu->menuitems[i].text); // Cvar specific handling switch (currentMenu->menuitems[i].status & IT_TYPE) @@ -12907,13 +12901,13 @@ static void M_DrawColorMenu(void) } break; case IT_TRANSTEXT: - V_DrawString(x, y, V_TRANSLUCENT, currentMenu->menuitems[i].text); + V_DrawString(x, y, V_TRANSLUCENT|MENUCAPS, currentMenu->menuitems[i].text); break; case IT_QUESTIONMARKS: - V_DrawString(x, y, V_TRANSLUCENT|V_OLDSPACING, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); + V_DrawString(x, y, V_TRANSLUCENT|V_OLDSPACING|MENUCAPS, M_CreateSecretMenuOption(currentMenu->menuitems[i].text)); break; case IT_HEADERTEXT: - V_DrawString(x-16, y, V_YELLOWMAP, currentMenu->menuitems[i].text); + V_DrawString(x-16, y, V_YELLOWMAP|MENUCAPS, currentMenu->menuitems[i].text); //V_DrawFill(19, y, 281, 9, currentMenu->menuitems[i+1].alphaKey); //V_DrawFill(300, y, 1, 9, 26); //M_DrawLevelPlatterHeader(y - (lsheadingheight - 12), currentMenu->menuitems[i].text, false); diff --git a/src/m_menu.h b/src/m_menu.h index 486b5b869..9806773b4 100644 --- a/src/m_menu.h +++ b/src/m_menu.h @@ -299,6 +299,10 @@ void Bird_menu_Onchange(void); // Saturn Hud menu updating void SaturnHud_menu_Onchange(void); +#ifdef HWRENDER +void M_UpdateOGLMenu(void); +#endif + void M_ReplayHut(INT32 choice); void M_SetPlaybackMenuPointer(void); diff --git a/src/m_misc.c b/src/m_misc.c index 8bb82cdd7..a3768120d 100644 --- a/src/m_misc.c +++ b/src/m_misc.c @@ -27,6 +27,8 @@ // Extended map support. #include +#include "am_map.h" + #include "doomdef.h" #include "g_game.h" #include "m_misc.h" @@ -1573,6 +1575,84 @@ boolean M_ScreenshotResponder(event_t *ev) return true; } +void M_MinimapGenerate(void) +{ +#ifdef USE_PNG + char *filepath; + boolean ret = false; + minigen_t *minigen = NULL; + size_t option_scale; + INT32 mul = 1; + + if (gamestate != GS_LEVEL) + { + CONS_Alert(CONS_ERROR, "You must be in a level to generate a preliminary minimap!\n"); + return; + } + + if (automapactive) + { + CONS_Alert(CONS_ERROR, "The automap is active! Please deactivate it and try again.\n"); + return; + } + + option_scale = COM_CheckPartialParm("-m"); + + if (option_scale) + { + if (COM_Argc() < option_scale + 2)/* no argument after? */ + { + CONS_Alert(CONS_ERROR, + "No multiplier follows parameter '%s'.\n", + COM_Argv(option_scale)); + return; + } + + mul = atoi(COM_Argv(option_scale + 1)); + + if (mul < 1 || mul > 10) + { + CONS_Alert(CONS_ERROR, + "Multiplier %d must be within range 1-10.\n", + mul); + return; + } + + filepath = va("%s" PATHSEP "%s-MINIMAP-%d.png", srb2home, G_BuildMapName(gamemap), mul); + } + else + { + filepath = va("%s" PATHSEP "%s-MINIMAP.png", srb2home, G_BuildMapName(gamemap)); + } + + minigen = AM_MinimapGenerate(mul); + + if (minigen == NULL || minigen->buf == NULL) + goto failure; + + M_CreateScreenShotPalette(); + ret = M_SavePNG(filepath, minigen->buf, minigen->w, minigen->h, screenshot_palette); + +failure: + if (minigen->buf != NULL) + free(minigen->buf); + + if (ret) + { + CONS_Printf(M_GetText("%s saved.\nRemember that this is not a complete minimap,\nand must be edited before putting in-game.\n"), filepath); + if (mul != 1) + { + CONS_Printf("You should divide its size by %d!\n", mul); + } + } + else + { + CONS_Alert(CONS_ERROR, M_GetText("Couldn't create %s\n"), filepath); + } +#endif //#ifdef USE_PNG +} + + // ========================================================================== // TRANSLATION FUNCTIONS // ========================================================================== diff --git a/src/m_misc.h b/src/m_misc.h index 333398161..c858ae128 100644 --- a/src/m_misc.h +++ b/src/m_misc.h @@ -69,6 +69,8 @@ void M_ScreenShot(void); void M_DoScreenShot(void); boolean M_ScreenshotResponder(event_t *ev); +void M_MinimapGenerate(void); + void Command_SaveConfig_f(void); void Command_LoadConfig_f(void); void Command_ChangeConfig_f(void); diff --git a/src/m_perfstats.c b/src/m_perfstats.c index 30640b21c..3c5526678 100644 --- a/src/m_perfstats.c +++ b/src/m_perfstats.c @@ -301,7 +301,7 @@ static boolean PS_IsRowValid(perfstatrow_t *row) || (row->flags & PS_SW && rendermode != render_soft) || (row->flags & PS_HW && rendermode != render_opengl) #ifdef HWRENDER - || (row->flags & PS_BATCHING && !cv_grbatching.value) + || (row->flags & PS_BATCHING && !cv_glbatching.value) #endif ); } @@ -518,7 +518,7 @@ static void PS_UpdateFrameStats(void) ps_hw_spritesorttime.value.p + ps_hw_spritedrawtime.value.p; - if (cv_grbatching.value) + if (cv_glbatching.value) { ps_otherrendertime.value.p -= ps_hw_batchsorttime.value.p + @@ -547,7 +547,7 @@ static void PS_UpdateFrameStats(void) PS_UpdateRowHistories(interpolation_rows, true);*/ #ifdef HWRENDER - if (rendermode == render_opengl && cv_grbatching.value) + if (rendermode == render_opengl && cv_glbatching.value) { PS_UpdateRowHistories(batchcount_rows, true); PS_UpdateRowHistories(batchcalls_rows, true); @@ -760,7 +760,7 @@ static void PS_DrawRenderStats(void) /*cy = */PS_DrawPerfRows(x, 10, V_BLUEMAP, commoncounter_rows);// + half_row; #ifdef HWRENDER - if (rendermode == render_opengl && cv_grbatching.value) + if (rendermode == render_opengl && cv_glbatching.value) { x = hires ? 200 : 155; y = PS_DrawPerfRows(x, 10, V_PURPLEMAP, batchcount_rows); diff --git a/src/m_textinput.c b/src/m_textinput.c index a73511f77..266a8f300 100644 --- a/src/m_textinput.c +++ b/src/m_textinput.c @@ -118,6 +118,15 @@ static void M_TextInputToWordBegin(textinput_t *input, boolean move_sel) if (move_sel) input->select = input->cursor; } +static void M_TextInputPaste(textinput_t *input) +{ + const char *paste = I_ClipboardPaste(); + if (input->select != input->cursor) + M_TextInputDelSelection(input); + if (paste != NULL) + M_TextInputAddString(input, paste); +} + void M_TextInputInit(textinput_t *input, char *buffer, size_t buffer_size) { input->buffer = buffer; @@ -131,6 +140,8 @@ void M_TextInputClear(textinput_t *input) input->cursor = 0; input->select = 0; input->length = 0; + + input->buffer[0] = 0; } void M_TextInputSetString(textinput_t *input, const char *c) @@ -147,6 +158,12 @@ boolean M_TextInputHandle(textinput_t *input, INT32 key) || key == KEY_LALT || key == KEY_RALT) return false; + if (shiftdown && key == KEY_INS) + { + M_TextInputPaste(input); + return true; + } + if ((cv_keyboardlayout.value != 3 && ctrldown) || (cv_keyboardlayout.value == 3 && ctrldown && !altdown)) { if (key == 'x' || key == 'X') @@ -168,11 +185,7 @@ boolean M_TextInputHandle(textinput_t *input, INT32 key) } else if (key == 'v' || key == 'V') { - const char *paste = I_ClipboardPaste(); - if (input->select != input->cursor) - M_TextInputDelSelection(input); - if (paste != NULL) - M_TextInputAddString(input, paste); + M_TextInputPaste(input); return true; } else if (key == 'w' || key == 'W') diff --git a/src/p_enemy.c b/src/p_enemy.c index caa85e331..96b0a16df 100644 --- a/src/p_enemy.c +++ b/src/p_enemy.c @@ -165,9 +165,6 @@ void A_SpawnObjectAbsolute(mobj_t *actor); void A_SpawnObjectRelative(mobj_t *actor); void A_ChangeAngleRelative(mobj_t *actor); void A_ChangeAngleAbsolute(mobj_t *actor); -void A_RollAngle(mobj_t *actor); -void A_ChangeRollAngleRelative(mobj_t *actor); -void A_ChangeRollAngleAbsolute(mobj_t *actor); void A_PlaySound(mobj_t *actor); void A_FindTarget(mobj_t *actor); void A_FindTracer(mobj_t *actor); @@ -2658,7 +2655,7 @@ void A_BossDeath(mobj_t *mo) } bossjustdie: - if (LUAh_BossDeath(mo)) + if (LUA_HookMobj(mo, MOBJ_HOOK(BossDeath))) return; else if (P_MobjWasRemoved(mo)) return; @@ -7183,80 +7180,6 @@ void A_ChangeAngleAbsolute(mobj_t *actor) actor->angle = FixedAngle(P_RandomRange(amin, amax)); } -// Function: A_RollAngle -// -// Description: Changes the roll angle. -// -// var1 = angle -// var2 = relative? (default) -// -void A_RollAngle(mobj_t *actor) -{ - INT32 locvar1 = var1; - INT32 locvar2 = var2; - const angle_t angle = FixedAngle(locvar1*FRACUNIT); - - if (LUA_CallAction(A_ROLLANGLE, actor)) - return; - - // relative (default) - if (!locvar2) - actor->rollangle += angle; - // absolute - else - actor->rollangle = angle; -} - -// Function: A_ChangeRollAngleRelative -// -// Description: Changes the roll angle to a random relative value between the min and max. Set min and max to the same value to eliminate randomness -// -// var1 = min -// var2 = max -// -void A_ChangeRollAngleRelative(mobj_t *actor) -{ - INT32 locvar1 = var1; - INT32 locvar2 = var2; - const fixed_t amin = locvar1*FRACUNIT; - const fixed_t amax = locvar2*FRACUNIT; - - if (LUA_CallAction(A_CHANGEROLLANGLERELATIVE, actor)) - return; - -#ifdef PARANOIA - if (amin > amax) - I_Error("A_ChangeRollAngleRelative: var1 is greater than var2"); -#endif - - actor->rollangle += FixedAngle(P_RandomRange(amin, amax)); -} - -// Function: A_ChangeRollAngleAbsolute -// -// Description: Changes the roll angle to a random absolute value between the min and max. Set min and max to the same value to eliminate randomness -// -// var1 = min -// var2 = max -// -void A_ChangeRollAngleAbsolute(mobj_t *actor) -{ - INT32 locvar1 = var1; - INT32 locvar2 = var2; - const fixed_t amin = locvar1*FRACUNIT; - const fixed_t amax = locvar2*FRACUNIT; - - if (LUA_CallAction(A_CHANGEROLLANGLEABSOLUTE, actor)) - return; - -#ifdef PARANOIA - if (amin > amax) - I_Error("A_ChangeRollAngleAbsolute: var1 is greater than var2"); -#endif - - actor->rollangle = FixedAngle(P_RandomRange(amin, amax)); -} - // Function: A_PlaySound // // Description: Plays a sound diff --git a/src/p_floor.c b/src/p_floor.c index bebc9a272..17e32c089 100644 --- a/src/p_floor.c +++ b/src/p_floor.c @@ -2119,10 +2119,11 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) sec = §ors[secnum]; FOFsector = false; + INT32 special = GETSECSPECIAL(sec->special, 2); - if (GETSECSPECIAL(sec->special, 2) == 3 || GETSECSPECIAL(sec->special, 2) == 5) + if (special == 3 || special == 5) floortouch = true; - else if (GETSECSPECIAL(sec->special, 2) >= 1 && GETSECSPECIAL(sec->special, 2) <= 8) + else if (special >= 1 && special <= 8) floortouch = false; else continue; @@ -2254,7 +2255,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) continue; if (!(players[i].mo->subsector->sector == sec - || P_PlayerTouchingSectorSpecial(&players[i], 2, (GETSECSPECIAL(sec->special, 2))) == sec)) + || P_PlayerTouchingSectorSpecial(&players[i], 2, special) == sec)) continue; if (floortouch == true && P_IsObjectOnRealGround(players[i].mo, sec)) @@ -2298,7 +2299,9 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) while ((affectPlayer = P_HavePlayersEnteredArea(playersArea, oldPlayersArea, inAndOut)) != -1) { - if (GETSECSPECIAL(sec->special, 2) == 2 || GETSECSPECIAL(sec->special, 2) == 3) + INT32 special = GETSECSPECIAL(sec->special, 2); + + if (special == 2 || special == 3) { for (i = 0; i < MAXPLAYERS; i++) { @@ -2507,123 +2510,44 @@ void T_CameraScanner(elevator_t *elevator) { // leveltime is compared to make multiple scanners in one map function correctly. static tic_t lastleveltime = 32000; // any number other than 0 should do here - static boolean camerascanned, camerascanned2, camerascanned3, camerascanned4; + static boolean camerascanned[MAXSPLITSCREENPLAYERS]; + static fixed_t t_cam_dist[MAXSPLITSCREENPLAYERS] = {-42, -42, -42, -42}; + static fixed_t t_cam_height[MAXSPLITSCREENPLAYERS] = {-42, -42, -42, -42}; if (leveltime != lastleveltime) // Back on the first camera scanner { - camerascanned = camerascanned2 = camerascanned3 = camerascanned4 = false; + memset(camerascanned, false, sizeof (camerascanned)); lastleveltime = leveltime; } - if (players[displayplayers[0]].mo) + for (UINT8 i = 0; i <= splitscreen; i++) { - if (players[displayplayers[0]].mo->subsector->sector == elevator->actionsector) - { - if (t_cam_dist == -42) - t_cam_dist = cv_cam_dist.value; - if (t_cam_height == -42) - t_cam_height = cv_cam_height.value; - if (t_cam_rotate == -42) - t_cam_rotate = cv_cam_rotate.value; - CV_SetValue(&cv_cam_height, FixedInt(elevator->sector->floorheight)); - CV_SetValue(&cv_cam_dist, FixedInt(elevator->sector->ceilingheight)); - CV_SetValue(&cv_cam_rotate, elevator->distance); - camerascanned = true; - } - else if (!camerascanned) - { - if (t_cam_height != -42 && cv_cam_height.value != t_cam_height) - CV_Set(&cv_cam_height, va("%f", (double)FIXED_TO_FLOAT(t_cam_height))); - if (t_cam_dist != -42 && cv_cam_dist.value != t_cam_dist) - CV_Set(&cv_cam_dist, va("%f", (double)FIXED_TO_FLOAT(t_cam_dist))); - if (t_cam_rotate != -42 && cv_cam_rotate.value != t_cam_rotate) - CV_Set(&cv_cam_rotate, va("%f", (double)t_cam_rotate)); + if (!players[displayplayers[i]].mo || P_MobjWasRemoved(players[displayplayers[i]].mo)) + continue; - t_cam_dist = t_cam_height = t_cam_rotate = -42; - } - } - - if (splitscreen && players[displayplayers[1]].mo) - { - if (players[displayplayers[1]].mo->subsector->sector == elevator->actionsector) + if (players[displayplayers[i]].mo->subsector->sector == elevator->actionsector) { - if (t_cam2_rotate == -42) - t_cam2_dist = cv_cam2_dist.value; - if (t_cam2_rotate == -42) - t_cam2_height = cv_cam2_height.value; - if (t_cam2_rotate == -42) - t_cam2_rotate = cv_cam2_rotate.value; - CV_SetValue(&cv_cam2_height, FixedInt(elevator->sector->floorheight)); - CV_SetValue(&cv_cam2_dist, FixedInt(elevator->sector->ceilingheight)); - CV_SetValue(&cv_cam2_rotate, elevator->distance); - camerascanned2 = true; + if (t_cam_dist[i] == -42) + t_cam_dist[i] = cv_cam_dist[i].value; + if (t_cam_height[i] == -42) + t_cam_height[i] = cv_cam_height[i].value; + if (t_cam_rotate[i] == -42) + t_cam_rotate[i] = cv_cam_rotate[i].value; + CV_SetValue(&cv_cam_height[i], FixedInt(elevator->sector->floorheight)); + CV_SetValue(&cv_cam_dist[i], FixedInt(elevator->sector->ceilingheight)); + CV_SetValue(&cv_cam_rotate[i], elevator->distance); + camerascanned[i] = true; } - else if (!camerascanned2) + else if (!camerascanned[i]) { - if (t_cam2_height != -42 && cv_cam2_height.value != t_cam2_height) - CV_Set(&cv_cam2_height, va("%f", (double)FIXED_TO_FLOAT(t_cam2_height))); - if (t_cam2_dist != -42 && cv_cam2_dist.value != t_cam2_dist) - CV_Set(&cv_cam2_dist, va("%f", (double)FIXED_TO_FLOAT(t_cam2_dist))); - if (t_cam2_rotate != -42 && cv_cam2_rotate.value != t_cam2_rotate) - CV_Set(&cv_cam2_rotate, va("%f", (double)t_cam2_rotate)); + if (t_cam_height[i] != -42 && cv_cam_height[i].value != t_cam_height[i]) + CV_Set(&cv_cam_height[i], va("%f", (double)FIXED_TO_FLOAT(t_cam_height[i]))); + if (t_cam_dist[i] != -42 && cv_cam_dist[i].value != t_cam_dist[i]) + CV_Set(&cv_cam_dist[i], va("%f", (double)FIXED_TO_FLOAT(t_cam_dist[i]))); + if (t_cam_rotate[i] != -42 && cv_cam_rotate[i].value != t_cam_rotate[i]) + CV_Set(&cv_cam_rotate[i], va("%f", (double)t_cam_rotate[i])); - t_cam2_dist = t_cam2_height = t_cam2_rotate = -42; - } - } - - if (splitscreen > 1 && players[displayplayers[2]].mo) - { - if (players[displayplayers[2]].mo->subsector->sector == elevator->actionsector) - { - if (t_cam3_rotate == -42) - t_cam3_dist = cv_cam3_dist.value; - if (t_cam3_rotate == -42) - t_cam3_height = cv_cam3_height.value; - if (t_cam3_rotate == -42) - t_cam3_rotate = cv_cam3_rotate.value; - CV_SetValue(&cv_cam3_height, FixedInt(elevator->sector->floorheight)); - CV_SetValue(&cv_cam3_dist, FixedInt(elevator->sector->ceilingheight)); - CV_SetValue(&cv_cam3_rotate, elevator->distance); - camerascanned3 = true; - } - else if (!camerascanned3) - { - if (t_cam3_height != -42 && cv_cam3_height.value != t_cam3_height) - CV_Set(&cv_cam3_height, va("%f", (double)FIXED_TO_FLOAT(t_cam3_height))); - if (t_cam3_dist != -42 && cv_cam3_dist.value != t_cam3_dist) - CV_Set(&cv_cam3_dist, va("%f", (double)FIXED_TO_FLOAT(t_cam3_dist))); - if (t_cam3_rotate != -42 && cv_cam3_rotate.value != t_cam3_rotate) - CV_Set(&cv_cam3_rotate, va("%f", (double)t_cam3_rotate)); - - t_cam3_dist = t_cam3_height = t_cam3_rotate = -42; - } - } - - if (splitscreen > 2 && players[displayplayers[3]].mo) - { - if (players[displayplayers[3]].mo->subsector->sector == elevator->actionsector) - { - if (t_cam4_rotate == -42) - t_cam4_dist = cv_cam4_dist.value; - if (t_cam4_rotate == -42) - t_cam4_height = cv_cam4_height.value; - if (t_cam4_rotate == -42) - t_cam4_rotate = cv_cam4_rotate.value; - CV_SetValue(&cv_cam4_height, FixedInt(elevator->sector->floorheight)); - CV_SetValue(&cv_cam4_dist, FixedInt(elevator->sector->ceilingheight)); - CV_SetValue(&cv_cam4_rotate, elevator->distance); - camerascanned4 = true; - } - else if (!camerascanned4) - { - if (t_cam4_height != -42 && cv_cam4_height.value != t_cam4_height) - CV_Set(&cv_cam4_height, va("%f", (double)FIXED_TO_FLOAT(t_cam4_height))); - if (t_cam4_dist != -42 && cv_cam4_dist.value != t_cam4_dist) - CV_Set(&cv_cam4_dist, va("%f", (double)FIXED_TO_FLOAT(t_cam4_dist))); - if (t_cam4_rotate != -42 && cv_cam4_rotate.value != t_cam4_rotate) - CV_Set(&cv_cam4_rotate, va("%f", (double)t_cam4_rotate)); - - t_cam4_dist = t_cam4_height = t_cam4_rotate = -42; + t_cam_dist[i] = t_cam_height[i] = t_cam_rotate[i] = -42; } } } @@ -2996,11 +2920,12 @@ void EV_CrumbleChain(sector_t *sec, ffloor_t *rover) fixed_t a, b, c; mobjtype_t type = MT_ROCKCRUMBLE1; const fixed_t spacing = 48*mapobjectscale; + INT32 special = GETSECSPECIAL(rover->master->frontsector->special, 3); // If the control sector has a special // of Section3:7-15, use the custom debris. - if (GETSECSPECIAL(rover->master->frontsector->special, 3) >= 8) - type = MT_ROCKCRUMBLE1+(GETSECSPECIAL(rover->master->frontsector->special, 3)-7); + if (special >= 8) + type = MT_ROCKCRUMBLE1+(special-7); // soundorg z height never gets set normally, so MEH. sec->soundorg.z = sec->floorheight; diff --git a/src/p_inter.c b/src/p_inter.c index ca1d88ba2..d4a5b3c1d 100644 --- a/src/p_inter.c +++ b/src/p_inter.c @@ -284,7 +284,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) if (special->flags & MF_BOSS && special->flags2 & MF2_FRET) return; - if (LUAh_TouchSpecial(special, toucher) || P_MobjWasRemoved(special)) + if (LUA_HookTouchSpecial(special, toucher) || P_MobjWasRemoved(special)) return; if (special->flags & MF_BOSS) @@ -976,11 +976,10 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) break; case MT_HOOPCOLLIDE: // This produces a kind of 'domino effect' with the hoop's pieces. - if (!midgamejoin) - for (; special->hprev != NULL; special = special->hprev); // Move to the first sprite in the hoop + for (; !P_MobjWasRemoved(special->hprev); special = special->hprev); // Move to the first sprite in the hoop i = 0; - for (; special->type == MT_HOOP; special = special->hnext) + for (; !P_MobjWasRemoved(special->hnext) && special->type == MT_HOOP; special = special->hnext) { special->fuse = 11; special->movedir = i; @@ -1641,7 +1640,7 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) target->flags2 &= ~(MF2_SKULLFLY|MF2_NIGHTSPULL); target->health = 0; // This makes it easy to check if something's dead elsewhere. - if (LUAh_MobjDeath(target, inflictor, source) || P_MobjWasRemoved(target)) + if (LUA_HookMobjDeath(target, inflictor, source) || P_MobjWasRemoved(target)) return; // SRB2kart @@ -2397,11 +2396,9 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da // Everything above here can't be forced. if (!metalrecording) { - UINT8 shouldForce = LUAh_ShouldDamage(target, inflictor, source, damage); + UINT8 shouldForce = LUA_HookShouldDamage(target, inflictor, source, damage); if (P_MobjWasRemoved(target)) return (shouldForce == 1); // mobj was removed - if (P_MobjWasRemoved(source)) - source = NULL; if (shouldForce == 1) force = true; else if (shouldForce == 2) @@ -2440,7 +2437,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da if (!force && target->fuse) // Invincible return false; - if (LUAh_MobjDamage(target, inflictor, source, damage) || P_MobjWasRemoved(target)) + if (LUA_HookMobjDamage(target, inflictor, source, damage) || P_MobjWasRemoved(target)) return true; if (target->health > 1) @@ -2466,7 +2463,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da if (!force && target->flags2 & MF2_FRET) // Currently flashing from being hit return false; - if (LUAh_MobjDamage(target, inflictor, source, damage) || P_MobjWasRemoved(target)) + if (LUA_HookMobjDamage(target, inflictor, source, damage) || P_MobjWasRemoved(target)) return true; if (target->health > 1) @@ -2474,7 +2471,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da } else if (target->flags & MF_ENEMY) { - if (LUAh_MobjDamage(target, inflictor, source, damage) || P_MobjWasRemoved(target)) + if (LUA_HookMobjDamage(target, inflictor, source, damage) || P_MobjWasRemoved(target)) return true; } @@ -2503,14 +2500,14 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da return false; // Don't run eachother over in special stages and team games and such } - if (LUAh_MobjDamage(target, inflictor, source, damage)) + if (LUA_HookMobjDamage(target, inflictor, source, damage)) return true; P_NiGHTSDamage(target, source); // -5s :( return true; } - if (LUAh_MobjDamage(target, inflictor, source, damage)) + if (LUA_HookMobjDamage(target, inflictor, source, damage)) return true; if (!force && inflictor && (inflictor->flags & MF_FIRE)) @@ -2638,6 +2635,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da P_ResetPlayer(target->player); } else + { switch (target->type) { case MT_EGGMOBILE2: // egg slimer @@ -2651,9 +2649,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da P_SetMobjState(target, target->info->painstate); break; } - - if (P_MobjWasRemoved(target)) - return false; + } if (!P_MobjWasRemoved(target)) { diff --git a/src/p_local.h b/src/p_local.h index 0902c8b3d..ea0bff603 100644 --- a/src/p_local.h +++ b/src/p_local.h @@ -66,6 +66,7 @@ // both the head and tail of the thinker list extern thinker_t thinkercap; +extern mobj_t *mobjcache; void P_InitThinkers(void); void P_AddThinker(thinker_t *thinker); @@ -116,7 +117,7 @@ struct demofreecam_s { camera_t *cam; // this is useful when the game is paused, notably mobj_t *soundmobj; // mobj to play sound from, used in s_sound - + angle_t localangle; // keeps track of the cam angle for cmds angle_t localaiming; // ditto with aiming boolean turnheld; // holding turn button for gradual turn speed @@ -126,17 +127,12 @@ struct demofreecam_s { extern struct demofreecam_s democam; extern camera_t camera[MAXSPLITSCREENPLAYERS]; -extern consvar_t cv_cam_dist, cv_cam_still, cv_cam_height; -extern consvar_t cv_cam_speed, cv_cam_rotate, cv_cam_rotspeed; - -extern consvar_t cv_cam2_dist, cv_cam2_still, cv_cam2_height; -extern consvar_t cv_cam2_speed, cv_cam2_rotate, cv_cam2_rotspeed; - -extern consvar_t cv_cam3_dist, cv_cam3_still, cv_cam3_height; -extern consvar_t cv_cam3_speed, cv_cam3_rotate, cv_cam3_rotspeed; - -extern consvar_t cv_cam4_dist, cv_cam4_still, cv_cam4_height; -extern consvar_t cv_cam4_speed, cv_cam4_rotate, cv_cam4_rotspeed; +extern consvar_t cv_cam_dist[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_cam_still[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_cam_height[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_cam_speed[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_cam_rotate[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_cam_rotspeed[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_tilting; extern consvar_t cv_quaketilt; @@ -146,10 +142,7 @@ extern consvar_t cv_actionmovie; extern consvar_t cv_lookbackmom; -extern fixed_t t_cam_dist, t_cam_height, t_cam_rotate; -extern fixed_t t_cam2_dist, t_cam2_height, t_cam2_rotate; -extern fixed_t t_cam3_dist, t_cam3_height, t_cam3_rotate; -extern fixed_t t_cam4_dist, t_cam4_height, t_cam4_rotate; +extern fixed_t t_cam_rotate[MAXSPLITSCREENPLAYERS]; fixed_t P_GetPlayerHeight(player_t *player); fixed_t P_GetPlayerSpinHeight(player_t *player); @@ -265,7 +258,7 @@ void P_SceneryThinker(mobj_t *mobj); // To test it in Lua, check mobj.valid FUNCINLINE static ATTRINLINE boolean P_MobjWasRemoved(const mobj_t *mobj) { - return !(mobj && mobj->thinker.function.acp1 == (actionf_p1)P_MobjThinker); + return (!mobj || mobj->thinker.function.acp1 != (actionf_p1)P_MobjThinker); } fixed_t P_MobjFloorZ(mobj_t *mobj, sector_t *sector, sector_t *boundsec, fixed_t x, fixed_t y, line_t *line, boolean lowest, boolean perfect); @@ -298,7 +291,14 @@ mobj_t *P_SPMAngle(mobj_t *source, mobjtype_t type, angle_t angle, UINT8 aimtype #define P_SpawnNameFinder(s,t) P_SPMAngle(s,t,s->angle,true,0) #endif void P_ColorTeamMissile(mobj_t *missile, player_t *source); -SINT8 P_MobjFlip(const mobj_t *mobj); + +// P_MobjFlip +// Special utility to return +1 or -1 depending on mobj's gravity +FUNCINLINE static ATTRINLINE SINT8 P_MobjFlip(const mobj_t *mobj) +{ + return (mobj && mobj->eflags & MFE_VERTICALFLIP) ? -1 : 1; +} + fixed_t P_GetMobjGravity(mobj_t *mo); FUNCMATH boolean P_WeaponOrPanel(mobjtype_t type); @@ -368,7 +368,11 @@ boolean P_MoveOrigin(mobj_t *thing, fixed_t x, fixed_t y, fixed_t z); void P_SlideMove(mobj_t *mo, boolean forceslide); void P_BouncePlayerMove(mobj_t *mo); void P_BounceMove(mobj_t *mo); -boolean P_CheckSight(mobj_t *t1, mobj_t *t2); + +#define P_CheckSight(t1, t2) P_CheckSight2(t1, t2, false) +#define P_CheckSightFast(t1, t2) P_CheckSight2(t1, t2, true) +boolean P_CheckSight2(mobj_t *t1, mobj_t *t2, boolean fast); + void P_CheckHoopPosition(mobj_t *hoopthing, fixed_t x, fixed_t y, fixed_t z, fixed_t radius); boolean P_CheckSector(sector_t *sector, boolean crunch); @@ -441,7 +445,6 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck); void P_PlayerFlagBurst(player_t *player, boolean toss); void P_CheckTimeLimit(void); void P_CheckPointLimit(void); -//void P_CheckSurvivors(void); boolean P_CheckRacers(void); boolean P_CanPickupItem(player_t *player, UINT8 weapon); diff --git a/src/p_map.c b/src/p_map.c index bd551829d..6825141a4 100644 --- a/src/p_map.c +++ b/src/p_map.c @@ -449,7 +449,7 @@ static boolean PIT_CheckThing(mobj_t *thing) } { - UINT8 shouldCollide = LUAh_MobjCollide(thing, tmthing); // checks hook for thing's type + UINT8 shouldCollide = LUA_Hook2Mobj(thing, tmthing, MOBJ_HOOK(MobjCollide)); // checks hook for thing's type if (P_MobjWasRemoved(tmthing) || P_MobjWasRemoved(thing)) return true; // one of them was removed??? if (shouldCollide == 1) @@ -458,7 +458,7 @@ static boolean PIT_CheckThing(mobj_t *thing) return true; // force no collide } { - UINT8 shouldCollide = LUAh_MobjMoveCollide(tmthing, thing); // checks hook for tmthing's type + UINT8 shouldCollide = LUA_Hook2Mobj(tmthing, thing, MOBJ_HOOK(MobjMoveCollide)); // checks hook for tmthing's type if (P_MobjWasRemoved(tmthing) || P_MobjWasRemoved(thing)) return true; // one of them was removed??? if (shouldCollide == 1) @@ -1727,6 +1727,7 @@ boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) tmbbox[BOXLEFT] = x - tmthing->radius; newsubsec = R_PointInSubsector(x, y); + ceilingline = blockingline = NULL; // The base floor / ceiling is from the subsector @@ -2391,16 +2392,19 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) { //All things are affected by their scale. fixed_t maxstep = FixedMul(MAXSTEPMOVE, mapobjectscale); + INT32 special = 0; if (thing->player) { + special = GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1); + // If using type Section1:13, double the maxstep. if (P_PlayerTouchingSectorSpecial(thing->player, 1, 13) - || GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1) == 13) + || special == 13) maxstep <<= 1; // If using type Section1:12, no maxstep. For ledges you don't want the player to climb! (see: Egg Zeppelin & SMK port walls) else if (P_PlayerTouchingSectorSpecial(thing->player, 1, 12) - || GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1) == 12) + || special == 12) maxstep = 0; } @@ -2446,7 +2450,7 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) else if (maxstep > 0 && !( thing->player && ( P_PlayerTouchingSectorSpecial(thing->player, 1, 14) - || GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1) == 14) + || special == 14) )) // Step down { // If the floor difference is MAXSTEPMOVE or less, and the sector isn't Section1:14, ALWAYS diff --git a/src/p_maputl.c b/src/p_maputl.c index f2fc0867e..3c91dc922 100644 --- a/src/p_maputl.c +++ b/src/p_maputl.c @@ -35,23 +35,33 @@ void P_ClosestPointOnLine(fixed_t x, fixed_t y, line_t *line, vertex_t *result) fixed_t dy = line->dy; // Determine t (the length of the vector from �Line[0]� to �p�) + fixed_t cx, cy; + fixed_t vx, vy; fixed_t magnitude; fixed_t t; + //Sub (p, &Line[0], &c); + cx = x - startx; + cy = y - starty; + + //Sub (&Line[1], &Line[0], &V); + vx = dx; + vy = dy; + //Normalize (&V, &V); magnitude = R_PointToDist2(line->v2->x, line->v2->y, startx, starty); - dx = FixedDiv(dx, magnitude); - dy = FixedDiv(dy, magnitude); + vx = FixedDiv(vx, magnitude); + vy = FixedDiv(vy, magnitude); - t = (FixedMul(dx, (x - startx)) + FixedMul(dy, (y - starty))); + t = (FixedMul(vx, cx) + FixedMul(vy, cy)); // Return the point between �Line[0]� and �Line[1]� - dx = FixedMul(dx, t); - dy = FixedMul(dy, t); + vx = FixedMul(vx, t); + vy = FixedMul(vy, t); //Add (&Line[0], &V, out); - result->x = startx + dx; - result->y = starty + dy; + result->x = startx + vx; + result->y = starty + vy; return; } @@ -69,15 +79,28 @@ void P_ClosestPointOnLine3D(fixed_t x, fixed_t y, fixed_t z, line_t *line, verte fixed_t dz = line->v2->z - line->v1->z; // Determine t (the length of the vector from �Line[0]� to �p�) + fixed_t cx, cy, cz; + fixed_t vx, vy, vz; fixed_t magnitude; fixed_t t; - magnitude = R_PointToDist2(0, line->v2->z, R_PointToDist2(line->v2->x, line->v2->y, startx, starty), startz); - dx = FixedDiv(dx, magnitude); - dy = FixedDiv(dy, magnitude); - dz = FixedDiv(dz, magnitude); + //Sub (p, &Line[0], &c); + cx = x - startx; + cy = y - starty; + cz = z - startz; - t = (FixedMul(dx, (x - startx)) + FixedMul(dy, (y - starty)) + FixedMul(dz, (z - startz))); + //Sub (&Line[1], &Line[0], &V); + vx = dx; + vy = dy; + vz = dz; + + //Normalize (&V, &V); + magnitude = R_PointToDist2(0, line->v2->z, R_PointToDist2(line->v2->x, line->v2->y, startx, starty), startz); + vx = FixedDiv(vx, magnitude); + vy = FixedDiv(vy, magnitude); + vz = FixedDiv(vz, magnitude); + + t = (FixedMul(vx, cx) + FixedMul(vy, cy) + FixedMul(vz, cz)); // Set closest point to the end if it extends past -Red if (t <= 0) @@ -96,14 +119,14 @@ void P_ClosestPointOnLine3D(fixed_t x, fixed_t y, fixed_t z, line_t *line, verte } // Return the point between �Line[0]� and �Line[1]� - dx = FixedMul(dx, t); - dy = FixedMul(dy, t); - dz = FixedMul(dz, t); + vx = FixedMul(vx, t); + vy = FixedMul(vy, t); + vz = FixedMul(vz, t); //Add (&Line[0], &V, out); - result->x = startx + dx; - result->y = starty + dy; - result->z = startz + dz; + result->x = startx + vx; + result->y = starty + vy; + result->z = startz + vz; return; } @@ -113,16 +136,21 @@ void P_ClosestPointOnLine3D(fixed_t x, fixed_t y, fixed_t z, line_t *line, verte // INT32 P_PointOnLineSide(fixed_t x, fixed_t y, const line_t *line) { + fixed_t dx, dy, left, right; + if (!line->dx) return x <= line->v1->x ? line->dy > 0 : line->dy < 0; if (!line->dy) return y <= line->v1->y ? line->dx < 0 : line->dx > 0; - x -= line->v1->x; - y -= line->v1->y; + dx = (x - line->v1->x); + dy = (y - line->v1->y); - return FixedMul(y, line->dx>>FRACBITS) < FixedMul(line->dy>>FRACBITS, x) ? 0 : 1; + left = FixedMul(line->dy>>FRACBITS, dx); + right = FixedMul(dy, line->dx>>FRACBITS); + + return right < left ? 0 : 1; } // @@ -182,22 +210,28 @@ INT32 P_BoxOnLineSide(fixed_t *tmbox, const line_t *ld) // static INT32 P_PointOnDivlineSide(fixed_t x, fixed_t y, divline_t *line) { + fixed_t dx, dy, left, right; + if (!line->dx) return x <= line->x ? line->dy > 0 : line->dy < 0; if (!line->dy) return y <= line->y ? line->dx < 0 : line->dx > 0; - x -= line->x; - y -= line->y; + dx = (x - line->x); + dy = (y - line->y); // try to quickly decide by looking at sign bits - if ((line->dy ^ line->dx ^ x ^ y) & 0x80000000) - return ((line->dy ^ x) & 0x80000000) ? 1 : 0; + if ((line->dy ^ line->dx ^ dx ^ dy) & 0x80000000) + return ((line->dy ^ dx) & 0x80000000) ? 1 : 0; - return FixedMul(y>>8, line->dx>>8) < FixedMul(line->dy>>8, x>>8) ? 0 : 1; + left = FixedMul(line->dy>>8, dx>>8); + right = FixedMul(dy>>8, line->dx>>8); + + return right < left ? 0 : 1; } + // // P_MakeDivline // @@ -216,14 +250,17 @@ void P_MakeDivline(line_t *li, divline_t *dl) // fixed_t P_InterceptVector(divline_t *v2, divline_t *v1) { - fixed_t den; + fixed_t frac, num, den; den = FixedMul(v1->dy>>8, v2->dx) - FixedMul(v1->dx>>8, v2->dy); if (!den) return 0; - return (FixedDiv(FixedMul((v1->x - v2->x)>>8, v1->dy) + FixedMul((v2->y - v1->y)>>8, v1->dx), den)); + num = FixedMul((v1->x - v2->x)>>8, v1->dy) + FixedMul((v2->y - v1->y)>>8, v1->dx); + frac = FixedDiv(num, den); + + return frac; } // diff --git a/src/p_mobj.c b/src/p_mobj.c index 0fc870045..03e7e9f99 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -48,6 +48,7 @@ actioncache_t actioncachehead; static mobj_t *overlaycap = NULL; static mobj_t *shadowcap = NULL; mobj_t *waypointcap = NULL; +mobj_t *mobjcache = NULL; void P_InitCachedActions(void) { @@ -91,6 +92,7 @@ FUNCINLINE static ATTRINLINE void P_CycleStateAnimation(mobj_t *mobj) // var2 determines delay between animation frames if (!(mobj->frame & FF_ANIMATE) || --mobj->anim_duration != 0) return; + mobj->anim_duration = (UINT16)mobj->state->var2; // compare the current sprite frame to the one we started from @@ -351,18 +353,6 @@ static boolean P_SetPrecipMobjState(precipmobj_t *mobj, statenum_t state) return true; } -// -// P_MobjFlip -// -// Special utility to return +1 or -1 depending on mobj's gravity -// -SINT8 P_MobjFlip(const mobj_t *mobj) -{ - if (mobj && mobj->eflags & MFE_VERTICALFLIP) - return -1; - return 1; -} - // // P_WeaponOrPanel // @@ -408,7 +398,7 @@ void P_ExplodeMissile(mobj_t *mo) P_RadiusAttack(mo, mo, 96*FRACUNIT); explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (!P_MobjWasRemoved(explodemo)) + if (explodemo) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -417,7 +407,7 @@ void P_ExplodeMissile(mobj_t *mo) S_StartSound(explodemo, sfx_pop); } explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (!P_MobjWasRemoved(explodemo)) + if (explodemo) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -426,7 +416,7 @@ void P_ExplodeMissile(mobj_t *mo) S_StartSound(explodemo, sfx_dmpain); } explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (!P_MobjWasRemoved(explodemo)) + if (explodemo) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -435,7 +425,7 @@ void P_ExplodeMissile(mobj_t *mo) S_StartSound(explodemo, sfx_pop); } explodemo = P_SpawnMobj(mo->x, mo->y, mo->z, MT_EXPLODE); - if (!P_MobjWasRemoved(explodemo)) + if (explodemo) { P_SetScale(explodemo, mo->scale); explodemo->destscale = mo->destscale; @@ -1892,12 +1882,13 @@ boolean P_CheckDeathPitCollide(mobj_t *mo) I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); + INT32 special = GETSECSPECIAL(mo->subsector->sector->special, 1); + if (((mo->z <= mo->subsector->sector->floorheight && !(mo->eflags & MFE_VERTICALFLIP) && (mo->subsector->sector->flags & SF_FLIPSPECIAL_FLOOR)) || (mo->z + mo->height >= mo->subsector->sector->ceilingheight && (mo->eflags & MFE_VERTICALFLIP) && (mo->subsector->sector->flags & SF_FLIPSPECIAL_CEILING))) - && (GETSECSPECIAL(mo->subsector->sector->special, 1) == 6 - || GETSECSPECIAL(mo->subsector->sector->special, 1) == 7)) + && (special == 6 || special == 7)) return true; return false; @@ -1908,16 +1899,14 @@ boolean P_CheckSolidLava(mobj_t *mo, ffloor_t *rover) I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); - { - fixed_t topheight = - *rover->t_slope ? P_GetZAt(*rover->t_slope, mo->x, mo->y) : - *rover->topheight; + fixed_t topheight = + *rover->t_slope ? P_GetZAt(*rover->t_slope, mo->x, mo->y) : + *rover->topheight; - if (rover->flags & FF_SWIMMABLE && GETSECSPECIAL(rover->master->frontsector->special, 1) == 3 - && !(rover->master->flags & ML_BLOCKMONSTERS) - && ((rover->master->flags & ML_EFFECT3) || mo->z-mo->momz > topheight - FixedMul(16*FRACUNIT, mo->scale))) - return true; - } + if (rover->flags & FF_SWIMMABLE && GETSECSPECIAL(rover->master->frontsector->special, 1) == 3 + && !(rover->master->flags & ML_BLOCKMONSTERS) + && ((rover->master->flags & ML_EFFECT3) || mo->z-mo->momz > topheight - FixedMul(16*FRACUNIT, mo->scale))) + return true; return false; } @@ -3242,20 +3231,68 @@ void P_DestroyRobots(void) } } +// the below is chasecam only, if you're curious. check out P_CalcPostImg in p_user.c for first person +static void P_CalcChasePostImg(player_t *player, camera_t *thiscam) +{ + const boolean flipcam = (player->pflags & PF_FLIPCAM && !(player->pflags & PF_NIGHTSMODE) && player->mo->eflags & MFE_VERTICALFLIP); + UINT16 postimgflags = 0; + UINT8 i; + + if (encoremode) + postimgflags |= POSTIMG_MIRROR; + if (flipcam) + postimgflags |= POSTIMG_FLIP; + + if (player->awayviewtics && player->awayviewmobj && !P_MobjWasRemoved(player->awayviewmobj)) // Camera must obviously exist + { + camera_t dummycam; + + dummycam.subsector = player->awayviewmobj->subsector; + dummycam.x = player->awayviewmobj->x; + dummycam.y = player->awayviewmobj->y; + dummycam.z = player->awayviewmobj->z; + //dummycam.height = 40*FRACUNIT; // alt view height is 20*FRACUNIT + dummycam.height = 0; // Why? Remote viewpoint cameras have no height. + + // Are we in water? + if (P_CameraCheckWater(&dummycam)) + postimgflags |= POSTIMG_WATER; + if (P_CameraCheckHeat(&dummycam)) + postimgflags |= POSTIMG_HEAT; + } + else + { + // Are we in water? + if (P_CameraCheckWater(thiscam)) + postimgflags |= POSTIMG_WATER; + if (P_CameraCheckHeat(thiscam)) + postimgflags |= POSTIMG_HEAT; + } + + for (i = 0; i <= splitscreen; i++) + { + if (player != &players[displayplayers[i]]) + continue; + + players[displayplayers[i]].postimgflags = postimgflags; + break; + } +} + // P_CameraThinker // // Process the mobj-ish required functions of the camera boolean P_CameraThinker(player_t *player, camera_t *thiscam, boolean resetcalled) { boolean itsatwodlevel = false; - boolean flipcam = (player->pflags & PF_FLIPCAM && !(player->pflags & PF_NIGHTSMODE) && player->mo->eflags & MFE_VERTICALFLIP); - postimg_t postimg = postimg_none; UINT8 i; // This can happen when joining if (thiscam->subsector == NULL || thiscam->subsector->sector == NULL) return true; + P_CalcChasePostImg(player, thiscam); + if (twodlevel) itsatwodlevel = true; else @@ -3271,64 +3308,27 @@ boolean P_CameraThinker(player_t *player, camera_t *thiscam, boolean resetcalled } } - if (encoremode && !flipcam) - postimg = postimg_mirror; - else if (!encoremode && flipcam) - postimg = postimg_flip; - else if (encoremode && flipcam) - postimg = postimg_mirrorflip; - else if (player->awayviewtics && player->awayviewmobj && !P_MobjWasRemoved(player->awayviewmobj)) // Camera must obviously exist - { - camera_t dummycam; - dummycam.subsector = player->awayviewmobj->subsector; - dummycam.x = player->awayviewmobj->x; - dummycam.y = player->awayviewmobj->y; - dummycam.z = player->awayviewmobj->z; - //dummycam.height = 40*FRACUNIT; // alt view height is 20*FRACUNIT - dummycam.height = 0; // Why? Remote viewpoint cameras have no height. - // Are we in water? - if (P_CameraCheckWater(&dummycam)) - postimg = postimg_water; - else if (P_CameraCheckHeat(&dummycam)) - postimg = postimg_heat; - } - else - { - // Are we in water? - if (P_CameraCheckWater(thiscam)) - postimg = postimg_water; - else if (P_CameraCheckHeat(thiscam)) - postimg = postimg_heat; - } - - if (postimg != postimg_none) - { - for (i = 0; i <= splitscreen; i++) - { - if (player != &players[displayplayers[i]]) - continue; - - postimgtype[i] = postimg; - } - } - if (thiscam->momx || thiscam->momy) { - if (!P_TryCameraMove(thiscam->x + thiscam->momx, thiscam->y + thiscam->momy, thiscam)) - { // Never fails for 2D mode. + if (!P_TryCameraMove(thiscam->x + thiscam->momx, thiscam->y + thiscam->momy, thiscam)) // Never fails for 2D mode. + { mobj_t dummy; + dummy.thinker.function.acp1 = (actionf_p1)P_MobjThinker; dummy.subsector = thiscam->subsector; dummy.x = thiscam->x; dummy.y = thiscam->y; dummy.z = thiscam->z; dummy.height = thiscam->height; + if (player->pflags & PF_TIMEOVER) player->kartstuff[k_timeovercam] = (2*TICRATE)+1; - if (!resetcalled && !(player->pflags & PF_NOCLIP || leveltime < introtime) && !P_CheckSight(&dummy, player->mo)) // TODO: "P_CheckCameraSight" instead. + + if (!resetcalled && !(player->pflags & PF_NOCLIP || leveltime < introtime) && !P_CheckSightFast(&dummy, player->mo)) // TODO: "P_CheckCameraSight" instead. P_ResetCamera(player, thiscam); else P_SlideCameraMove(thiscam); + if (resetcalled) // Okay this means the camera is fully reset. return true; } @@ -3337,7 +3337,7 @@ boolean P_CameraThinker(player_t *player, camera_t *thiscam, boolean resetcalled if (!itsatwodlevel) P_CheckCameraPosition(thiscam->x, thiscam->y, thiscam); - thiscam->subsector = R_PointInSubsector(thiscam->x, thiscam->y); + thiscam->subsector = R_PointInSubsectorFast(thiscam->x, thiscam->y); thiscam->floorz = tmfloorz; thiscam->ceilingz = tmceilingz; @@ -3410,8 +3410,8 @@ static void P_PlayerMobjThinker(mobj_t *mobj) I_Assert(mobj != NULL); I_Assert(mobj->player != NULL); I_Assert(!P_MobjWasRemoved(mobj)); - - if (P_MobjWasRemoved(mobj)) + + if (!mobj) return; P_MobjCheckWater(mobj); @@ -6030,41 +6030,38 @@ static void P_KoopaThinker(mobj_t *koopa) // void P_RollPitchMobj(mobj_t* mobj) { - boolean usedist = false; - if (P_MobjWasRemoved(mobj)) - return; + return; - if (cv_sloperolldist.value > 0) - usedist = true; + if (cv_sloperoll.value != 2) + { + mobj->sloperoll = FixedAngle(0); + mobj->slopepitch = FixedAngle(0); + return; + } - if (cv_spriteroll.value && cv_sloperoll.value == 2) - { - K_RollMobjBySlopes(mobj, usedist); - } - else - { - mobj->sloperoll = FixedAngle(0); - mobj->slopepitch = FixedAngle(0); - } + K_RollMobjBySlopes(mobj, cv_sloperolldist.value && !splitscreen); } angle_t P_MobjPitchAndRoll(mobj_t *mobj) { - spritedef_t *sprdef; - spriteframe_t *sprframe; - angle_t ang = 0; + spritedef_t *sprdef; + spriteframe_t *sprframe; + angle_t ang = 0; angle_t camang = 0; angle_t return_angle = 0; - - if (!cv_spriteroll.value) + + if (!cv_sloperoll.value) return 0; - if (P_MobjWasRemoved(mobj)) - return 0; + if (P_MobjWasRemoved(mobj)) + return 0; - size_t rot = mobj->frame & FF_FRAMEMASK; - boolean papersprite = (mobj->frame & FF_PAPERSPRITE); + // if mobj doesent have any of those, no need to do the rest + if (mobj->roll == 0 && mobj->pitch == 0 && mobj->sloperoll == 0 && mobj->slopepitch == 0) + return 0; + + size_t rot = (mobj->frame & FF_FRAMEMASK); if (mobj->skin && mobj->sprite == SPR_PLAY) { @@ -6081,7 +6078,7 @@ angle_t P_MobjPitchAndRoll(mobj_t *mobj) if (rot >= sprdef->numframes) { sprdef = &sprites[states[S_UNKNOWN].sprite]; - rot = states[S_UNKNOWN].frame&FF_FRAMEMASK; + rot = (states[S_UNKNOWN].frame & FF_FRAMEMASK); } sprframe = &sprdef->spriteframes[rot]; @@ -6089,20 +6086,16 @@ angle_t P_MobjPitchAndRoll(mobj_t *mobj) // No sprite frame? I guess it is possible if (!sprframe) return 0; - if (sprframe->rotate != SRF_SINGLE || papersprite) + if (sprframe->rotate != SRF_SINGLE || (mobj->frame & FF_PAPERSPRITE)) { ang = R_PointToAngle(mobj->x, mobj->y) - mobj->angle; camang = R_PointToAngle(mobj->x, mobj->y); } - return_angle = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), mobj->roll) - + FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), mobj->pitch); - - if (cv_sloperoll.value) - { - return_angle += FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), mobj->sloperoll) - + FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), mobj->slopepitch); - } + return_angle = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), mobj->roll) + + FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), mobj->pitch) + + FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), mobj->sloperoll) + + FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), mobj->slopepitch); return return_angle; } @@ -6189,7 +6182,7 @@ void P_MobjThinker(mobj_t *mobj) // Special thinker for scenery objects if (mobj->flags & MF_SCENERY) { - if (LUAh_MobjThinker(mobj)) + if (LUA_HookMobj(mobj, MOBJ_HOOK(MobjThinker))) return; if (P_MobjWasRemoved(mobj)) @@ -6263,7 +6256,7 @@ void P_MobjThinker(mobj_t *mobj) P_RemoveMobj(mobj); return; } - + if (cv_sloperoll.value == 2 && mobj->state == &states[S_SHADOW]) { mobj->slopepitch = mobj->target->slopepitch; @@ -6286,6 +6279,7 @@ void P_MobjThinker(mobj_t *mobj) P_RemoveMobj(mobj); return; } + P_RollPitchMobj(mobj); break; case MT_SMOLDERING: @@ -6886,7 +6880,7 @@ void P_MobjThinker(mobj_t *mobj) mobj->fuse--; if (!mobj->fuse) { - if (!LUAh_MobjFuse(mobj)) + if (!LUA_HookMobj(mobj, MOBJ_HOOK(MobjFuse))) P_RemoveMobj(mobj); return; } @@ -6901,13 +6895,13 @@ void P_MobjThinker(mobj_t *mobj) // Check for a Lua thinker first if (!mobj->player) { - if (LUAh_MobjThinker(mobj) || P_MobjWasRemoved(mobj)) + if (LUA_HookMobj(mobj, MOBJ_HOOK(MobjThinker)) || P_MobjWasRemoved(mobj)) return; } else if (!mobj->player->spectator) { // You cannot short-circuit the player thinker like you can other thinkers. - LUAh_MobjThinker(mobj); + LUA_HookMobj(mobj, MOBJ_HOOK(MobjThinker)); if (P_MobjWasRemoved(mobj)) return; } @@ -6916,7 +6910,7 @@ void P_MobjThinker(mobj_t *mobj) // separate thinker if (mobj->flags & MF_PUSHABLE || (mobj->info->flags & MF_PUSHABLE && mobj->fuse)) { - if (P_MobjWasRemoved(mobj)) + if (!mobj) return; P_MobjCheckWater(mobj); @@ -6932,7 +6926,7 @@ void P_MobjThinker(mobj_t *mobj) } else if (mobj->flags & MF_BOSS) { - if (LUAh_BossThinker(mobj)) + if (LUA_HookMobj(mobj, MOBJ_HOOK(BossThinker))) { if (P_MobjWasRemoved(mobj)) return; @@ -8899,7 +8893,7 @@ void P_MobjThinker(mobj_t *mobj) fixed_t x, y, z; mobj_t *flagmo, *newmobj; - if (!LUAh_MobjFuse(mobj) && !P_MobjWasRemoved(mobj)) + if (!LUA_HookMobj(mobj, MOBJ_HOOK(MobjFuse)) && !P_MobjWasRemoved(mobj)) { switch (mobj->type) { @@ -9234,7 +9228,6 @@ void P_PushableThinker(mobj_t *mobj) if (GETSECSPECIAL(sec->special, 2) == 1 && mobj->z == sec->floorheight) P_LinedefExecute(sec->tag, mobj, sec); -// else if (GETSECSPECIAL(sec->special, 2) == 8) { sector_t *sec2; @@ -9385,7 +9378,18 @@ mobj_t *P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type) { const mobjinfo_t *info = &mobjinfo[type]; state_t *st; - mobj_t *mobj = Z_Calloc(sizeof (*mobj), PU_LEVEL, NULL); + mobj_t *mobj; + + if (mobjcache != NULL) + { + mobj = mobjcache; + mobjcache = mobjcache->hnext; + memset(mobj, 0, sizeof(*mobj)); + } + else + { + mobj = Z_Calloc(sizeof (*mobj), PU_LEVEL, NULL); + } // this is officially a mobj, declared as soon as possible. mobj->thinker.function.acp1 = (actionf_p1)P_MobjThinker; @@ -9434,11 +9438,11 @@ mobj_t *P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type) mobj->destscale = mapobjectscale; mobj->scalespeed = mapobjectscale/12; } - + // Sprite rendering - mobj->realxscale = mobj->realyscale = mobj->scale; + mobj->realxscale = mobj->realyscale = mobj->scale; mobj->spritexscale = mobj->realxscale; - mobj->spriteyscale = mobj->realyscale; + mobj->spriteyscale = mobj->realyscale; mobj->spritexoffset = mobj->spriteyoffset = 0; // Funni slam sound when landing @@ -9490,7 +9494,7 @@ mobj_t *P_SpawnMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype_t type) // DANGER! This can cause P_SpawnMobj to return NULL! // Avoid using P_RemoveMobj on the newly created mobj in "MobjSpawn" Lua hooks! - if (LUAh_MobjSpawn(mobj)) + if (LUA_HookMobj(mobj, MOBJ_HOOK(MobjSpawn))) { if (P_MobjWasRemoved(mobj)) return NULL; @@ -9846,7 +9850,18 @@ mobj_t *P_SpawnShadowMobj(mobj_t * caster) { const mobjinfo_t *info = &mobjinfo[MT_SHADOW]; state_t *st; - mobj_t *mobj = Z_Calloc(sizeof (*mobj), PU_LEVEL, NULL); + mobj_t *mobj; + + if (mobjcache != NULL) + { + mobj = mobjcache; + mobjcache = mobjcache->hnext; + memset(mobj, 0, sizeof(*mobj)); + } + else + { + mobj = Z_Calloc(sizeof (*mobj), PU_LEVEL, NULL); + } // this is officially a mobj, declared as soon as possible. mobj->thinker.function.acp1 = (actionf_p1)P_MobjThinker; @@ -9892,11 +9907,11 @@ mobj_t *P_SpawnShadowMobj(mobj_t * caster) mobj->destscale = mapobjectscale; mobj->scalespeed = mapobjectscale/12; } - + // Sprite rendering - mobj->spritexscale = mobj->spriteyscale = mobj->scale; + mobj->spritexscale = mobj->spriteyscale = mobj->scale; mobj->spritexoffset = mobj->spriteyoffset = 0; - + // set subsector and/or block links P_SetThingPosition(mobj); I_Assert(mobj->subsector != NULL); @@ -9994,10 +10009,13 @@ static precipmobj_t *P_SpawnPrecipMobj(fixed_t x, fixed_t y, fixed_t z, mobjtype if (mobj->floorz != starting_floorz) mobj->precipflags |= PCF_FOF; - else if (GETSECSPECIAL(mobj->subsector->sector->special, 1) == 7 - || GETSECSPECIAL(mobj->subsector->sector->special, 1) == 6 - || mobj->subsector->sector->floorpic == skyflatnum) - mobj->precipflags |= PCF_PIT; + else + { + INT32 special = GETSECSPECIAL(mobj->subsector->sector->special, 1); + + if (special == 7 || special == 6 || mobj->subsector->sector->floorpic == skyflatnum) + mobj->precipflags |= PCF_PIT; + } R_ResetPrecipitationMobjInterpolationState(mobj); @@ -10022,7 +10040,7 @@ void P_RemoveMobj(mobj_t *mobj) return; // something already removing this mobj. mobj->thinker.function.acp1 = (actionf_p1)P_RemoveThinkerDelayed; // shh. no recursing. - LUAh_MobjRemoved(mobj); + LUA_HookMobj(mobj, MOBJ_HOOK(MobjRemoved)); mobj->thinker.function.acp1 = (actionf_p1)P_MobjThinker; // needed for P_UnsetThingPosition, etc. to work. // Rings only, please! @@ -10100,7 +10118,7 @@ void P_RemoveMobj(mobj_t *mobj) P_SetTarget(&mobj->hprev->hnext, cachenext); P_SetTarget(&mobj->hprev, NULL); } - + // clear the reference from the mapthing if (mobj->spawnpoint) mobj->spawnpoint->mobj = NULL; @@ -10117,7 +10135,9 @@ void P_RemoveMobj(mobj_t *mobj) // Invalidate mobj_t data to cause crashes if accessed! memset(mobj, 0xff, sizeof(mobj_t)); #endif - Z_Free(mobj); // No refrences? Can be removed immediately! :D + // no references, dump it directly in the mobj cache + mobj->hnext = mobjcache; + mobjcache = mobj; } else { // Add thinker just to delay removing it until refrences are gone. @@ -10210,19 +10230,26 @@ void P_SpawnPrecipitation(void) if (dedicated || !cv_drawdist_precip.value || curWeather == PRECIP_NONE) // SRB2Kart return; + fixed_t density = (cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT); + + if (cv_lessprecip.value) + density *= 2; // just spawn half the precip + // Use the blockmap to narrow down our placing patterns for (i = 0; i < bmapwidth*bmapheight; ++i) { basex = bmaporgx + (i % bmapwidth) * MAPBLOCKSIZE; basey = bmaporgy + (i / bmapwidth) * MAPBLOCKSIZE; - for (j = 0; j < FRACUNIT; j += cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT) + // If mobjscale < FRACUNIT, each blockmap cell covers + // more area so spawn more precipitation in that area. + for (j = 0; j < FRACUNIT; j += density) { INT32 floorz; INT32 ceilingz; - x = ((cv_lessprecip.value ? basex*1.5 : basex) + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3)); - y = ((cv_lessprecip.value ? basey*1.5 : basey) + ((M_RandomKey(MAPBLOCKUNITS<<3)<>3)); + x = basex + ((M_RandomKey(MAPBLOCKUNITS << 3) << FRACBITS) >> 3); + y = basey + ((M_RandomKey(MAPBLOCKUNITS << 3) << FRACBITS) >> 3); precipsector = R_IsPointInSubsector(x, y); @@ -10291,7 +10318,7 @@ void P_PrecipitationEffects(void) INT32 volume; size_t i; - boolean sounds_rain = true; + boolean rainsfx = true; boolean sounds_thunder = true; boolean effects_lightning = true; boolean lightningStrike = false; @@ -10324,7 +10351,7 @@ void P_PrecipitationEffects(void) effects_lightning = false; break; case PRECIP_STORM_NORAIN: // no rain, lightning and thunder allowed - sounds_rain = false; + rainsfx = false; case PRECIP_STORM: // everything. break; default: @@ -10332,6 +10359,8 @@ void P_PrecipitationEffects(void) return; } + boolean sounds_rain = ((cv_drawdist_precip.value != 0) && rainsfx && (!leveltime || leveltime % 80 == 1)); + // Currently thunderstorming with lightning, and we're sounding the thunder... // and where there's thunder, there's gotta be lightning! if (effects_lightning && lightningStrike) @@ -10351,38 +10380,57 @@ void P_PrecipitationEffects(void) if (sound_disabled) return; // Sound off? D'aw, no fun. + if (!sounds_rain && !sounds_thunder) + return; // no need to calculate volume at ALL + if (players[displayplayers[0]].mo->subsector->sector->ceilingpic == skyflatnum) volume = 255; // Sky above? We get it full blast. else { /* GCC is optimizing away y >= yl, FUCK YOU */ - volatile fixed_t x, y, yl, yh, xl, xh; + INT64 x, y, yl, yh, xl, xh; fixed_t closedist, newdist; // Essentially check in a 1024 unit radius of the player for an outdoor area. - yl = players[displayplayers[0]].mo->y - 1024*FRACUNIT; - yh = players[displayplayers[0]].mo->y + 1024*FRACUNIT; - xl = players[displayplayers[0]].mo->x - 1024*FRACUNIT; - xh = players[displayplayers[0]].mo->x + 1024*FRACUNIT; - closedist = 2048*FRACUNIT; +#define RADIUSSTEP (64*FRACUNIT) +#define SEARCHRADIUS (16*RADIUSSTEP) + yl = yh = players[displayplayers[0]].mo->y; + yl -= SEARCHRADIUS; + while (yl < INT32_MIN) + yl += RADIUSSTEP; + yh += SEARCHRADIUS; + while (yh > INT32_MAX) + yh -= RADIUSSTEP; - for (y = yl; y >= yl && y <= yh; y += FRACUNIT*64) - for (x = xl; x >= xl && x <= xh; x += FRACUNIT*64) + xl = xh = players[displayplayers[0]].mo->x; + xl -= SEARCHRADIUS; + while (xl < INT32_MIN) + xl += RADIUSSTEP; + xh += SEARCHRADIUS; + while (xh > INT32_MAX) + xh -= RADIUSSTEP; + + closedist = SEARCHRADIUS*2; +#undef SEARCHRADIUS + for (y = yl; y <= yh; y += RADIUSSTEP) + for (x = xl; x <= xh; x += RADIUSSTEP) { - if (R_PointInSubsector(x, y)->sector->ceilingpic != skyflatnum) // Found the outdoors! + if (R_PointInSubsectorFast((fixed_t)x, (fixed_t)y)->sector->ceilingpic != skyflatnum) // Found the outdoors! continue; - newdist = S_CalculateSoundDistance(players[displayplayers[0]].mo->x, players[displayplayers[0]].mo->y, 0, x, y, 0); + newdist = S_CalculateSoundDistance(players[displayplayers[0]].mo->x, players[displayplayers[0]].mo->y, 0, (fixed_t)x, (fixed_t)y, 0); + if (newdist < closedist) closedist = newdist; } volume = 255 - (closedist>>(FRACBITS+2)); } +#undef RADIUSSTEP volume = CLAMP(volume, 0, 255); - if (sounds_rain && (!leveltime || leveltime % 80 == 1)) + if (sounds_rain) S_StartSoundAtVolume(players[displayplayers[0]].mo, sfx_rainin, volume); if (!sounds_thunder) @@ -10567,7 +10615,8 @@ void P_SpawnPlayer(INT32 playernum) } // spawn as spectator determination - if (multiplayer && demo.playback); // Don't mess with spectator values since the demo setup handles them already. + if (multiplayer && demo.playback) + ; // Don't mess with spectator values since the demo setup handles them already. else if (!G_GametypeHasSpectators()) p->spectator = false; else if (netgame && p->jointime <= 1 && pcount) @@ -10634,15 +10683,8 @@ void P_SpawnPlayer(INT32 playernum) // (usefulness: when body mobj is detached from player (who respawns), // the dead body mobj retains the skin through the 'spritedef' override). mobj->skin = &skins[p->skin]; - if (p->localskin > 0) - { - if (p->skinlocal) - mobj->localskin = &localskins[p->localskin - 1]; - else - mobj->localskin = & skins[p->localskin - 1]; - } - else - mobj->localskin = 0; + + mobj->localskin = ((p->localskin > 0) ? (p->skinlocal ? &localskins[p->localskin - 1] : &skins[p->localskin - 1]) : 0); mobj->skinlocal = p->skinlocal; mobj->health = p->health; @@ -11250,7 +11292,8 @@ void P_SpawnMapThing(mapthing_t *mthing) mobj = P_SpawnMobj(x, y, z, i); - if (!mobj || P_MobjWasRemoved(mobj)) { + if (!mobj || P_MobjWasRemoved(mobj)) + { CONS_Alert(CONS_ERROR, "Failed to spawn map thing #%d at %d, %d. This will crash vanilla clients!\n", mthing->type, x>>FRACBITS, y>>FRACBITS); return; } @@ -11784,12 +11827,8 @@ void P_SpawnHoopsAndRings(mapthing_t *mthing) z = mthing->options << FRACBITS; hoopcenter = P_SpawnMobj(x, y, z, MT_HOOPCENTER); - hoopcenter->spawnpoint = mthing; - // Screw these damn hoops, I need this thinker. - //hoopcenter->flags |= MF_NOTHINK; - z += sec->f_slope ? P_GetZAt(sec->f_slope, x, y) : sec->floorheight; @@ -11835,10 +11874,8 @@ void P_SpawnHoopsAndRings(mapthing_t *mthing) mobj = P_SpawnMobj(finalx, finaly, finalz, MT_HOOP); - //if (maptol & TOL_XMAS) - //P_SetMobjState(mobj, mobj->info->seestate + (i & 1)); - mobj->z -= mobj->height/2; + P_SetTarget(&mobj->target, hoopcenter); // Link the sprite to the center. mobj->fuse = 0; @@ -11975,9 +12012,6 @@ void P_SpawnHoopsAndRings(mapthing_t *mthing) mobj = P_SpawnMobj(finalx, finaly, finalz, MT_HOOP); - //if (maptol & TOL_XMAS) - //P_SetMobjState(mobj, mobj->info->seestate + (i & 1)); - mobj->z -= mobj->height/2; P_SetTarget(&mobj->target, hoopcenter); // Link the sprite to the center. mobj->fuse = 0; @@ -12348,10 +12382,6 @@ void P_ColorTeamMissile(mobj_t *missile, player_t *source) else if (source->ctfteam == 1) missile->color = skincolor_redring; } - /* - else - missile->color = player->mo->color; //copy color - */ } // diff --git a/src/p_mobj.h b/src/p_mobj.h index 7a8151dc3..cd7c64dc1 100644 --- a/src/p_mobj.h +++ b/src/p_mobj.h @@ -261,6 +261,7 @@ typedef enum { PCF_SPLASH = 1<<4, // Splashed on the ground, return to the ceiling after the animation's over PCF_THUNK = 1<<5, // Ran the thinker this tic. } precipflag_t; + // Map Object definition. typedef struct mobj_s { @@ -287,8 +288,7 @@ typedef struct mobj_s spritenum_t sprite; // used to find patch_t and flip value UINT32 frame; // frame number, plus bits see p_pspr.h UINT16 anim_duration; // for FF_ANIMATE states - - UINT32 renderflags; // render flags + fixed_t spritexscale, spriteyscale; fixed_t spritexoffset, spriteyoffset; fixed_t old_spritexscale, old_spriteyscale; @@ -440,8 +440,7 @@ typedef struct precipmobj_s spritenum_t sprite; // used to find patch_t and flip value UINT32 frame; // frame number, plus bits see p_pspr.h UINT16 anim_duration; // for FF_ANIMATE states - - UINT32 renderflags; // render flags + fixed_t spritexscale, spriteyscale; fixed_t spritexoffset, spriteyoffset; fixed_t old_spritexscale, old_spriteyscale; @@ -450,7 +449,7 @@ typedef struct precipmobj_s fixed_t realxscale, realyscale; // funn-E streeetch fixed_t stretchslam; // "squish" effect when you land - + //sloperollangle angle_t sloperoll, slopepitch; angle_t old_sloperoll, old_slopepitch; diff --git a/src/p_polyobj.c b/src/p_polyobj.c index f890b0bd0..ffc6651b8 100644 --- a/src/p_polyobj.c +++ b/src/p_polyobj.c @@ -153,6 +153,9 @@ FUNCINLINE static ATTRINLINE void PolyObj_AddThinker(thinker_t *th) th->next = thinkercap.next; th->prev = &thinkercap; thinkercap.next = th; + + th->references = 0; + th->cachable = false; // not initialising this made the mobjcache die thx! } static void FreeSideLists(void) diff --git a/src/p_saveg.c b/src/p_saveg.c index efb96f75c..4b79bc886 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -296,7 +296,7 @@ static void P_NetArchivePlayers(savebuffer_t *save, boolean resending) // // P_NetUnArchivePlayers // -static void P_NetUnArchivePlayers(savebuffer_t *save, boolean resending) +static void P_NetUnArchivePlayers(boolean reloading) { INT32 i, j; UINT16 flags; @@ -306,8 +306,8 @@ static void P_NetUnArchivePlayers(savebuffer_t *save, boolean resending) for (i = 0; i < MAXPLAYERS; i++) { - if (resending) - adminplayers[i] = (INT32)READSINT8(save->p); + if (reloading) + adminplayers[i] = (INT32)READSINT8(save_p); // Do NOT memset player struct to 0 // other areas may initialize data elsewhere @@ -317,8 +317,8 @@ static void P_NetUnArchivePlayers(savebuffer_t *save, boolean resending) // NOTE: sending tics should (hopefully) no longer be necessary - if (resending) - READSTRINGN(save->p, player_names[i], MAXPLAYERNAME); + if (reloading) + READSTRINGN(save_p, player_names[i], MAXPLAYERNAME); players[i].aiming = READANGLE(save->p); players[i].awayviewaiming = READANGLE(save->p); @@ -344,7 +344,7 @@ static void P_NetUnArchivePlayers(savebuffer_t *save, boolean resending) players[i].flashpal = READUINT16(save->p); players[i].flashcount = READUINT16(save->p); - if (resending) + if (reloading) { players[i].skincolor = READUINT8(save->p); players[i].skin = READINT32(save->p); @@ -2159,11 +2159,6 @@ static void LoadMobjThinker(savebuffer_t *save, actionf_p1 thinker) mobj->realyscale = FRACUNIT; mobj->stretchslam = 0; - mobj->stretchslam = 0; - mobj->slamsoundtimer = 0; - - mobj->mirrored = 0; - // Timer for slam sound effect mobj->slamsoundtimer = 0; diff --git a/src/p_setup.c b/src/p_setup.c index f8a1dde52..280c91935 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -63,7 +63,7 @@ #include "md5.h" // map MD5 -// for LUAh_MapLoad +// for MapLoad hook #include "lua_script.h" #include "lua_hook.h" @@ -460,7 +460,11 @@ FUNCINLINE static ATTRINLINE void P_LoadRawVertexes(UINT8 *data) * \param seg Seg to compute length for. * \return Length in fracunits. */ +#if defined (WALLSPLATS) || defined (FLOORSPLATS) fixed_t P_SegLength(seg_t *seg) +#else +static inline fixed_t P_SegLength(seg_t *seg) +#endif { INT64 dx = (seg->v2->x - seg->v1->x)>>1; INT64 dy = (seg->v2->y - seg->v1->y)>>1; @@ -510,7 +514,7 @@ void P_UpdateSegLightOffset(seg_t *li) // Loads the SEGS resource from a level. static void P_LoadRawSegs(UINT8 *data) { - INT32 linedef, side; + INT32 rawlinedef, rawside; mapseg_t *ml = (mapseg_t*)data; seg_t *li = segs; line_t *ldef; @@ -530,14 +534,14 @@ static void P_LoadRawSegs(UINT8 *data) li->angle = (SHORT(ml->angle))<offset = (SHORT(ml->offset))<linedef); - ldef = &lines[linedef]; + rawlinedef = SHORT(ml->linedef); + ldef = &lines[rawlinedef]; li->linedef = ldef; - li->side = side = SHORT(ml->side); - li->sidedef = &sides[ldef->sidenum[side]]; - li->frontsector = sides[ldef->sidenum[side]].sector; + li->side = rawside = SHORT(ml->side); + li->sidedef = &sides[ldef->sidenum[rawside]]; + li->frontsector = sides[ldef->sidenum[rawside]].sector; if (ldef->flags & ML_TWOSIDED) - li->backsector = sides[ldef->sidenum[side^1]].sector; + li->backsector = sides[ldef->sidenum[rawside^1]].sector; else li->backsector = 0; @@ -1542,16 +1546,23 @@ static void P_CreateBlockMap(void) // First find limits of map for (i = 0; i < numvertexes; i++) { - if (vertexes[i].x>>FRACBITS < minx) - minx = vertexes[i].x>>FRACBITS; - else if (vertexes[i].x>>FRACBITS > maxx) - maxx = vertexes[i].x>>FRACBITS; - if (vertexes[i].y>>FRACBITS < miny) - miny = vertexes[i].y>>FRACBITS; - else if (vertexes[i].y>>FRACBITS > maxy) - maxy = vertexes[i].y>>FRACBITS; + fixed_t t; + + if ((t = vertexes[i].x) < minx) + minx = t; + else if (t > maxx) + maxx = t; + if ((t = vertexes[i].y) < miny) + miny = t; + else if (t > maxy) + maxy = t; } + minx >>= FRACBITS; + maxx >>= FRACBITS; + miny >>= FRACBITS; + maxy >>= FRACBITS; + // Save blockmap parameters bmaporgx = minx << FRACBITS; bmaporgy = miny << FRACBITS; @@ -2426,7 +2437,7 @@ static void P_SetupCamera(UINT8 pnum, camera_t *cam) cam->y = players[pnum].mo->y; cam->z = players[pnum].mo->z; cam->angle = players[pnum].mo->angle; - cam->subsector = R_PointInSubsector(cam->x, cam->y); // make sure camera has a subsector set -- Monster Iestyn (12/11/18) + cam->subsector = R_PointInSubsectorFast(cam->x, cam->y); // make sure camera has a subsector set -- Monster Iestyn (12/11/18) } else { @@ -2451,7 +2462,7 @@ static void P_SetupCamera(UINT8 pnum, camera_t *cam) cam->y = thing->y; cam->z = thing->z; cam->angle = FixedAngle((fixed_t)thing->angle << FRACBITS); - cam->subsector = R_PointInSubsector(cam->x, cam->y); // make sure camera has a subsector set -- Monster Iestyn (12/11/18) + cam->subsector = R_PointInSubsectorFast(cam->x, cam->y); // make sure camera has a subsector set -- Monster Iestyn (12/11/18) } } @@ -2466,17 +2477,11 @@ static void P_InitCamera(void) P_SetupCamera(displayplayers[i], &camera[i]); // Though, I don't think anyone would care about cam_rotate being reset back to the only value that makes sense :P - if (!cv_cam_rotate.changed) - CV_Set(&cv_cam_rotate, cv_cam_rotate.defaultvalue); - - if (!cv_cam2_rotate.changed) - CV_Set(&cv_cam2_rotate, cv_cam2_rotate.defaultvalue); - - if (!cv_cam3_rotate.changed) - CV_Set(&cv_cam3_rotate, cv_cam3_rotate.defaultvalue); - - if (!cv_cam4_rotate.changed) - CV_Set(&cv_cam4_rotate, cv_cam4_rotate.defaultvalue); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (!cv_cam_rotate[i].changed) + CV_Set(&cv_cam_rotate[i], cv_cam_rotate[i].defaultvalue); + } displayplayers[0] = consoleplayer; // Start with your OWN view, please! } @@ -2494,6 +2499,9 @@ static void P_InitMinimapInfo(void) fixed_t a; fixed_t b; node_t *bsp = &nodes[numnodes-1]; + + minimapinfo.minimap_pic = NULL; + lumpnum = W_CheckNumForName(va("%sR", G_BuildMapName(gamemap))); if (lumpnum != -1) @@ -2505,6 +2513,7 @@ static void P_InitMinimapInfo(void) minimapinfo.max_x = bsp->bbox[0][BOXRIGHT]; minimapinfo.min_y = bsp->bbox[0][BOXBOTTOM]; minimapinfo.max_y = bsp->bbox[0][BOXTOP]; + if (bsp->bbox[1][BOXLEFT] < minimapinfo.min_x) minimapinfo.min_x = bsp->bbox[1][BOXLEFT]; if (bsp->bbox[1][BOXRIGHT] > minimapinfo.max_x) @@ -2513,15 +2522,19 @@ static void P_InitMinimapInfo(void) minimapinfo.min_y = bsp->bbox[1][BOXBOTTOM]; if (bsp->bbox[1][BOXTOP] > minimapinfo.max_y) minimapinfo.max_y = bsp->bbox[1][BOXTOP]; + // You might be wondering why these are being bitshift here // it's because mapwidth and height would otherwise overflow for maps larger than half the size possible... // map boundaries and sizes will ALWAYS be whole numbers thankfully // later calculations take into consideration that these are actually not in terms of FRACUNIT though minimapinfo.map_w = (minimapinfo.max_x >>= FRACBITS) - (minimapinfo.min_x >>= FRACBITS); minimapinfo.map_h = (minimapinfo.max_y >>= FRACBITS) - (minimapinfo.min_y >>= FRACBITS); + minimapinfo.minimap_w = minimapinfo.minimap_h = 100; + a = FixedDiv(minimapinfo.minimap_w<>(FRACBITS-4); @@ -2535,8 +2548,10 @@ static void P_InitMinimapInfo(void) } minimapinfo.zoom = b; } + minimapinfo.zoom >>= (FRACBITS-4); minimapinfo.zoom -= (minimapinfo.zoom/20); + // These should always be small enough to be bitshift back right now minimapinfo.offs_x = FixedMul((minimapinfo.min_x + minimapinfo.map_w/2) << FRACBITS, minimapinfo.zoom); minimapinfo.offs_y = FixedMul((minimapinfo.min_y + minimapinfo.map_h/2) << FRACBITS, minimapinfo.zoom); @@ -2587,9 +2602,6 @@ boolean P_SetupLevel(boolean skipprecip, boolean reloadinggamestate) P_LevelInitStuff(reloadinggamestate); - for (i = 0; i <= splitscreen; i++) - postimgtype[i] = postimg_none; - if (mapheaderinfo[gamemap-1]->forcecharacter[0] != '\0' && atoi(mapheaderinfo[gamemap-1]->forcecharacter) != 255) P_ForceCharacter(mapheaderinfo[gamemap-1]->forcecharacter); @@ -2600,18 +2612,11 @@ boolean P_SetupLevel(boolean skipprecip, boolean reloadinggamestate) if (!dedicated) { - if (!cv_chasecam.changed) - CV_SetValue(&cv_chasecam, chase); - - // same for second player - if (!cv_chasecam2.changed) - CV_SetValue(&cv_chasecam2, chase); - - if (!cv_chasecam3.changed) - CV_SetValue(&cv_chasecam3, chase); - - if (!cv_chasecam4.changed) - CV_SetValue(&cv_chasecam4, chase); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (!cv_chasecam[i].changed) + CV_SetValue(&cv_chasecam[i], chase); + } } // Initial height of PointOfView @@ -2742,6 +2747,8 @@ boolean P_SetupLevel(boolean skipprecip, boolean reloadinggamestate) R_ClearLevelSplats(); #endif + mobjcache = NULL; + R_InitializeLevelInterpolators(); P_InitThinkers(); @@ -3006,12 +3013,11 @@ boolean P_SetupLevel(boolean skipprecip, boolean reloadinggamestate) } P_PreTicker(2); if (!reloadinggamestate) - LUAh_MapLoad(); + LUA_HookInt(gamemap, HOOK(MapLoad)); } if (rendermode != render_none && !reloadinggamestate) { - R_ResetViewInterpolation(0); R_ResetViewInterpolation(0); R_UpdateMobjInterpolators(); } @@ -3157,11 +3163,6 @@ UINT16 P_PartialAddWadFile(const char *wadfilename, boolean local) // S_LoadMusicDefs(wadnum); - // - // edit music defs for stuff like musictest - // - S_LoadMTDefs(wadnum); - // // search for maps // diff --git a/src/p_setup.h b/src/p_setup.h index c6a18915a..7f90564e0 100644 --- a/src/p_setup.h +++ b/src/p_setup.h @@ -88,6 +88,11 @@ SINT8 P_PartialAddGetStage(void); boolean P_RunSOC(const char *socfilename); void P_WriteThings(lumpnum_t lump); + +#if defined (WALLSPLATS) || defined (FLOORSPLATS) +fixed_t P_SegLength(seg_t *seg); +#endif + void P_UpdateSegLightOffset(seg_t *li); size_t P_PrecacheLevelFlats(void); void P_AllocMapHeader(INT16 i); diff --git a/src/p_sight.c b/src/p_sight.c index b482403cb..1d71e5553 100644 --- a/src/p_sight.c +++ b/src/p_sight.c @@ -38,66 +38,21 @@ static INT32 sightcounts[2]; // // Returns side 0 (front), 1 (back), or 2 (on). // -static INT32 P_DivlineSide(fixed_t x, fixed_t y, divline_t *node) +// killough 4/19/98: made static, cleaned up +static INT32 P_DivlineSide(fixed_t x, fixed_t y, const divline_t *node) { - fixed_t dx, dy, left, right; - - if (!node->dx) - { - if (x == node->x) - return 2; - - if (x <= node->x) - return (node->dy > 0); - - return (node->dy < 0); - } - - if (!node->dy) - { - if (y == node->y) - return 2; - - if (y <= node->y) - return (node->dx < 0); - - return (node->dx > 0); - } - - dx = x - node->x; - dy = y - node->y; - - left = (node->dy>>FRACBITS) * (dx>>FRACBITS); - right = (dy>>FRACBITS) * (node->dx>>FRACBITS); - - if (right < left) - return 0; // front side - - if (left == right) - return 2; - - return 1; // back side + fixed_t left, right; + return + !node->dx ? x == node->x ? 2 : x <= node->x ? node->dy > 0 : node->dy < 0 : + !node->dy ? y == node->y ? 2 : y <= node->y ? node->dx < 0 : node->dx > 0 : + (right = ((y - node->y) >> FRACBITS) * (node->dx >> FRACBITS)) < + (left = ((x - node->x) >> FRACBITS) * (node->dy >> FRACBITS)) ? 0 : + right == left ? 2 : 1; } -// -// P_InterceptVector2 -// -// Returns the fractional intercept point along the first divline. -// This is only called by the addthings and addlines traversers. -// -static fixed_t P_InterceptVector2(divline_t *v2, divline_t *v1) +static INT32 P_DivlineCrossed(fixed_t x1, fixed_t y1, fixed_t x2, fixed_t y2, const divline_t *node) { - fixed_t frac, num, den; - - den = FixedMul(v1->dy>>8, v2->dx) - FixedMul(v1->dx>>8, v2->dy); - - if (!den) - return 0; - - num = FixedMul((v1->x - v2->x)>>8, v1->dy) + FixedMul((v2->y - v1->y)>>8, v1->dx); - frac = FixedDiv(num, den); - - return frac; + return (P_DivlineSide(x1, y1, node) == P_DivlineSide(x2, y2, node)); } static boolean P_CrossSubsecPolyObj(polyobj_t *po, register los_t *los) @@ -135,23 +90,21 @@ static boolean P_CrossSubsecPolyObj(polyobj_t *po, register los_t *los) v2 = line->v2; // line isn't crossed? - if (P_DivlineSide(v1->x, v1->y, &los->strace) == - P_DivlineSide(v2->x, v2->y, &los->strace)) + if (P_DivlineCrossed(v1->x, v1->y, v2->x, v2->y, &los->strace)) continue; divl.dx = v2->x - (divl.x = v1->x); divl.dy = v2->y - (divl.y = v1->y); // line isn't crossed? - if (P_DivlineSide(los->strace.x, los->strace.y, &divl) == - P_DivlineSide(los->t2x, los->t2y, &divl)) + if (P_DivlineCrossed(los->strace.x, los->strace.y, los->t2x, los->t2y, &divl)) continue; // stop because it is not two sided //if (!(po->flags & POF_TESTHEIGHT)) //return false; - frac = P_InterceptVector2(&los->strace, &divl); + frac = P_InterceptVector(&los->strace, &divl); // get slopes of top and bottom of this polyobject line topslope = FixedDiv(polysec->ceilingheight - los->sightzstart , frac); @@ -232,16 +185,14 @@ static boolean P_CrossSubsector(size_t num, register los_t *los) v2 = line->v2; // line isn't crossed? - if (P_DivlineSide(v1->x, v1->y, &los->strace) == - P_DivlineSide(v2->x, v2->y, &los->strace)) + if (P_DivlineCrossed(v1->x, v1->y, v2->x, v2->y, &los->strace)) continue; divl.dx = v2->x - (divl.x = v1->x); divl.dy = v2->y - (divl.y = v1->y); // line isn't crossed? - if (P_DivlineSide(los->strace.x, los->strace.y, &divl) == - P_DivlineSide(los->t2x, los->t2y, &divl)) + if (P_DivlineCrossed(los->strace.x, los->strace.y, los->t2x, los->t2y, &divl)) continue; // stop because it is not two sided anyway @@ -249,7 +200,7 @@ static boolean P_CrossSubsector(size_t num, register los_t *los) return false; // calculate fractional intercept (how far along we are divided by how far we are from t2) - frac = P_InterceptVector2(&los->strace, &divl); + frac = P_InterceptVector(&los->strace, &divl); front = seg->frontsector; back = seg->backsector; @@ -348,25 +299,34 @@ static boolean P_CrossSubsector(size_t num, register los_t *los) // if strace crosses the given node successfully. // // killough 4/20/98: rewritten to remove tail recursion, clean up, and optimize - -static boolean P_CrossBSPNode(INT32 bspnum, register los_t *los) +static boolean P_CrossBSPNode(INT32 bspnum, register los_t *los, boolean fast) { while (!(bspnum & NF_SUBSECTOR)) { register node_t *bsp = nodes + bspnum; - INT32 side = P_DivlineSide(los->strace.x,los->strace.y,(divline_t *)bsp)&1; - if (side == P_DivlineSide(los->t2x, los->t2y, (divline_t *) bsp)) - bspnum = bsp->children[side]; // doesn't touch the other side - else // the partition plane is crossed here + + INT32 side = (fast ? R_PointOnSideFast(los->strace.x, los->strace.y, bsp) : (P_DivlineSide(los->strace.x,los->strace.y, (divline_t *)bsp) & 1)); + INT32 side2 = (fast ? R_PointOnSideFast(los->t2x, los->t2y, bsp) : P_DivlineSide(los->t2x, los->t2y, (divline_t *) bsp)); + + if (side == side2) { - if (!P_CrossBSPNode(bsp->children[side], los)) - return 0; // cross the starting side + bspnum = bsp->children[side]; // doesn't touch the other side + } + else + { + // the partition plane is crossed here + if (!P_CrossBSPNode(bsp->children[side], los, fast)) + { + return false; // cross the starting side + } else - bspnum = bsp->children[side^1]; // cross the ending side + { + bspnum = bsp->children[side^1]; // cross the ending side + } } } - return - P_CrossSubsector((bspnum == -1 ? 0 : bspnum & ~NF_SUBSECTOR), los); + + return P_CrossSubsector((bspnum == -1 ? 0 : bspnum & ~NF_SUBSECTOR), los); } // @@ -375,7 +335,7 @@ static boolean P_CrossBSPNode(INT32 bspnum, register los_t *los) // Returns true if a straight line between t1 and t2 is unobstructed. // Uses REJECT. // -boolean P_CheckSight(mobj_t *t1, mobj_t *t2) +boolean P_CheckSight2(mobj_t *t1, mobj_t *t2, boolean fast) { const sector_t *s1, *s2; size_t pnum; @@ -492,5 +452,5 @@ boolean P_CheckSight(mobj_t *t1, mobj_t *t2) } // the head node is the last node output - return P_CrossBSPNode((INT32)numnodes - 1, &los); -} \ No newline at end of file + return (P_CrossBSPNode((INT32)numnodes - 1, &los, fast)); +} diff --git a/src/p_slopes.c b/src/p_slopes.c index 6270821b1..0ba37a816 100644 --- a/src/p_slopes.c +++ b/src/p_slopes.c @@ -364,11 +364,11 @@ void P_SpawnSlope_Line(int linenum) // In P_SpawnSlopeLine the origin is the centerpoint of the sourcelinedef fslope = line->frontsector->f_slope = - P_MakeSlope(&point, &direction, dz, flags); + P_MakeSlope(&point, &direction, dz, flags); - // Set up some shit - fslope->extent = extent; - fslope->refpos = 1; + // Set up some shit + fslope->extent = extent; + fslope->refpos = 1; // Now remember that f_slope IS a vector // fslope->o = origin 3D point 1 of the vector @@ -425,11 +425,11 @@ void P_SpawnSlope_Line(int linenum) dz = FixedDiv(origin.z - point.z, extent); cslope = line->frontsector->c_slope = - P_MakeSlope(&point, &direction, dz, flags); + P_MakeSlope(&point, &direction, dz, flags); - // Set up some shit - cslope->extent = extent; - cslope->refpos = 2; + // Set up some shit + cslope->extent = extent; + cslope->refpos = 2; // Sync the linedata of the line that started this slope // TODO: Anything special for control sector based slopes later? @@ -494,11 +494,11 @@ void P_SpawnSlope_Line(int linenum) dz = FixedDiv(origin.z - point.z, extent); fslope = line->backsector->f_slope = - P_MakeSlope(&point, &direction, dz, flags); + P_MakeSlope(&point, &direction, dz, flags); - // Set up some shit - fslope->extent = extent; - fslope->refpos = 3; + // Set up some shit + fslope->extent = extent; + fslope->refpos = 3; // Sync the linedata of the line that started this slope // TODO: Anything special for control sector based slopes later? @@ -531,6 +531,7 @@ void P_SpawnSlope_Line(int linenum) P_CalculateSlopeNormal(fslope); } + if (backceil) { fixed_t highest, lowest; @@ -540,11 +541,11 @@ void P_SpawnSlope_Line(int linenum) dz = FixedDiv(origin.z - point.z, extent); cslope = line->backsector->c_slope = - P_MakeSlope(&point, &direction, dz, flags); + P_MakeSlope(&point, &direction, dz, flags); - // Set up some shit - cslope->extent = extent; - cslope->refpos = 4; + // Set up some shit + cslope->extent = extent; + cslope->refpos = 4; // Sync the linedata of the line that started this slope // TODO: Anything special for control sector based slopes later? @@ -604,7 +605,8 @@ static pslope_t *P_NewVertexSlope(INT16 tag1, INT16 tag2, INT16 tag3, UINT8 flag memset(ret->vertices, 0, 3*sizeof(mapthing_t)); // And... look for the vertices in question. - for (i = 0; i < nummapthings; i++, mt++) { + for (i = 0; i < nummapthings; i++, mt++) + { if (mt->type != 750) // Haha, I'm hijacking the old Chaos Spawn thingtype for something! continue; @@ -617,7 +619,8 @@ static pslope_t *P_NewVertexSlope(INT16 tag1, INT16 tag2, INT16 tag3, UINT8 flag } // Now set heights for each vertex, because they haven't been set yet - for (i = 0; i < 3; i++) { + for (i = 0; i < 3; i++) + { mt = ret->vertices[i]; if (!mt) // If a vertex wasn't found, it's game over. There's nothing you can do to recover (except maybe try and kill the slope instead - TODO?) I_Error("P_NewVertexSlope: Slope vertex %s (for linedef tag %d) not found!", sizeu1(i), tag1); @@ -649,23 +652,23 @@ static pslope_t *P_NewVertexSlope(INT16 tag1, INT16 tag2, INT16 tag3, UINT8 flag // void P_CopySectorSlope(line_t *line) { - sector_t *fsec = line->frontsector; - int i, special = line->special; + sector_t *fsec = line->frontsector; + int i, special = line->special; - // Check for copy linedefs - for(i = -1; (i = P_FindSectorFromLineTag(line, i)) >= 0;) - { - sector_t *srcsec = sectors + i; + // Check for copy linedefs + for(i = -1; (i = P_FindSectorFromLineTag(line, i)) >= 0;) + { + sector_t *srcsec = sectors + i; - if((special - 719) & 1 && !fsec->f_slope && srcsec->f_slope) - fsec->f_slope = srcsec->f_slope; //P_CopySlope(srcsec->f_slope); - if((special - 719) & 2 && !fsec->c_slope && srcsec->c_slope) - fsec->c_slope = srcsec->c_slope; //P_CopySlope(srcsec->c_slope); - } + if((special - 719) & 1 && !fsec->f_slope && srcsec->f_slope) + fsec->f_slope = srcsec->f_slope; //P_CopySlope(srcsec->f_slope); + if((special - 719) & 2 && !fsec->c_slope && srcsec->c_slope) + fsec->c_slope = srcsec->c_slope; //P_CopySlope(srcsec->c_slope); + } - fsec->hasslope = true; + fsec->hasslope = true; - line->special = 0; // Linedef was use to set slopes, it finished its job, so now make it a normal linedef + line->special = 0; // Linedef was use to set slopes, it finished its job, so now make it a normal linedef } // @@ -790,49 +793,6 @@ void P_ResetDynamicSlopes(void) // Various utilities related to slopes // -// -// P_GetZAt -// -// Returns the height of the sloped plane at (x, y) as a fixed_t -// -fixed_t P_GetZAt(pslope_t *slope, fixed_t x, fixed_t y) -{ - fixed_t dist = FixedMul(x - slope->o.x, slope->d.x) + - FixedMul(y - slope->o.y, slope->d.y); - - return slope->o.z + FixedMul(dist, slope->zdelta); -} - -// Returns the height of the sector floor at (x, y) -fixed_t P_GetSectorFloorZAt(const sector_t *sector, fixed_t x, fixed_t y) -{ - return sector->f_slope ? P_GetZAt(sector->f_slope, x, y) : sector->floorheight; -} - -// Returns the height of the sector ceiling at (x, y) -fixed_t P_GetSectorCeilingZAt(const sector_t *sector, fixed_t x, fixed_t y) -{ - return sector->c_slope ? P_GetZAt(sector->c_slope, x, y) : sector->ceilingheight; -} - -// Returns the height of the FOF top at (x, y) -fixed_t P_GetFFloorTopZAt(const ffloor_t *ffloor, fixed_t x, fixed_t y) -{ - return *ffloor->t_slope ? P_GetZAt(*ffloor->t_slope, x, y) : *ffloor->topheight; -} - -// Returns the height of the FOF bottom at (x, y) -fixed_t P_GetFFloorBottomZAt(const ffloor_t *ffloor, fixed_t x, fixed_t y) -{ - return *ffloor->b_slope ? P_GetZAt(*ffloor->b_slope, x, y) : *ffloor->bottomheight; -} - -// Returns the height of the light list at (x, y) -fixed_t P_GetLightZAt(const lightlist_t *light, fixed_t x, fixed_t y) -{ - return light->slope ? P_GetZAt(light->slope, x, y) : light->height; -} - // // P_QuantizeMomentumToSlope // diff --git a/src/p_slopes.h b/src/p_slopes.h index 57683d6e1..82dd90738 100644 --- a/src/p_slopes.h +++ b/src/p_slopes.h @@ -13,9 +13,12 @@ #ifndef P_SLOPES_H__ #define P_SLOPES_H__ +#include "doomtype.h" + void P_CalculateSlopeNormal(pslope_t *slope); void P_ResetDynamicSlopes(void); void P_RunDynamicSlopes(void); + // P_SpawnSlope_Line // Creates one or more slopes based on the given line type and front/back // sectors. @@ -30,19 +33,45 @@ void P_CopySectorSlope(line_t *line); pslope_t *P_SlopeById(UINT16 id); +// +// P_GetZAt +// + // Returns the height of the sloped plane at (x, y) as a fixed_t -fixed_t P_GetZAt(pslope_t *slope, fixed_t x, fixed_t y); +FUNCINLINE static ATTRINLINE fixed_t P_GetZAt(pslope_t *z_slope, fixed_t x, fixed_t y) +{ + return z_slope->o.z + FixedMul((FixedMul(x - z_slope->o.x, z_slope->d.x) + FixedMul(y - z_slope->o.y, z_slope->d.y)), z_slope->zdelta); +} -// Returns the height of the sector at (x, y) -fixed_t P_GetSectorFloorZAt (const sector_t *sector, fixed_t x, fixed_t y); -fixed_t P_GetSectorCeilingZAt(const sector_t *sector, fixed_t x, fixed_t y); +// Returns the height of the sector floor at (x, y) +FUNCINLINE static ATTRINLINE fixed_t P_GetSectorFloorZAt(const sector_t *z_sector, fixed_t x, fixed_t y) +{ + return z_sector->f_slope ? P_GetZAt(z_sector->f_slope, x, y) : z_sector->floorheight; +} -// Returns the height of the FOF at (x, y) -fixed_t P_GetFFloorTopZAt (const ffloor_t *ffloor, fixed_t x, fixed_t y); -fixed_t P_GetFFloorBottomZAt(const ffloor_t *ffloor, fixed_t x, fixed_t y); +// Returns the height of the sector ceiling at (x, y) +FUNCINLINE static ATTRINLINE fixed_t P_GetSectorCeilingZAt(const sector_t *z_sector, fixed_t x, fixed_t y) +{ + return z_sector->c_slope ? P_GetZAt(z_sector->c_slope, x, y) : z_sector->ceilingheight; +} + +// Returns the height of the FOF top at (x, y) +FUNCINLINE static ATTRINLINE fixed_t P_GetFFloorTopZAt(const ffloor_t *z_ffloor, fixed_t x, fixed_t y) +{ + return *z_ffloor->t_slope ? P_GetZAt(*z_ffloor->t_slope, x, y) : *z_ffloor->topheight; +} + +// Returns the height of the FOF bottom at (x, y) +FUNCINLINE static ATTRINLINE fixed_t P_GetFFloorBottomZAt(const ffloor_t *z_ffloor, fixed_t x, fixed_t y) +{ + return *z_ffloor->b_slope ? P_GetZAt(*z_ffloor->b_slope, x, y) : *z_ffloor->bottomheight; +} // Returns the height of the light list at (x, y) -fixed_t P_GetLightZAt(const lightlist_t *light, fixed_t x, fixed_t y); +FUNCINLINE static ATTRINLINE fixed_t P_GetLightZAt(const lightlist_t *z_light, fixed_t x, fixed_t y) +{ + return z_light->slope ? P_GetZAt(z_light->slope, x, y) : z_light->height; +} // Lots of physics-based bullshit void P_QuantizeMomentumToSlope(vector3_t *momentum, pslope_t *slope); diff --git a/src/p_spec.c b/src/p_spec.c index 997cc437c..8ccfed3c3 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -35,7 +35,7 @@ #include "hu_stuff.h" #include "m_misc.h" #include "m_cond.h" //unlock triggers -#include "lua_hook.h" // LUAh_LinedefExecute +#include "lua_hook.h" // LUA_HookLinedefExecute #include "k_kart.h" // SRB2kart #include "console.h" // CON_LogMessage @@ -1431,12 +1431,14 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller } else if (caller) { - if (GETSECSPECIAL(caller->special, 2) == 6) + INT32 special = GETSECSPECIAL(caller->special, 2); + + if (special == 6) { if (!(ALL7EMERALDS(emeralds))) return false; } - else if (GETSECSPECIAL(caller->special, 2) == 7) // SRB2Kart: reusing for Race Lap executor + else if (special == 7) // SRB2Kart: reusing for Race Lap executor { UINT8 lap; @@ -1470,7 +1472,7 @@ boolean P_RunTriggerLinedef(line_t *triggerline, mobj_t *actor, sector_t *caller // If we were not triggered by a sector type especially for the purpose, // a Linedef Executor linedef trigger is not handling sector triggers properly, return. - else if ((!GETSECSPECIAL(caller->special, 2) || GETSECSPECIAL(caller->special, 2) > 7) && (specialtype > 322)) + else if ((!special || special > 7) && (specialtype > 322)) { CONS_Alert(CONS_WARNING, M_GetText("Linedef executor trigger isn't handling sector triggers properly!\nspecialtype = %d, if you are not a dev, report this warning instance\nalong with the wad that caused it!\n"), @@ -1805,27 +1807,23 @@ void P_SwitchWeather(INT32 weathernum) precipmobj = (precipmobj_t *)think; + mobjtype_t type = 0; + INT32 z = 0; + + if (swap == PRECIP_BLANK || swap == PRECIP_STORM_NORAIN) // Remove precip, but keep it around for reuse. + { + precipmobj->precipflags |= PCF_INVISIBLE; + continue; + } + if (swap == PRECIP_RAIN) // Snow To Rain { - precipmobj->type = MT_RAIN; // proper set the type - precipmobj->info = &mobjinfo[MT_RAIN]; - precipmobj->flags = mobjinfo[MT_RAIN].flags; - st = &states[mobjinfo[MT_RAIN].spawnstate]; - precipmobj->state = st; - precipmobj->tics = st->tics; - precipmobj->sprite = st->sprite; - precipmobj->frame = st->frame; - precipmobj->momz = cv_mobjscaleprecip.value ? FixedMul(mobjinfo[MT_RAIN].speed, mapobjectscale) : mobjinfo[MT_RAIN].speed; - - precipmobj->precipflags &= ~(PCF_INVISIBLE|PCF_SPLASH); // P_PrecipThinker will add this again if it needs to + type = MT_RAIN; } else if (swap == PRECIP_SNOW) // Rain To Snow { - INT32 z; + type = MT_SNOWFLAKE; - precipmobj->type = MT_SNOWFLAKE; // proper set the type - precipmobj->info = &mobjinfo[MT_SNOWFLAKE]; - precipmobj->flags = mobjinfo[MT_SNOWFLAKE].flags; z = M_RandomByte(); if (z < 64) @@ -1834,92 +1832,69 @@ void P_SwitchWeather(INT32 weathernum) z = 1; else z = 0; - - st = &states[mobjinfo[MT_SNOWFLAKE].spawnstate+z]; - precipmobj->state = st; - precipmobj->tics = st->tics; - precipmobj->sprite = st->sprite; - precipmobj->frame = st->frame; - precipmobj->momz = cv_mobjscaleprecip.value ? FixedMul(mobjinfo[MT_SNOWFLAKE].speed, mapobjectscale) : mobjinfo[MT_SNOWFLAKE].speed; - - precipmobj->precipflags &= ~(PCF_INVISIBLE|PCF_SPLASH); // P_PrecipThinker will add this again if it needs to - } - else if (swap == PRECIP_BLANK || swap == PRECIP_STORM_NORAIN) // Remove precip, but keep it around for reuse. - { - precipmobj->precipflags |= PCF_INVISIBLE; } + + precipmobj->type = type; // proper set the type + precipmobj->info = &mobjinfo[type]; + precipmobj->flags = mobjinfo[type].flags; + + st = &states[mobjinfo[type].spawnstate+z]; + + precipmobj->state = st; + precipmobj->tics = st->tics; + precipmobj->sprite = st->sprite; + precipmobj->frame = st->frame; + precipmobj->momz = (cv_mobjscaleprecip.value ? FixedMul(mobjinfo[type].speed, mapobjectscale) : mobjinfo[type].speed); + + precipmobj->precipflags &= ~(PCF_INVISIBLE|PCF_SPLASH); // P_PrecipThinker will add this again if it needs to } } + boolean dontspawn = false; + switch (weathernum) { case PRECIP_SNOW: // snow curWeather = PRECIP_SNOW; - - if (!swap) - P_SpawnPrecipitation(); - break; case PRECIP_RAIN: // rain { - boolean dontspawn = false; - if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_STORM_NOSTRIKES) dontspawn = true; curWeather = PRECIP_RAIN; - - if (!dontspawn && !swap) - P_SpawnPrecipitation(); - break; } case PRECIP_STORM: // storm { - boolean dontspawn = false; - if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_STORM_NOSTRIKES) dontspawn = true; curWeather = PRECIP_STORM; - - if (!dontspawn && !swap) - P_SpawnPrecipitation(); - break; } case PRECIP_STORM_NOSTRIKES: // storm w/o lightning { - boolean dontspawn = false; - if (curWeather == PRECIP_RAIN || curWeather == PRECIP_STORM || curWeather == PRECIP_STORM_NOSTRIKES) dontspawn = true; curWeather = PRECIP_STORM_NOSTRIKES; - - if (!dontspawn && !swap) - P_SpawnPrecipitation(); - break; } case PRECIP_STORM_NORAIN: // storm w/o rain curWeather = PRECIP_STORM_NORAIN; - - if (!swap) - P_SpawnPrecipitation(); - break; case PRECIP_BLANK: curWeather = PRECIP_BLANK; - - if (!swap) - P_SpawnPrecipitation(); - break; default: + dontspawn = true; curWeather = PRECIP_NONE; break; } + + if (!dontspawn && !swap) + P_SpawnPrecipitation(); } /** Gets an object. @@ -2084,6 +2059,9 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) mo->y += y; mo->z += z; P_SetThingPosition(mo); + mo->old_x = mo->x; + mo->old_y = mo->y; + mo->old_z = mo->z; if (mo->player) { @@ -2102,7 +2080,6 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) camera[i].reset = true; camera[i].subsector = R_PointInSubsector(camera[i].x, camera[i].y); R_RelativeTeleportViewInterpolation(i, x, y, z, 0); - R_ResetViewInterpolation(i + 1); // reset view interp as well break; } } @@ -2520,7 +2497,6 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) if (displayplayers[i] == (mo->player - players)) { R_ResetViewInterpolation(i + 1); - R_ResetViewInterpolation(i + 1); } } } @@ -2855,7 +2831,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) case 443: // Calls a named Lua function if (line->text) - LUAh_LinedefExecute(line, mo, callsec); + LUA_HookLinedefExecute(line, mo, callsec); else CONS_Alert(CONS_WARNING, "Linedef %s is missing the hook name of the Lua function to call! (This should be given in the front texture fields)\n", sizeu1(line-lines)); break; diff --git a/src/p_tick.c b/src/p_tick.c index 7405792d0..3b0cadde8 100644 --- a/src/p_tick.c +++ b/src/p_tick.c @@ -196,6 +196,8 @@ void P_AddThinker(thinker_t *thinker) thinkercap.prev = thinker; thinker->references = 0; // killough 11/98: init reference counter to 0 + + thinker->cachable = (thinker->function.acp1 == (actionf_p1)P_MobjThinker); } // @@ -235,7 +237,17 @@ void P_RemoveThinkerDelayed(thinker_t *thinker) * thinker->prev->next = thinker->next */ (next->prev = currentthinker = thinker->prev)->next = next; R_DestroyLevelInterpolators(thinker); - Z_Free(thinker); + + if (thinker->cachable == true) + { + // put cachable thinkers in the mobj cache, so we can avoid allocations + ((mobj_t *)thinker)->hnext = mobjcache; + mobjcache = (mobj_t *)thinker; + } + else + { + Z_Free(thinker); + } } // @@ -250,9 +262,20 @@ void P_UnlinkThinker(thinker_t *thinker) I_Assert(thinker->references == 0); (next->prev = thinker->prev)->next = next; - Z_Free(thinker); + + if (thinker->cachable == true) + { + // put cachable thinkers in the mobj cache, so we can avoid allocations + ((mobj_t *)thinker)->hnext = mobjcache; + mobjcache = (mobj_t *)thinker; + } + else + { + Z_Free(thinker); + } } + // // P_RemoveThinker // @@ -327,7 +350,7 @@ static inline void P_RunThinkers(void) } } -static inline void P_DeviceRumbleTick(void) +static void P_DeviceRumbleTick(void) { UINT8 i; @@ -345,7 +368,7 @@ static inline void P_DeviceRumbleTick(void) if (!P_IsLocalPlayer(player)) continue; - if (G_GetDeviceForPlayer(i) == 0) + if (cv_usejoystick[i].value == 0) continue; if (!playeringame[displayplayers[i]] || player->spectator) @@ -397,7 +420,7 @@ void P_RunChaseCameras(void) } } -static inline void P_RunQuakes(void) +static void P_RunQuakes(void) { fixed_t ir; @@ -434,10 +457,21 @@ void P_Ticker(boolean run) { INT32 i; - //Increment jointime even if paused. + // Increment jointime even if paused for (i = 0; i < MAXPLAYERS; i++) + { if (playeringame[i]) - ++players[i].jointime; + { + players[i].jointime++; + } + } + + if (run) + { + // Update old view state BEFORE ticking so resetting + // the old interpolation state from game logic works. + R_UpdateViewInterpolation(); + } if (objectplacing) { @@ -469,9 +503,6 @@ void P_Ticker(boolean run) return; } - for (i = 0; i <= splitscreen; i++) - postimgtype[i] = postimg_none; - P_MapStart(); if (run) @@ -520,7 +551,7 @@ void P_Ticker(boolean run) ps_checkposition_calls.value.i = 0; PS_START_TIMING(ps_lua_prethinkframe_time); - LUAh_PreThinkFrame(); + LUA_HookPreThinkFrame(); PS_STOP_TIMING(ps_lua_prethinkframe_time); PS_START_TIMING(ps_playerthink_time); @@ -556,7 +587,7 @@ void P_Ticker(boolean run) } PS_START_TIMING(ps_lua_thinkframe_time); - LUAh_ThinkFrame(); + LUA_HookThinkFrame(); PS_STOP_TIMING(ps_lua_thinkframe_time); } @@ -632,14 +663,17 @@ void P_Ticker(boolean run) G_WriteAllGhostTics(); - if (cv_recordmultiplayerdemos.value && (demo.savemode == DSM_NOTSAVING || demo.savemode == DSM_WILLAUTOSAVE)) - if (demo.savebutton && demo.savebutton + 3*TICRATE < leveltime && (InputDown(gc_lookback, 1) || (cv_usejoystick.value && axis > 0))) - demo.savemode = DSM_TITLEENTRY; + if (cv_recordmultiplayerdemos.value) + { + if (demo.savemode == DSM_NOTSAVING || demo.savemode == DSM_WILLAUTOSAVE) + if (demo.savebutton && demo.savebutton + 3*TICRATE < leveltime && (InputDown(gc_lookback, 1) || (cv_usejoystick[0].value && axis > 0))) + demo.savemode = DSM_TITLEENTRY; - //if there are no players left at all, stop demo recording - //Demos that that dont have any players crash during playback, which can happen with dedicated servers - if (cv_recordmultiplayerdemos.value && demo.savemode == DSM_WILLAUTOSAVE && !D_NumPlayers()) - G_SaveDemo(); + // if there are no players left at all, stop demo recording + // Demos that that dont have any players crash during playback, which can happen with dedicated servers + if (demo.savemode == DSM_WILLAUTOSAVE && !D_NumPlayers()) + G_ResetDemoRecording(); + } } else if (demo.playback) // Use Ghost data for consistency checks. { @@ -660,7 +694,7 @@ void P_Ticker(boolean run) D_MapChange(gamemap, gametype, encoremode, true, 0, false, false); PS_START_TIMING(ps_lua_postthinkframe_time); - LUAh_PostThinkFrame(); + LUA_HookPostThinkFrame(); PS_STOP_TIMING(ps_lua_postthinkframe_time); } @@ -672,7 +706,6 @@ void P_Ticker(boolean run) if (run) { R_UpdateLevelInterpolators(); - R_UpdateViewInterpolation(); // Hack: ensure newview is assigned every tic. // Ensures view interpolation is T-1 to T in poor network conditions @@ -682,16 +715,18 @@ void P_Ticker(boolean run) for (i = 0; i <= splitscreen; i++) { player_t *player = &players[displayplayers[i]]; - boolean isSkyVisibleForPlayer = skyVisiblePerPlayer[i]; if (!player->mo) continue; - if (isSkyVisibleForPlayer && skyboxmo[0] && cv_skybox.value) + const boolean skybox = (skyboxmo[0] && cv_skybox.value); + + if (skyVisiblePerPlayer[i] && skybox) { - R_SkyboxFrame(player); + R_SkyboxFrame(i); } - R_SetupFrame(player, (skyboxmo[0] && cv_skybox.value)); + + R_SetupFrame(i, skybox); } } } @@ -708,9 +743,6 @@ void P_PreTicker(INT32 frames) INT32 i; ticcmd_t temptic; - for (i = 0; i <= splitscreen; i++) - postimgtype[i] = postimg_none; - hook_defrosting = frames; while (hook_defrosting) @@ -719,7 +751,7 @@ void P_PreTicker(INT32 frames) R_UpdateMobjInterpolators(); - LUAh_PreThinkFrame(); + LUA_HOOK(PreThinkFrame); for (i = 0; i < MAXPLAYERS; i++) if (playeringame[i] && players[i].mo && !P_MobjWasRemoved(players[i].mo)) @@ -748,7 +780,7 @@ void P_PreTicker(INT32 frames) if (playeringame[i] && players[i].mo && !P_MobjWasRemoved(players[i].mo)) P_PlayerAfterThink(&players[i]); - LUAh_ThinkFrame(); + LUA_HookThinkFrame(); P_RunOverlays(); P_RunShadows(); @@ -756,7 +788,7 @@ void P_PreTicker(INT32 frames) P_UpdateSpecials(); P_RespawnSpecials(); - LUAh_PostThinkFrame(); + LUA_HOOK(PostThinkFrame); R_UpdateLevelInterpolators(); R_UpdateViewInterpolation(); diff --git a/src/p_user.c b/src/p_user.c index 7c57fb107..3133ee49b 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -427,8 +427,6 @@ void P_ResetPlayer(player_t *player) player->powers[pw_tailsfly] = 0; player->onconveyor = 0; player->skidtime = 0; - /*if (player-players == consoleplayer && botingame) - CV_SetValue(&cv_analog2, true);*/ } // @@ -508,8 +506,6 @@ void P_DoSuperTransformation(player_t *player, boolean giverings) // Adds to the player's score void P_AddPlayerScore(player_t *player, UINT32 amount) { - //UINT32 oldscore; - if (!(G_BattleGametype())) return; @@ -519,8 +515,6 @@ void P_AddPlayerScore(player_t *player, UINT32 amount) if (player->exiting) // srb2kart return; - //oldscore = player->score; - // Don't go above MAXSCORE. if (player->marescore + amount < MAXSCORE) player->marescore += amount; @@ -743,7 +737,7 @@ void P_RestoreMusic(player_t *player) return; if (leveltime < MUSICSTARTTIME) - S_StartMapMusic(true); + S_StartMapMusic(); else // see also where time overs are handled - search for "lives = 2" in this file { INT32 wantedmus = 0; // 0 is level music, 1 is invincibility, 2 is grow @@ -2341,8 +2335,6 @@ static void P_MovePlayer(player_t *player) if (maptol & TOL_2D) runspd = FixedMul(runspd, 2*FRACUNIT/3); - //P_SkidStuff(player); - ///////////////////////// // MOVEMENT ANIMATIONS // ///////////////////////// @@ -2498,7 +2490,7 @@ static void P_MovePlayer(player_t *player) } #ifdef HWRENDER - if (rendermode != render_soft && rendermode != render_none && cv_grfovchange.value) + if (rendermode == render_opengl && cv_glfovchange.value) { fixed_t speed; const fixed_t runnyspeed = 20*FRACUNIT; @@ -2976,34 +2968,34 @@ camera_t camera[MAXSPLITSCREENPLAYERS]; // Four cameras, three for splitscreen static void CV_CamRotate_OnChange(void) { - if (cv_cam_rotate.value < 0) - CV_SetValue(&cv_cam_rotate, cv_cam_rotate.value + 360); - else if (cv_cam_rotate.value > 359) - CV_SetValue(&cv_cam_rotate, cv_cam_rotate.value % 360); + if (cv_cam_rotate[0].value < 0) + CV_SetValue(&cv_cam_rotate[0], cv_cam_rotate[0].value + 360); + else if (cv_cam_rotate[0].value > 359) + CV_SetValue(&cv_cam_rotate[0], cv_cam_rotate[0].value % 360); } static void CV_CamRotate2_OnChange(void) { - if (cv_cam2_rotate.value < 0) - CV_SetValue(&cv_cam2_rotate, cv_cam2_rotate.value + 360); - else if (cv_cam2_rotate.value > 359) - CV_SetValue(&cv_cam2_rotate, cv_cam2_rotate.value % 360); + if (cv_cam_rotate[1].value < 0) + CV_SetValue(&cv_cam_rotate[1], cv_cam_rotate[1].value + 360); + else if (cv_cam_rotate[1].value > 359) + CV_SetValue(&cv_cam_rotate[1], cv_cam_rotate[1].value % 360); } static void CV_CamRotate3_OnChange(void) { - if (cv_cam3_rotate.value < 0) - CV_SetValue(&cv_cam3_rotate, cv_cam3_rotate.value + 360); - else if (cv_cam3_rotate.value > 359) - CV_SetValue(&cv_cam3_rotate, cv_cam3_rotate.value % 360); + if (cv_cam_rotate[2].value < 0) + CV_SetValue(&cv_cam_rotate[2], cv_cam_rotate[2].value + 360); + else if (cv_cam_rotate[2].value > 359) + CV_SetValue(&cv_cam_rotate[2], cv_cam_rotate[2].value % 360); } static void CV_CamRotate4_OnChange(void) { - if (cv_cam4_rotate.value < 0) - CV_SetValue(&cv_cam4_rotate, cv_cam4_rotate.value + 360); - else if (cv_cam4_rotate.value > 359) - CV_SetValue(&cv_cam4_rotate, cv_cam4_rotate.value % 360); + if (cv_cam_rotate[3].value < 0) + CV_SetValue(&cv_cam_rotate[3], cv_cam_rotate[3].value + 360); + else if (cv_cam_rotate[3].value > 359) + CV_SetValue(&cv_cam_rotate[3], cv_cam_rotate[3].value % 360); } static CV_PossibleValue_t CV_CamSpeed[] = {{0, "MIN"}, {1*FRACUNIT, "MAX"}, {0, NULL}}; @@ -3074,33 +3066,47 @@ static void CV_PlayerCam4_OnChange(void) P_ResetCamera(&players[displayplayers[3]], &camera[3]); } -consvar_t cv_cam_dist = {"cam_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam1_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam_height = {"cam_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam1_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam_still = {"cam_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam_speed = {"cam_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam_rotate = {"cam_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam_rotspeed = {"cam_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_cam_dist[MAXSPLITSCREENPLAYERS] = { + {"cam_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam1_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam2_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam2_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam3_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam3_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam4_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam4_OnChange, 0, NULL, NULL, 0, 0, NULL} +}; -consvar_t cv_cam2_dist = {"cam2_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam2_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam2_height = {"cam2_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam2_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam2_still = {"cam2_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam2_speed = {"cam2_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam2_rotate = {"cam2_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate2_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam2_rotspeed = {"cam2_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_cam_height[MAXSPLITSCREENPLAYERS] = { + {"cam_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam1_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam2_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam2_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam3_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam3_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam4_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam4_OnChange, 0, NULL, NULL, 0, 0, NULL}, +}; -consvar_t cv_cam3_dist = {"cam3_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam3_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam3_height = {"cam3_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam3_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam3_still = {"cam3_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam3_speed = {"cam3_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam3_rotate = {"cam3_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate3_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam3_rotspeed = {"cam3_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_cam_still[MAXSPLITSCREENPLAYERS] = { + {"cam_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam2_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam3_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam4_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL} +}; -consvar_t cv_cam4_dist = {"cam4_dist", "160", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam4_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam4_height = {"cam4_height", "50", CV_FLOAT|CV_SAVE|CV_CALL|CV_NOINIT, NULL, CV_PlayerCam4_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam4_still = {"cam4_still", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam4_speed = {"cam4_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam4_rotate = {"cam4_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate4_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cam4_rotspeed = {"cam4_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_cam_speed[MAXSPLITSCREENPLAYERS] = { + {"cam_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam2_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam3_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam4_speed", "0.4", CV_FLOAT|CV_SAVE, CV_CamSpeed, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_cam_rotate[MAXSPLITSCREENPLAYERS] = { + {"cam_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam2_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate2_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam3_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate3_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"cam4_rotate", "0", CV_CALL|CV_NOINIT, CV_CamRotate, CV_CamRotate4_OnChange, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_cam_rotspeed[MAXSPLITSCREENPLAYERS] = { + {"cam_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam2_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam3_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"cam4_rotspeed", "10", CV_SAVE, rotation_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; consvar_t cv_tilting = {"tilting", "Off", CV_SAVE|CV_CALL, CV_OnOff, Bird_menu_Onchange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_quaketilt = {"quaketilt", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -3111,18 +3117,7 @@ consvar_t cv_actionmovie = {"actionmovie", "Off", CV_SAVE, CV_OnOff, NULL, 0, NU static CV_PossibleValue_t lookbackmom_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Double"}, {0, NULL}}; consvar_t cv_lookbackmom = {"cameralookbackmom", "Off", CV_SAVE, lookbackmom_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -fixed_t t_cam_dist = -42; -fixed_t t_cam_height = -42; -fixed_t t_cam_rotate = -42; -fixed_t t_cam2_dist = -42; -fixed_t t_cam2_height = -42; -fixed_t t_cam2_rotate = -42; -fixed_t t_cam3_dist = -42; -fixed_t t_cam3_height = -42; -fixed_t t_cam3_rotate = -42; -fixed_t t_cam4_dist = -42; -fixed_t t_cam4_height = -42; -fixed_t t_cam4_rotate = -42; +fixed_t t_cam_rotate[MAXSPLITSCREENPLAYERS] = {-42, -42, -42, -42}; #define MAXCAMERADIST 140*FRACUNIT // Max distance the camera can be in front of the player (2D mode) @@ -3174,7 +3169,7 @@ static ticcmd_t *P_CameraCmd(camera_t *cam) mouseaiming = true; invertmouse = cv_invertmouse.value; - lookaxis = cv_lookaxis.value; + lookaxis = cv_lookaxis[0].value; usejoystick = true; turnright = InputDown(gc_turnright, 1); @@ -3357,7 +3352,7 @@ void P_DemoCameraMovement(camera_t *cam) democam.soundmobj = awayviewmobj_hack; // update subsector to avoid crashes; - cam->subsector = R_PointInSubsector(cam->x, cam->y); + cam->subsector = R_PointInSubsectorFast(cam->x, cam->y); } void P_ResetCamera(player_t *player, camera_t *thiscam) @@ -3388,17 +3383,18 @@ void P_ResetCamera(player_t *player, camera_t *thiscam) thiscam->z = z; thiscam->reset = true; - if (!(thiscam == &camera[0] && (cv_cam_still.value || cv_analog.value)) - && !(thiscam == &camera[1] && (cv_cam2_still.value || cv_analog2.value)) - && !(thiscam == &camera[2] && (cv_cam3_still.value || cv_analog3.value)) - && !(thiscam == &camera[3] && (cv_cam4_still.value || cv_analog4.value))) + if (!(thiscam == &camera[0] && (cv_cam_still[0].value)) + && !(thiscam == &camera[1] && (cv_cam_still[1].value)) + && !(thiscam == &camera[2] && (cv_cam_still[2].value)) + && !(thiscam == &camera[3] && (cv_cam_still[3].value))) { thiscam->angle = player->mo->angle; thiscam->aiming = 0; } + thiscam->relativex = 0; - thiscam->subsector = R_PointInSubsector(thiscam->x,thiscam->y); + thiscam->subsector = R_PointInSubsectorFast(thiscam->x,thiscam->y); thiscam->radius = 20*FRACUNIT; thiscam->height = 16*FRACUNIT; @@ -3410,7 +3406,7 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall { static boolean lookbackactive[MAXSPLITSCREENPLAYERS]; static UINT8 lookbackdelay[MAXSPLITSCREENPLAYERS]; - UINT8 num; + UINT8 num, plyrnum; angle_t angle = 0, focusangle = 0, focusaiming = 0; fixed_t x, y, z, dist, viewpointx, viewpointy, camspeed, camdist, camheight, pviewheight; fixed_t pan, xpan, ypan; @@ -3440,6 +3436,44 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall return true; } + if (thiscam == &camera[1]) // Camera 2 + { + num = 1; + } + else if (thiscam == &camera[2]) // Camera 3 + { + num = 2; + } + else if (thiscam == &camera[3]) // Camera 4 + { + num = 3; + } + else // Camera 1 + { + num = 0; + } + + if (player == &players[consoleplayer]) + { + plyrnum = 0; + } + else if (player == &players[displayplayers[1]]) + { + plyrnum = 1; + } + else if (player == &players[displayplayers[2]]) + { + plyrnum = 2; + } + else if (player == &players[displayplayers[3]]) + { + plyrnum = 3; + } + else + { + plyrnum = 255; + } + mo = player->mo; #ifndef NOCLIPCAM @@ -3458,40 +3492,23 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall if (player->spectator) // force cam off for spectators return true; - if (!cv_chasecam.value && thiscam == &camera[0]) - return true; - - if (!cv_chasecam2.value && thiscam == &camera[1]) - return true; - - if (!cv_chasecam3.value && thiscam == &camera[2]) - return true; - - if (!cv_chasecam4.value && thiscam == &camera[3]) + if (!cv_chasecam[num].value && thiscam == &camera[num]) return true; } if (!thiscam->chase && !resetcalled) { - if (player == &players[consoleplayer]) - focusangle = localangle[0]; - else if (player == &players[displayplayers[1]]) - focusangle = localangle[1]; - else if (player == &players[displayplayers[2]]) - focusangle = localangle[2]; - else if (player == &players[displayplayers[3]]) - focusangle = localangle[3]; + if (plyrnum != 255) + { + focusangle = localangle[plyrnum]; + } else + { focusangle = mo->angle; + } - if (thiscam == &camera[0]) - camrotate = cv_cam_rotate.value; - else if (thiscam == &camera[1]) - camrotate = cv_cam2_rotate.value; - else if (thiscam == &camera[2]) - camrotate = cv_cam3_rotate.value; - else if (thiscam == &camera[3]) - camrotate = cv_cam4_rotate.value; + if (thiscam == &camera[num]) + camrotate = cv_cam_rotate[num].value; else camrotate = 0; @@ -3509,35 +3526,15 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall thiscam->radius = 20*mapobjectscale; thiscam->height = 16*mapobjectscale; - // Don't run while respawning from a starpost - // Inu 4/8/13 Why not?! -// if (leveltime > 0 && timeinmap <= 0) -// return true; - if (demo.playback) { focusangle = mo->angle; focusaiming = 0; } - else if (player == &players[consoleplayer]) + else if (plyrnum != 255) { - focusangle = localangle[0]; - focusaiming = localaiming[0]; - } - else if (player == &players[displayplayers[1]]) - { - focusangle = localangle[1]; - focusaiming = localaiming[1]; - } - else if (player == &players[displayplayers[2]]) - { - focusangle = localangle[2]; - focusaiming = localaiming[2]; - } - else if (player == &players[displayplayers[3]]) - { - focusangle = localangle[3]; - focusaiming = localaiming[3]; + focusangle = localangle[plyrnum]; + focusaiming = localaiming[plyrnum]; } else { @@ -3548,46 +3545,12 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall if (P_CameraThinker(player, thiscam, resetcalled)) return true; - if (thiscam == &camera[1]) // Camera 2 - { - num = 1; - camspeed = cv_cam2_speed.value; - camstill = cv_cam2_still.value; - camrotate = cv_cam2_rotate.value; - camdist = FixedMul(cv_cam2_dist.value, mapobjectscale); - camheight = FixedMul(cv_cam2_height.value, mapobjectscale); - lookback = camspin[1]; - } - else if (thiscam == &camera[2]) // Camera 3 - { - num = 2; - camspeed = cv_cam3_speed.value; - camstill = cv_cam3_still.value; - camrotate = cv_cam3_rotate.value; - camdist = FixedMul(cv_cam3_dist.value, mapobjectscale); - camheight = FixedMul(cv_cam3_height.value, mapobjectscale); - lookback = camspin[2]; - } - else if (thiscam == &camera[3]) // Camera 4 - { - num = 3; - camspeed = cv_cam4_speed.value; - camstill = cv_cam4_still.value; - camrotate = cv_cam4_rotate.value; - camdist = FixedMul(cv_cam4_dist.value, mapobjectscale); - camheight = FixedMul(cv_cam4_height.value, mapobjectscale); - lookback = camspin[3]; - } - else // Camera 1 - { - num = 0; - camspeed = cv_cam_speed.value; - camstill = cv_cam_still.value; - camrotate = cv_cam_rotate.value; - camdist = FixedMul(cv_cam_dist.value, mapobjectscale); - camheight = FixedMul(cv_cam_height.value, mapobjectscale); - lookback = camspin[0]; - } + camspeed = cv_cam_speed[num].value; + camstill = cv_cam_still[num].value; + camrotate = cv_cam_rotate[num].value; + camdist = FixedMul(cv_cam_dist[num].value, mapobjectscale); + camheight = FixedMul(cv_cam_height[num].value, mapobjectscale); + lookback = camspin[num]; if (timeover) { @@ -3651,10 +3614,7 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall } if (!resetcalled && (leveltime > starttime && timeover != 2) - && ((thiscam == &camera[0] && t_cam_rotate != -42) - || (thiscam == &camera[1] && t_cam2_rotate != -42) - || (thiscam == &camera[2] && t_cam3_rotate != -42) - || (thiscam == &camera[3] && t_cam4_rotate != -42))) + && (thiscam == &camera[num] && t_cam_rotate[num] != -42)) { angle = FixedAngle(camrotate*FRACUNIT); thiscam->angle = angle; @@ -3995,7 +3955,6 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall { P_MoveChaseCamera(player, thiscam, false); R_ResetViewInterpolation(num + 1); - R_ResetViewInterpolation(num + 1); } return (x == thiscam->x && y == thiscam->y && z == thiscam->z && angle == thiscam->aiming); @@ -4020,7 +3979,6 @@ boolean P_SpectatorJoinGame(player_t *player) { if (P_IsLocalPlayer(player)) CONS_Printf(M_GetText("Server does not allow team change.\n")); - //player->powers[pw_flashing] = TICRATE + 1; //to prevent message spam. } // Team changing in Team Match and CTF // Pressing fire assigns you to a team that needs players if allowed. @@ -4103,11 +4061,12 @@ boolean P_SpectatorJoinGame(player_t *player) return false; } +// the below is first person only, if you're curious. check out P_CalcChasePostImg in p_mobj.c for chasecam static void P_CalcPostImg(player_t *player) { sector_t *sector = player->mo->subsector->sector; - postimg_t *type = NULL; - INT32 *param; + INT16 typeflag = 0; + //INT32 *param; fixed_t pviewheight; UINT8 i; @@ -4122,20 +4081,19 @@ static void P_CalcPostImg(player_t *player) pviewheight = player->awayviewmobj->z + 20*FRACUNIT; } - for (i = 0; i <= splitscreen; i++) + /*for (i = 0; i <= splitscreen; i++) { if (player == &players[displayplayers[i]]) { - type = &postimgtype[i]; param = &postimgparam[i]; break; } - } + }*/ // see if we are in heat (no, not THAT kind of heat...) if (P_FindSpecialLineFromTag(13, sector->tag, -1) != -1) - *type = postimg_heat; + typeflag |= POSTIMG_HEAT; else if (sector->ffloors) { ffloor_t *rover; @@ -4154,7 +4112,7 @@ static void P_CalcPostImg(player_t *player) continue; if (P_FindSpecialLineFromTag(13, rover->master->frontsector->tag, -1) != -1) - *type = postimg_heat; + typeflag |= POSTIMG_HEAT; } } @@ -4176,36 +4134,35 @@ static void P_CalcPostImg(player_t *player) if (pviewheight >= topheight || pviewheight <= bottomheight) continue; - *type = postimg_water; + typeflag |= POSTIMG_WATER; } } - if (!encoremode) // srb2kart - { - if (player->mo->eflags & MFE_VERTICALFLIP) - *type = postimg_flip; - } - else - { - if (player->mo->eflags & MFE_VERTICALFLIP) - *type = postimg_mirrorflip; - else - *type = postimg_mirror; - } + if (encoremode) // srb2kart + typeflag |= POSTIMG_MIRROR; + + if (player->mo->eflags & MFE_VERTICALFLIP) + typeflag |= POSTIMG_FLIP; -#if 1 - (void)param; -#else // Motion blur - if (player->speed > (35<speed > (35<speed - 32)/4; if (*param > 5) *param = 5; + }*/ + + for (i = 0; i <= splitscreen; i++) + { + if (player != &players[displayplayers[i]]) + continue; + + players[displayplayers[i]].postimgflags = typeflag; + break; } -#endif } void P_DoTimeOver(player_t *player) @@ -4215,6 +4172,8 @@ void P_DoTimeOver(player_t *player) player->pflags |= PF_TIMEOVER; + demo.savebutton = leveltime; + if (P_IsLocalPlayer(player) && !demo.playback) legitimateexit = true; // SRB2kart: losing a race is still seeing it through to the end :p @@ -4368,7 +4327,7 @@ void P_PlayerThink(player_t *player) } if (player->playerstate == PST_REBORN) { - LUAh_PlayerThink(player); + LUA_HookPlayer(player, HOOK(PlayerThink)); return; } } @@ -4475,7 +4434,7 @@ void P_PlayerThink(player_t *player) if (player->playerstate == PST_DEAD) { - LUAh_PlayerThink(player); + LUA_HookPlayer(player, HOOK(PlayerThink)); return; } } @@ -4541,7 +4500,7 @@ void P_PlayerThink(player_t *player) else player->mo->flags2 &= ~MF2_SHADOW; P_DeathThink(player); - LUAh_PlayerThink(player); + LUA_HookPlayer(player, HOOK(PlayerThink)); return; } @@ -4713,7 +4672,7 @@ void P_PlayerThink(player_t *player) if (!player->mo) { - LUAh_PlayerThink(player); + LUA_HookPlayer(player, HOOK(PlayerThink)); return; // P_MovePlayer removed player->mo. } @@ -4725,10 +4684,7 @@ void P_PlayerThink(player_t *player) if (player->onconveyor == 1) player->cmomy = player->cmomx = 0; - //P_DoSuperStuff(player); - //P_CheckSneakerAndLivesTimer(player); P_DoBubbleBreath(player); // Spawn Sonic's bubbles - //P_CheckUnderwaterAndSpaceTimer(player); // Display the countdown drown numbers! P_CheckInvincibilityTimer(player); // Spawn Invincibility Sparkles P_DoPlayerHeadSigns(player); // Spawn Tag/CTF signs over player's head @@ -4896,7 +4852,7 @@ void P_PlayerThink(player_t *player) if (rendermode != render_none) DoABarrelRoll(player); - LUAh_PlayerThink(player); + LUA_HookPlayer(player, HOOK(PlayerThink)); } // @@ -4947,7 +4903,6 @@ void P_PlayerAfterThink(player_t *player) if (player->pflags & PF_NIGHTSMODE) { player->powers[pw_gravityboots] = 0; - //player->mo->eflags &= ~MFE_VERTICALFLIP; } if (player->pflags & PF_SLIDING) diff --git a/src/r_bsp.c b/src/r_bsp.c index 586aa3799..db6a4378d 100644 --- a/src/r_bsp.c +++ b/src/r_bsp.c @@ -15,6 +15,8 @@ #include "g_game.h" #include "r_local.h" #include "r_state.h" +#include "r_portal.h" // Add seg portals + #include "r_splats.h" #include "p_local.h" // camera @@ -28,7 +30,6 @@ side_t *sidedef; line_t *linedef; sector_t *frontsector; sector_t *backsector; -portal_pair *g_portal; // is curline a portal seg? // very ugly realloc() of drawsegs at run-time, I upped it to 512 // instead of 256.. and someone managed to send me a level with @@ -486,7 +487,7 @@ static void R_AddLine(seg_t *line) line2 = P_FindSpecialLineFromTag(40, line->linedef->tag, line2); if (line2 >= 0) // found it! { - R_AddPortal(line->linedef-lines, line2, x1, x2); // Remember the lines for later rendering + Portal_Add2Lines(line->linedef-lines, line2, x1, x2); // Remember the lines for later rendering //return; // Don't fill in that space now! goto clipsolid; } @@ -582,10 +583,10 @@ static void R_AddLine(seg_t *line) clippass: g_walloffscreen = false; + R_ClipPassWallSegment(x1, x2 - 1, false); + if (g_walloffscreen) R_ClipPassWallSegment(x1, x2 - 1, true); - else - R_ClipPassWallSegment(x1, x2 - 1, false); return; clipsolid: @@ -626,7 +627,21 @@ static boolean R_CheckBBox(const fixed_t *bspcoord) cliprange_t *start; // Find the corners of the box that define the edges from current viewpoint. - if ((boxpos = (viewx <= bspcoord[BOXLEFT] ? 0 : viewx < bspcoord[BOXRIGHT] ? 1 : 2) + (viewy >= bspcoord[BOXTOP] ? 0 : viewy > bspcoord[BOXBOTTOM] ? 4 : 8)) == 5) + if (viewx <= bspcoord[BOXLEFT]) + boxpos = 0; + else if (viewx < bspcoord[BOXRIGHT]) + boxpos = 1; + else + boxpos = 2; + + if (viewy >= bspcoord[BOXTOP]) + boxpos |= 0; + else if (viewy > bspcoord[BOXBOTTOM]) + boxpos |= 1<<2; + else + boxpos |= 2<<2; + + if (boxpos == 5) return true; check = checkcoord[boxpos]; @@ -655,7 +670,8 @@ static boolean R_CheckBBox(const fixed_t *bspcoord) sx2 = viewangletox[angle2]; // Does not cross a pixel. - if (sx1 >= sx2) return false; + if (sx1 >= sx2) + return false; start = solidsegs; while (start->last < sx2) @@ -1319,7 +1335,8 @@ void R_RenderBSPNode(INT32 bspnum) bsp = &nodes[bspnum]; // Decide which side the view point is on. - side = R_PointOnSide(viewx, viewy, bsp); + side = R_PointOnSideFast(viewx, viewy, bsp); + // Recursively divide front space. R_RenderBSPNode(bsp->children[side]); diff --git a/src/r_bsp.h b/src/r_bsp.h index 0d73c2bc4..f93541d7b 100644 --- a/src/r_bsp.h +++ b/src/r_bsp.h @@ -25,7 +25,8 @@ extern side_t *sidedef; extern line_t *linedef; extern sector_t *frontsector; extern sector_t *backsector; -extern portal_pair *g_portal; // is curline a portal seg? +typedef struct portal_s portal_t; +extern portal_t *g_portal; // is curline a portal seg? // drawsegs are allocated on the fly... see r_segs.c @@ -41,7 +42,6 @@ void R_ClearClipSegs(void); void R_PortalClearClipSegs(INT32 start, INT32 end); void R_ClearDrawSegs(void); void R_RenderBSPNode(INT32 bspnum); -void R_AddPortal(INT32 line1, INT32 line2, INT32 x1, INT32 x2); // determines when a given sector shouldn't abide by the encoremap's palette. // no longer a static since this is used for encore in hw_main.c as well now: diff --git a/src/r_defs.h b/src/r_defs.h index 71e13e4d4..bc95649bb 100644 --- a/src/r_defs.h +++ b/src/r_defs.h @@ -687,14 +687,6 @@ typedef struct #pragma pack() #endif -typedef enum // trimmed since its only real use here is for xscale/yscale -{ - RF_HORIZONTALFLIP = 0x0001, // Flip sprite horizontally - RF_VERTICALFLIP = 0x0002, // Flip sprite vertically - RF_ABSOLUTEOFFSETS = 0x0004, // Sprite uses the object's offsets absolutely, instead of relatively - RF_FLIPOFFSETS = 0x0008, // Relative object offsets are flipped with the sprite -} renderflags_t; - typedef enum { SRF_SINGLE = 0, // 0-angle for all rotations diff --git a/src/r_fps.c b/src/r_fps.c index 9ccba8a7b..b861dea56 100644 --- a/src/r_fps.c +++ b/src/r_fps.c @@ -23,6 +23,7 @@ #include "r_state.h" #include "z_zone.h" #include "console.h" // con_startup_loadprogress +#include "i_time.h" #ifdef HWRENDER #include "hardware/hw_main.h" // for cv_grshearing @@ -79,6 +80,7 @@ static viewvars_t skyview_old[MAXSPLITSCREENPLAYERS]; static viewvars_t skyview_new[MAXSPLITSCREENPLAYERS]; static viewvars_t *oldview = &pview_old[0]; +static tic_t last_view_update; static int oldview_invalid[MAXSPLITSCREENPLAYERS] = {0, 0, 0, 0}; viewvars_t *newview = &pview_new[0]; @@ -89,19 +91,24 @@ static levelinterpolator_t **levelinterpolators; static size_t levelinterpolators_len; static size_t levelinterpolators_size; +static inline fixed_t R_LerpFixedView(fixed_t from, fixed_t to, fixed_t frac) +{ + return from + FixedMul(frac, to - from); +} + +static inline angle_t R_LerpAngleView(angle_t from, angle_t to, fixed_t frac) +{ + return from + FixedMul(frac, to - from); +} static inline fixed_t R_LerpFixed(fixed_t from, fixed_t to, fixed_t frac) { - if (from == to) - return to; - return from + FixedMul(frac, to - from); + return ((from == to) ? to : (from + FixedMul(frac, to - from))); } static inline angle_t R_LerpAngle(angle_t from, angle_t to, fixed_t frac) { - if (from == to) - return to; - return from + FixedMul(frac, to - from); + return ((from == to) ? to : (from + FixedMul(frac, to - from))); } /*static vector2_t *R_LerpVector2(const vector2_t *from, const vector2_t *to, fixed_t frac, vector2_t *out) @@ -129,7 +136,7 @@ static void R_SetupFreelook(void) // (lmps, network and use F12...) if (rendermode == render_soft #ifdef HWRENDER - || cv_grshearing.value + || cv_glshearing.value #endif ) { @@ -151,7 +158,7 @@ static void R_SetupFreelook(void) void R_InterpolateViewRollAngle(fixed_t frac) { - viewroll = R_LerpAngle(oldview->roll, newview->roll, frac); + viewroll = R_LerpAngleView(oldview->roll, newview->roll, frac); } void R_InterpolateView(fixed_t frac, boolean forceinvalid) @@ -179,19 +186,19 @@ void R_InterpolateView(fixed_t frac, boolean forceinvalid) prevview = newview; } - viewx = R_LerpFixed(prevview->x, newview->x, frac); - viewy = R_LerpFixed(prevview->y, newview->y, frac); - viewz = R_LerpFixed(prevview->z, newview->z, frac); + viewx = R_LerpFixedView(prevview->x, newview->x, frac); + viewy = R_LerpFixedView(prevview->y, newview->y, frac); + viewz = R_LerpFixedView(prevview->z, newview->z, frac); - viewangle = R_LerpAngle(prevview->angle, newview->angle, frac); - aimingangle = R_LerpAngle(prevview->aim, newview->aim, frac); - viewroll = R_LerpAngle(prevview->roll, newview->roll, frac); + viewangle = R_LerpAngleView(prevview->angle, newview->angle, frac); + aimingangle = R_LerpAngleView(prevview->aim, newview->aim, frac); + viewroll = R_LerpAngleView(prevview->roll, newview->roll, frac); viewsin = FINESINE(viewangle>>ANGLETOFINESHIFT); viewcos = FINECOSINE(viewangle>>ANGLETOFINESHIFT); viewplayer = newview->player; - viewsector = R_PointInSubsector(viewx, viewy)->sector; + viewsector = R_PointInSubsectorFast(viewx, viewy)->sector; R_SetupFreelook(); } @@ -207,21 +214,27 @@ void R_UpdateViewInterpolation(void) if (oldview_invalid[i]) oldview_invalid[i]--; } + + last_view_update = I_GetTime(); } void R_ResetViewInterpolation(UINT8 p) { + // Wait an extra tic if the interpolation state hasn't + // updated yet. + int t = ((last_view_update == I_GetTime()) ? 1 : 2); + if (p == 0) { UINT8 i; for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { - oldview_invalid[i]++; + oldview_invalid[i] = t; } } else { - oldview_invalid[p - 1]++; + oldview_invalid[p - 1] = t; } } @@ -293,7 +306,7 @@ void R_InterpolateMobjState(mobj_t *mobj, fixed_t frac, interpmobjstate_t *out) out->y = mobj->y; out->z = mobj->z; out->scale = mobj->scale; - out->subsector = mobj->subsector; + //out->subsector = mobj->subsector; out->angle = mobj->player ? mobj->player->frameangle : mobj->angle; out->pitch = mobj->pitch; out->roll = mobj->roll; @@ -314,8 +327,7 @@ void R_InterpolateMobjState(mobj_t *mobj, fixed_t frac, interpmobjstate_t *out) out->spritexoffset = mobj->resetinterp ? mobj->spritexoffset : R_LerpFixed(mobj->old_spritexoffset, mobj->spritexoffset, frac); out->spriteyoffset = mobj->resetinterp ? mobj->spriteyoffset : R_LerpFixed(mobj->old_spriteyoffset, mobj->spriteyoffset, frac); out->scale = mobj->resetinterp ? mobj->scale : R_LerpFixed(mobj->old_scale, mobj->scale, frac); - //out->subsector = R_PointInSubsector(out->x, out->y); // why was this even done? - out->subsector = mobj->subsector; + //out->subsector = R_PointInSubsector(out->x, out->y); // this is unused if (mobj->player) out->angle = mobj->resetinterp ? mobj->player->frameangle : R_LerpAngle(mobj->player->old_frameangle, mobj->player->frameangle, frac); @@ -323,7 +335,7 @@ void R_InterpolateMobjState(mobj_t *mobj, fixed_t frac, interpmobjstate_t *out) out->angle = mobj->resetinterp ? mobj->angle : R_LerpAngle(mobj->old_angle, mobj->angle, frac); #ifdef HWRENDER - if (cv_grmdls.value) + if (rendermode == render_opengl && cv_glmdls.value) { // pitch roll stuff out->pitch = mobj->resetinterp ? mobj->pitch : R_LerpAngle(mobj->old_pitch, mobj->pitch, frac); @@ -351,7 +363,7 @@ void R_InterpolatePrecipMobjState(precipmobj_t *mobj, fixed_t frac, interpmobjst out->y = mobj->y; out->z = mobj->z; out->scale = cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT; - out->subsector = mobj->subsector; + //out->subsector = mobj->subsector; out->angle = mobj->angle; out->spritexscale = mobj->spritexscale; out->spriteyscale = mobj->spriteyscale; @@ -368,9 +380,8 @@ void R_InterpolatePrecipMobjState(precipmobj_t *mobj, fixed_t frac, interpmobjst out->spriteyscale = mobj->spriteyscale; out->spritexoffset = mobj->spritexoffset; out->spriteyoffset = mobj->spriteyoffset; + //out->subsector = R_PointInSubsector(out->x, out->y); // this is unused - //out->subsector = R_PointInSubsector(out->x, out->y); // i dont understand lol - out->subsector = mobj->subsector; out->angle = R_LerpAngle(mobj->old_angle, mobj->angle, frac); } diff --git a/src/r_fps.h b/src/r_fps.h index a4aef71cd..5ac6cfe90 100644 --- a/src/r_fps.h +++ b/src/r_fps.h @@ -59,7 +59,7 @@ typedef struct { fixed_t x; fixed_t y; fixed_t z; - subsector_t *subsector; + //subsector_t *subsector; angle_t angle; fixed_t scale; fixed_t spritexscale; diff --git a/src/r_main.c b/src/r_main.c index 4d79fda92..9541fef41 100644 --- a/src/r_main.c +++ b/src/r_main.c @@ -31,6 +31,7 @@ #include "p_spec.h" // skyboxmo #include "z_zone.h" #include "m_random.h" // quake camera shake +#include "r_portal.h" #include "doomstat.h" // MAXSPLITSCREENPLAYERS #include "r_fps.h" // Frame interpolation/uncapped #include "tables.h" @@ -66,14 +67,6 @@ boolean skyVisiblePerPlayer[MAXSPLITSCREENPLAYERS]; // saved values of skyVisibl sector_t *viewsector; player_t *viewplayer; -// PORTALS! -// You can thank and/or curse JTE for these. -UINT8 portalrender; -sector_t *portalcullsector; -portal_pair *portal_base, *portal_cap; -line_t *portalclipline; -INT32 portalclipstart, portalclipend; - fixed_t rendertimefrac; fixed_t rendertimefrac_unpaused; fixed_t renderdeltatics; @@ -168,14 +161,20 @@ void SendWeaponPref4(void); static void Precipstuff_OnChange(void); consvar_t cv_tailspickup = {"tailspickup", "On", CV_NETVAR|CV_NOSHOWHELP, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_chasecam = {"chasecam", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_chasecam2 = {"chasecam2", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_chasecam3 = {"chasecam3", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_chasecam4 = {"chasecam4", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_flipcam = {"flipcam", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_flipcam2 = {"flipcam2", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam2_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_flipcam3 = {"flipcam3", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam3_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_flipcam4 = {"flipcam4", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam4_OnChange, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_chasecam[MAXSPLITSCREENPLAYERS] = { + {"chasecam", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"chasecam2", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"chasecam3", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"chasecam4", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + +consvar_t cv_flipcam[MAXSPLITSCREENPLAYERS] = { + {"flipcam", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"flipcam2", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam2_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"flipcam3", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam3_OnChange, 0, NULL, NULL, 0, 0, NULL}, + {"flipcam4", "No", CV_SAVE|CV_CALL|CV_NOINIT, CV_YesNo, FlipCam4_OnChange, 0, NULL, NULL, 0, 0, NULL} +}; consvar_t cv_shadow = {"shadow", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_shadowoffs = {"offsetshadows", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -194,7 +193,7 @@ consvar_t cv_drawdist_precip = {"drawdist_precip", "1024", CV_SAVE|CV_CALL|CV_NO consvar_t cv_lessprecip = {"lessweathereffects", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, Precipstuff_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_mobjscaleprecip = {"scaleprecipmobjscale", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, Precipstuff_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_grmaxinterpdist = {"gr_maxinterpdist", "Infinite", CV_SAVE, maxinterpdist_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_maxinterpdist = {"maxinterpdist", "Infinite", CV_SAVE, maxinterpdist_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_ripplewater = {"waterripples", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -299,32 +298,6 @@ static void Precipstuff_OnChange(void) P_SpawnPrecipitation(); } -// -// R_PointOnSide -// Traverse BSP (sub) tree, -// check point against partition plane. -// Returns side 0 (front) or 1 (back). -// -// killough 5/2/98: reformatted -// -PUREFUNC INT32 R_PointOnSide(fixed_t x, fixed_t y, const node_t *restrict node) -{ - if (!node->dx) - return x <= node->x ? node->dy > 0 : node->dy < 0; - - if (!node->dy) - return y <= node->y ? node->dx < 0 : node->dx > 0; - - x -= node->x; - y -= node->y; - - // Try to quickly decide by looking at sign bits. - // also use a mask to avoid branch prediction - INT32 mask = (node->dy ^ node->dx ^ x ^ y) >> 31; - return (mask & ((node->dy ^ x) < 0)) | // (left is negative) - (~mask & (FixedMul(y, node->dx>>FRACBITS) >= FixedMul(node->dy>>FRACBITS, x))); -} - // // R_PointToAngle // To get a global angle from cartesian coordinates, @@ -390,17 +363,19 @@ angle_t R_PointToAngle2(fixed_t pviewx, fixed_t pviewy, fixed_t x, fixed_t y) angle_t R_PlayerSliptideAngle(player_t *player) { mobj_t *mo; - spritedef_t *sprdef; - spriteframe_t *sprframe; - angle_t ang = 0; + spritedef_t *sprdef; + spriteframe_t *sprframe; + angle_t ang = 0; - if (!cv_sliptideroll.value || !player || P_MobjWasRemoved(player->mo)) - return 0; + if (!cv_sloperoll.value || !cv_sliptideroll.value || !player || P_MobjWasRemoved(player->mo)) + return 0; - mo = player->mo; + mo = player->mo; - size_t rot = mo->frame & FF_FRAMEMASK; - boolean papersprite = (mo->frame & FF_PAPERSPRITE); + if (mo->player->sliproll == 0 || mo->player->kartstuff[k_aizdriftstrat] == 0) + return 0; + + size_t rot = (mo->frame & FF_FRAMEMASK); if (mo->skin && mo->sprite == SPR_PLAY) { @@ -417,7 +392,7 @@ angle_t R_PlayerSliptideAngle(player_t *player) if (rot >= sprdef->numframes) { sprdef = &sprites[states[S_UNKNOWN].sprite]; - rot = states[S_UNKNOWN].frame&FF_FRAMEMASK; + rot = (states[S_UNKNOWN].frame & FF_FRAMEMASK); } sprframe = &sprdef->spriteframes[rot]; @@ -425,10 +400,10 @@ angle_t R_PlayerSliptideAngle(player_t *player) // No sprite frame? I guess it is possible if (!sprframe) return 0; - if (sprframe->rotate != SRF_SINGLE || papersprite) + if (sprframe->rotate != SRF_SINGLE || (mo->frame & FF_PAPERSPRITE)) ang = R_PointToAngle(mo->x, mo->y) - mo->angle; - return FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), mo->player->sliproll*(mo->player->sliptidemem)); + return FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), mo->player->sliproll * mo->player->kartstuff[k_aizdriftstrat]); } INT32 R_GetHudUncap(void) @@ -1051,19 +1026,6 @@ void R_Init(void) framecount = 0; } -// -// R_PointInSubsector -// -subsector_t *R_PointInSubsector(fixed_t x, fixed_t y) -{ - size_t nodenum = numnodes-1; - - while (!(nodenum & NF_SUBSECTOR)) - nodenum = nodes[nodenum].children[R_PointOnSide(x, y, nodes+nodenum)]; - - return &subsectors[nodenum & ~NF_SUBSECTOR]; -} - // // R_IsPointInSubsector, same as above but returns 0 if not in subsector // @@ -1074,16 +1036,13 @@ subsector_t *R_IsPointInSubsector(fixed_t x, fixed_t y) size_t nodenum; subsector_t *ret; - // single subsector is a special case - //if (numnodes == 0) - //return subsectors; - nodenum = numnodes - 1; while (!(nodenum & NF_SUBSECTOR)) { node = &nodes[nodenum]; - side = R_PointOnSide(x, y, node); + //side = R_PointOnSide(x, y, node); + side = R_PointOnSideFast(x, y, node); // this is fine since R_IsPointInSubsector is only used for precip spawn unless you disable noclipcam lol nodenum = node->children[side]; } @@ -1101,38 +1060,29 @@ subsector_t *R_IsPointInSubsector(fixed_t x, fixed_t y) mobj_t *viewmobj; -void R_SkyboxFrame(player_t *player) +static void +R_SetupCommonFrame +( player_t * player, + subsector_t * subsector) { - camera_t *thiscam = &camera[0]; - UINT8 i; + newview->player = player; - if (splitscreen) - { - for (i = 0; i <= splitscreen; i++) - { - if (player == &players[displayplayers[i]]) - { - thiscam = &camera[i]; - R_SetViewContext(VIEWCONTEXT_SKY1 + i); - break; - } - } - } + newview->x += quake.x; + newview->y += quake.y; + newview->z += quake.z; + + newview->roll = R_ViewRollAngle(player); + + if (subsector) + newview->sector = subsector->sector; else - { - R_SetViewContext(VIEWCONTEXT_SKY1); - } + newview->sector = R_PointInSubsector(newview->x, newview->y)->sector; - // cut-away view stuff - newview->sky = true; - viewmobj = skyboxmo[0]; -#ifdef PARANOIA - if (!viewmobj) - { - const size_t playeri = (size_t)(player - players); - I_Error("R_SkyboxFrame: viewmobj null (player %s)", sizeu1(playeri)); - } -#endif + R_InterpolateView(R_UsingFrameInterpolation() ? (demo.playback && demo.freecam) ? rendertimefrac_unpaused : rendertimefrac : FRACUNIT, false); +} + +static void R_SetupAimingFrame(player_t *player, camera_t *thiscam) +{ if (player->awayviewtics) { newview->aim = player->awayviewaiming; @@ -1147,31 +1097,43 @@ void R_SkyboxFrame(player_t *player) { newview->aim = player->aiming; newview->angle = player->mo->angle; + if (!demo.playback && player->playerstate != PST_DEAD) { - if (player == &players[consoleplayer]) + for (UINT8 i = 0; i <= splitscreen; i++) { - newview->angle = localangle[0]; // WARNING: camera uses this - newview->aim = localaiming[0]; - } - else if (splitscreen) - { - for (i = 1; i <= splitscreen; i++) + if (player == (i == 0 ? &players[consoleplayer] : &players[displayplayers[i]])) { - if (player == &players[displayplayers[i]]) - { - newview->angle = localangle[i]; - newview->aim = localaiming[i]; - break; - } + newview->angle = localangle[i]; + newview->aim = localaiming[i]; + break; } } } } - newview->angle += viewmobj->angle; - newview->roll = R_ViewRollAngle(player); +} - newview->player = player; +void R_SkyboxFrame(int s) +{ + player_t *player = &players[displayplayers[s]]; + camera_t *thiscam = &camera[s]; + subsector_t * subsector = NULL; + + R_SetViewContext(VIEWCONTEXT_SKY1 + s); + + // cut-away view stuff + newview->sky = true; + viewmobj = skyboxmo[0]; +#ifdef PARANOIA + if (P_MobjWasRemoved(viewmobj)) + { + const size_t playeri = (size_t)(player - players); + I_Error("R_SkyboxFrame: viewmobj null (player %s)", sizeu1(playeri)); + } +#endif + R_SetupAimingFrame(player, thiscam); + + newview->angle += viewmobj->angle; newview->x = viewmobj->x; newview->y = viewmobj->y; @@ -1179,211 +1141,87 @@ void R_SkyboxFrame(player_t *player) if (viewmobj->spawnpoint) newview->z = ((fixed_t)viewmobj->spawnpoint->angle)<x += quake.x; - newview->y += quake.y; - newview->z += quake.z; +#define SETUPSKYVIEW(viewmo, zscale)\ + if (skyboxmo[1])\ + {\ + fixed_t x = 0, y = 0;\ + if (mh->skybox_scalex > 0)\ + x = (viewmo->x - skyboxmo[1]->x) / mh->skybox_scalex;\ + else if (mh->skybox_scalex < 0)\ + x = (viewmo->x - skyboxmo[1]->x) * -mh->skybox_scalex;\ + if (mh->skybox_scaley > 0)\ + y = (viewmo->y - skyboxmo[1]->y) / mh->skybox_scaley;\ + else if (mh->skybox_scaley < 0)\ + y = (viewmo->y - skyboxmo[1]->y) * -mh->skybox_scaley;\ + if (viewmobj->angle == 0)\ + {\ + newview->x += x;\ + newview->y += y;\ + }\ + else if (viewmobj->angle == ANGLE_90)\ + {\ + newview->x -= y;\ + newview->y += x;\ + }\ + else if (viewmobj->angle == ANGLE_180)\ + {\ + newview->x -= x;\ + newview->y -= y;\ + }\ + else if (viewmobj->angle == ANGLE_270)\ + {\ + newview->x += y;\ + newview->y -= x;\ + }\ + else\ + {\ + angle_t ang = viewmobj->angle>>ANGLETOFINESHIFT;\ + newview->x += FixedMul(x,FINECOSINE(ang)) - FixedMul(y, FINESINE(ang));\ + newview->y += FixedMul(x, FINESINE(ang)) + FixedMul(y,FINECOSINE(ang));\ + }\ + }\ + if (mh->skybox_scalez > 0)\ + newview->z += zscale / mh->skybox_scalez;\ + else if (mh->skybox_scalez < 0)\ + newview->z += zscale * -mh->skybox_scalez; if (mapheaderinfo[gamemap-1]) { mapheader_t *mh = mapheaderinfo[gamemap-1]; + if (player->awayviewtics) { - if (skyboxmo[1]) - { - fixed_t x = 0, y = 0; - if (mh->skybox_scalex > 0) - x = (player->awayviewmobj->x - skyboxmo[1]->x) / mh->skybox_scalex; - else if (mh->skybox_scalex < 0) - x = (player->awayviewmobj->x - skyboxmo[1]->x) * -mh->skybox_scalex; - - if (mh->skybox_scaley > 0) - y = (player->awayviewmobj->y - skyboxmo[1]->y) / mh->skybox_scaley; - else if (mh->skybox_scaley < 0) - y = (player->awayviewmobj->y - skyboxmo[1]->y) * -mh->skybox_scaley; - - if (viewmobj->angle == 0) - { - newview->x += x; - newview->y += y; - } - else if (viewmobj->angle == ANGLE_90) - { - newview->x -= y; - newview->y += x; - } - else if (viewmobj->angle == ANGLE_180) - { - newview->x -= x; - newview->y -= y; - } - else if (viewmobj->angle == ANGLE_270) - { - newview->x += y; - newview->y -= x; - } - else - { - angle_t ang = viewmobj->angle>>ANGLETOFINESHIFT; - newview->x += FixedMul(x,FINECOSINE(ang)) - FixedMul(y, FINESINE(ang)); - newview->y += FixedMul(x, FINESINE(ang)) + FixedMul(y,FINECOSINE(ang)); - } - } - if (mh->skybox_scalez > 0) - newview->z += (player->awayviewmobj->z + 20*FRACUNIT) / mh->skybox_scalez; - else if (mh->skybox_scalez < 0) - newview->z += (player->awayviewmobj->z + 20*FRACUNIT) * -mh->skybox_scalez; + SETUPSKYVIEW(player->awayviewmobj, (player->awayviewmobj->z + 20*FRACUNIT)); } else if (thiscam->chase) { - if (skyboxmo[1]) - { - fixed_t x = 0, y = 0; - if (mh->skybox_scalex > 0) - x = (thiscam->x - skyboxmo[1]->x) / mh->skybox_scalex; - else if (mh->skybox_scalex < 0) - x = (thiscam->x - skyboxmo[1]->x) * -mh->skybox_scalex; - - if (mh->skybox_scaley > 0) - y = (thiscam->y - skyboxmo[1]->y) / mh->skybox_scaley; - else if (mh->skybox_scaley < 0) - y = (thiscam->y - skyboxmo[1]->y) * -mh->skybox_scaley; - - if (viewmobj->angle == 0) - { - newview->x += x; - newview->y += y; - } - else if (viewmobj->angle == ANGLE_90) - { - newview->x -= y; - newview->y += x; - } - else if (viewmobj->angle == ANGLE_180) - { - newview->x -= x; - newview->y -= y; - } - else if (viewmobj->angle == ANGLE_270) - { - newview->x += y; - newview->y -= x; - } - else - { - angle_t ang = viewmobj->angle>>ANGLETOFINESHIFT; - newview->x += FixedMul(x,FINECOSINE(ang)) - FixedMul(y, FINESINE(ang)); - newview->y += FixedMul(x, FINESINE(ang)) + FixedMul(y,FINECOSINE(ang)); - } - } - if (mh->skybox_scalez > 0) - newview->z += (thiscam->z + (thiscam->height>>1)) / mh->skybox_scalez; - else if (mh->skybox_scalez < 0) - newview->z += (thiscam->z + (thiscam->height>>1)) * -mh->skybox_scalez; + SETUPSKYVIEW(thiscam, (thiscam->z + (thiscam->height>>1))); } else { - if (skyboxmo[1]) - { - fixed_t x = 0, y = 0; - if (mh->skybox_scalex > 0) - x = (player->mo->x - skyboxmo[1]->x) / mh->skybox_scalex; - else if (mh->skybox_scalex < 0) - x = (player->mo->x - skyboxmo[1]->x) * -mh->skybox_scalex; - if (mh->skybox_scaley > 0) - y = (player->mo->y - skyboxmo[1]->y) / mh->skybox_scaley; - else if (mh->skybox_scaley < 0) - y = (player->mo->y - skyboxmo[1]->y) * -mh->skybox_scaley; - - if (viewmobj->angle == 0) - { - newview->x += x; - newview->y += y; - } - else if (viewmobj->angle == ANGLE_90) - { - newview->x -= y; - newview->y += x; - } - else if (viewmobj->angle == ANGLE_180) - { - newview->x -= x; - newview->y -= y; - } - else if (viewmobj->angle == ANGLE_270) - { - newview->x += y; - newview->y -= x; - } - else - { - angle_t ang = viewmobj->angle>>ANGLETOFINESHIFT; - newview->x += FixedMul(x,FINECOSINE(ang)) - FixedMul(y, FINESINE(ang)); - newview->y += FixedMul(x, FINESINE(ang)) + FixedMul(y,FINECOSINE(ang)); - } - } - if (mh->skybox_scalez > 0) - newview->z += player->viewz / mh->skybox_scalez; - else if (mh->skybox_scalez < 0) - newview->z += player->viewz * -mh->skybox_scalez; + SETUPSKYVIEW(player->mo, player->viewz); } } +#undef SETUPSKYVIEW - if (viewmobj->subsector) - newview->sector = viewmobj->subsector->sector; - else - newview->sector = R_PointInSubsector(newview->x, newview->y)->sector; + if (!P_MobjWasRemoved(viewmobj)) + subsector = viewmobj->subsector; - R_InterpolateView(R_UsingFrameInterpolation() ? (demo.playback && demo.freecam) ? rendertimefrac_unpaused : rendertimefrac : FRACUNIT, false); + R_SetupCommonFrame(player, subsector); } -void R_SetupFrame(player_t *player, boolean skybox) +void R_SetupFrame(int s, boolean skybox) { - camera_t *thiscam; - boolean chasecam = false; + player_t *player = &players[displayplayers[s]]; + camera_t *thiscam = &camera[s]; + boolean chasecam = (cv_chasecam[s].value != 0); + subsector_t * subsector = NULL; - if (splitscreen > 2 && player == &players[displayplayers[3]]) + R_SetViewContext(VIEWCONTEXT_PLAYER1 + s); + if (thiscam->reset) { - thiscam = &camera[3]; - chasecam = (cv_chasecam4.value != 0); - R_SetViewContext(VIEWCONTEXT_PLAYER4); - if (thiscam->reset) - { - R_ResetViewInterpolation(4); - thiscam->reset = false; - } - } - else if (splitscreen > 1 && player == &players[displayplayers[2]]) - { - thiscam = &camera[2]; - chasecam = (cv_chasecam3.value != 0); - R_SetViewContext(VIEWCONTEXT_PLAYER3); - if (thiscam->reset) - { - R_ResetViewInterpolation(3); - thiscam->reset = false; - } - } - else if (splitscreen && player == &players[displayplayers[1]]) - { - thiscam = &camera[1]; - chasecam = (cv_chasecam2.value != 0); - R_SetViewContext(VIEWCONTEXT_PLAYER2); - if (thiscam->reset) - { - R_ResetViewInterpolation(2); - thiscam->reset = false; - } - } - else - { - thiscam = &camera[0]; - chasecam = (cv_chasecam.value != 0); - R_SetViewContext(VIEWCONTEXT_PLAYER1); - if (thiscam->reset) - { - R_ResetViewInterpolation(1); - thiscam->reset = false; - } + R_ResetViewInterpolation(s); + thiscam->reset = false; } if (player->spectator) // no spectator chasecam @@ -1401,192 +1239,72 @@ void R_SetupFrame(player_t *player, boolean skybox) newview->sky = !skybox; + R_SetupAimingFrame(player, thiscam); + if (player->awayviewtics) // cut-away view stuff { viewmobj = player->awayviewmobj; // should be a MT_ALTVIEWMAN I_Assert(viewmobj != NULL); + + newview->x = viewmobj->x; + newview->y = viewmobj->y; newview->z = viewmobj->z + 20*FRACUNIT; - newview->aim = player->awayviewaiming; - newview->angle = viewmobj->angle; + + if (!P_MobjWasRemoved(viewmobj)) + subsector = viewmobj->subsector; + + R_SetupCommonFrame(player, subsector); } else if (!player->spectator && (thiscam && chasecam)) // use outside cam view { viewmobj = NULL; + + newview->x = thiscam->x; + newview->y = thiscam->y; newview->z = thiscam->z + (thiscam->height>>1); - newview->aim = thiscam->aiming; - newview->angle = thiscam->angle; + + R_SetupCommonFrame(player, thiscam->subsector); } else // use the player's eyes view { - newview->z = player->viewz; - viewmobj = player->mo; I_Assert(viewmobj != NULL); - newview->aim = player->aiming; - newview->angle = viewmobj->angle; - - if (!demo.playback && player->playerstate != PST_DEAD) - { - if (player == &players[consoleplayer]) - { - newview->angle = localangle[0]; // WARNING: camera uses this - newview->aim = localaiming[0]; - } - else if (splitscreen) - { - UINT8 i; - for (i = 1; i <= splitscreen; i++) - { - if (player == &players[displayplayers[i]]) - { - newview->angle = localangle[i]; - newview->aim = localaiming[i]; - break; - } - } - } - } - } - newview->roll = R_ViewRollAngle(player); - newview->z += quake.z; - - newview->player = player; - - if ((thiscam && chasecam) && !player->awayviewtics && !player->spectator) - { - newview->x = thiscam->x; - newview->y = thiscam->y; - newview->x += quake.x; - newview->y += quake.y; - - if (thiscam->subsector && thiscam->subsector->sector) - newview->sector = thiscam->subsector->sector; - else - newview->sector = R_PointInSubsector(newview->x, newview->y)->sector; - } - else - { newview->x = viewmobj->x; newview->y = viewmobj->y; - newview->x += quake.x; - newview->y += quake.y; + newview->z = player->viewz; - if (!P_MobjWasRemoved(viewmobj) && viewmobj->subsector && thiscam && thiscam->subsector->sector) - newview->sector = viewmobj->subsector->sector; - else - newview->sector = R_PointInSubsector(newview->x, newview->y)->sector; + if (!P_MobjWasRemoved(viewmobj)) + subsector = viewmobj->subsector; + + R_SetupCommonFrame(player, subsector); } - - R_InterpolateView(R_UsingFrameInterpolation() ? (demo.playback && demo.freecam) ? rendertimefrac_unpaused : rendertimefrac : FRACUNIT, false); } -#define ANGLED_PORTALS - -static void R_PortalFrame(line_t *start, line_t *dest, portal_pair *portal) +static void R_PortalFrame(portal_t *portal) { - vertex_t dest_c, start_c; -#ifdef ANGLED_PORTALS - // delta angle - angle_t dangle = R_PointToAngle2(0,0,dest->dx,dest->dy) - R_PointToAngle2(start->dx,start->dy,0,0); -#endif - - //R_SetupFrame(player, false); viewx = portal->viewx; viewy = portal->viewy; viewz = portal->viewz; viewangle = portal->viewangle; - // newview->sin = FINESINE(newview->angle>>ANGLETOFINESHIFT); - // newview->cos = FINECOSINE(newview->angle>>ANGLETOFINESHIFT); + // viewsin = FINESINE(viewangle>>ANGLETOFINESHIFT); + // viewcos = FINECOSINE(viewangle>>ANGLETOFINESHIFT); - portalcullsector = dest->frontsector; - viewsector = dest->frontsector; - portalclipline = dest; portalclipstart = portal->start; portalclipend = portal->end; - // Offset the portal view by the linedef centers - - // looking glass center - start_c.x = (start->v1->x + start->v2->x) / 2; - start_c.y = (start->v1->y + start->v2->y) / 2; - - // other side center - dest_c.x = (dest->v1->x + dest->v2->x) / 2; - dest_c.y = (dest->v1->y + dest->v2->y) / 2; - - // Heights! - viewz += dest->frontsector->floorheight - start->frontsector->floorheight; - - // calculate the difference in position and rotation! -#ifdef ANGLED_PORTALS - if (dangle == 0) -#endif - { // the entrance goes straight opposite the exit, so we just need to mess with the offset. - viewx += dest_c.x - start_c.x; - viewy += dest_c.y - start_c.y; - return; - } - -#ifdef ANGLED_PORTALS - viewangle += dangle; - // newview->sin = FINESINE(newview->angle>>ANGLETOFINESHIFT); - // newview->cos = FINECOSINE(newview->angle>>ANGLETOFINESHIFT); - //CONS_Printf("dangle == %u\n", AngleFixed(dangle)>>FRACBITS); - - // ???? + if (portal->clipline != -1) { - fixed_t disttopoint; - angle_t angtopoint; - - disttopoint = R_PointToDist2(start_c.x, start_c.y, newview->x, newview->y); - angtopoint = R_PointToAngle2(start_c.x, start_c.y, newview->x, newview->y); - angtopoint += dangle; - - viewx = dest_c.x+FixedMul(FINECOSINE(angtopoint>>ANGLETOFINESHIFT), disttopoint); - viewy = dest_c.y+FixedMul(FINESINE(angtopoint>>ANGLETOFINESHIFT), disttopoint); - } -#endif -} - -void R_AddPortal(INT32 line1, INT32 line2, INT32 x1, INT32 x2) -{ - portal_pair *portal = Z_Malloc(sizeof(portal_pair), PU_LEVEL, NULL); - INT16 *ceilingclipsave = Z_Malloc(sizeof(INT16)*(x2-x1), PU_LEVEL, NULL); - INT16 *floorclipsave = Z_Malloc(sizeof(INT16)*(x2-x1), PU_LEVEL, NULL); - fixed_t *frontscalesave = Z_Malloc(sizeof(fixed_t)*(x2-x1), PU_LEVEL, NULL); - - portal->line1 = line1; - portal->line2 = line2; - portal->pass = portalrender+1; - portal->next = NULL; - - R_PortalStoreClipValues(x1, x2, ceilingclipsave, floorclipsave, frontscalesave); - - portal->ceilingclip = ceilingclipsave; - portal->floorclip = floorclipsave; - portal->frontscale = frontscalesave; - - portal->start = x1; - portal->end = x2; - - g_portal = portal; // this tells R_StoreWallRange that curline is a portal seg - - portal->viewx = viewx; - portal->viewy = viewy; - portal->viewz = viewz; - portal->viewangle = viewangle; - - if (!portal_base) - { - portal_base = portal; - portal_cap = portal; + portalclipline = &lines[portal->clipline]; + portalcullsector = portalclipline->frontsector; + viewsector = portalclipline->frontsector; } else { - portal_cap->next = portal; - portal_cap = portal; + portalclipline = NULL; + portalcullsector = NULL; + viewsector = R_PointInSubsector(viewx, viewy)->sector; } } @@ -1602,7 +1320,6 @@ void R_AddPortal(INT32 line1, INT32 line2, INT32 x1, INT32 x2) void R_RenderPlayerView(player_t *player) { - portal_pair *portal; const boolean skybox = (skyboxmo[0] && cv_skybox.value); UINT8 i; @@ -1639,13 +1356,12 @@ void R_RenderPlayerView(player_t *player) break; } - portalrender = 0; - portal_base = portal_cap = NULL; + Portal_InitList(); PS_START_TIMING(ps_skyboxtime); if (skybox && skyVisible) { - R_SkyboxFrame(player); + R_SkyboxFrame(viewssnum); R_ClearClipSegs(); R_ClearDrawSegs(); @@ -1665,7 +1381,7 @@ void R_RenderPlayerView(player_t *player) } PS_STOP_TIMING(ps_skyboxtime); - R_SetupFrame(player, skybox); + R_SetupFrame(viewssnum, skybox); skyVisible = false; framecount++; validcount++; @@ -1705,37 +1421,41 @@ void R_RenderPlayerView(player_t *player) ps_numsprites.value.i = numvisiblesprites; - // PORTAL RENDERING PS_START_TIMING(ps_sw_portaltime); - for(portal = portal_base; portal; portal = portal_base) + // Portal rendering. Hijacks the BSP traversal. + if (portal_base) { - // render the portal - CONS_Debug(DBG_RENDER, "Rendering portal from line %d to %d\n", portal->line1, portal->line2); - portalrender = portal->pass; + portal_t *portal; - R_PortalFrame(&lines[portal->line1], &lines[portal->line2], portal); + for (portal = portal_base; portal; portal = portal_base) + { + portalrender = portal->pass; // Recursiveness depth. - R_PortalClearClipSegs(portal->start, portal->end); + R_ClearFFloorClips(); - R_PortalRestoreClipValues(portal->start, portal->end, portal->ceilingclip, portal->floorclip, portal->frontscale); + // Apply the viewpoint stored for the portal. + R_PortalFrame(portal); - validcount++; + // Hack in the clipsegs to delimit the starting + // clipping for sprites and possibly other similar + // future items. + R_PortalClearClipSegs(portal->start, portal->end); - R_RenderBSPNode((INT32)numnodes - 1); - R_ClipSprites(); - //R_DrawPlanes(); - //R_DrawMasked(); + // Hack in the top/bottom clip values for the window + // that were previously stored. + Portal_ClipApply(portal); - // okay done. free it. - portalcullsector = NULL; // Just in case... - portal_base = portal->next; - Z_Free(portal->ceilingclip); - Z_Free(portal->floorclip); - Z_Free(portal->frontscale); - Z_Free(portal); + // Render the BSP from the new viewpoint, and clip + // any sprites with the new clipsegs and window. + R_RenderBSPNode((INT32)numnodes - 1); + R_ClipSprites(); + + Portal_Remove(portal); + + validcount++; + } } PS_STOP_TIMING(ps_sw_portaltime); - // END PORTAL RENDERING PS_START_TIMING(ps_sw_planetime); R_DrawPlanes(); @@ -1767,15 +1487,18 @@ void R_RenderPlayerView(player_t *player) void R_RegisterEngineStuff(void) { + INT32 i; + CV_RegisterVar(&cv_gravity); CV_RegisterVar(&cv_tailspickup); CV_RegisterVar(&cv_soniccd); CV_RegisterVar(&cv_allowmlook); CV_RegisterVar(&cv_homremoval); - CV_RegisterVar(&cv_flipcam); - CV_RegisterVar(&cv_flipcam2); - CV_RegisterVar(&cv_flipcam3); - CV_RegisterVar(&cv_flipcam4); + + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + CV_RegisterVar(&cv_flipcam[i]); + } // Enough for dedicated server if (dedicated) @@ -1788,43 +1511,25 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_mobjscaleprecip); CV_RegisterVar(&cv_fov); - CV_RegisterVar(&cv_chasecam); - CV_RegisterVar(&cv_chasecam2); - CV_RegisterVar(&cv_chasecam3); - CV_RegisterVar(&cv_chasecam4); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + CV_RegisterVar(&cv_chasecam[i]); + } CV_RegisterVar(&cv_shadow); CV_RegisterVar(&cv_shadowoffs); CV_RegisterVar(&cv_skybox); CV_RegisterVar(&cv_ffloorclip); CV_RegisterVar(&cv_spriteclip); - CV_RegisterVar(&cv_cam_dist); - CV_RegisterVar(&cv_cam_still); - CV_RegisterVar(&cv_cam_height); - CV_RegisterVar(&cv_cam_speed); - CV_RegisterVar(&cv_cam_rotate); - CV_RegisterVar(&cv_cam_rotspeed); - - CV_RegisterVar(&cv_cam2_dist); - CV_RegisterVar(&cv_cam2_still); - CV_RegisterVar(&cv_cam2_height); - CV_RegisterVar(&cv_cam2_speed); - CV_RegisterVar(&cv_cam2_rotate); - CV_RegisterVar(&cv_cam2_rotspeed); - - CV_RegisterVar(&cv_cam3_dist); - CV_RegisterVar(&cv_cam3_still); - CV_RegisterVar(&cv_cam3_height); - CV_RegisterVar(&cv_cam3_speed); - CV_RegisterVar(&cv_cam3_rotate); - CV_RegisterVar(&cv_cam3_rotspeed); - - CV_RegisterVar(&cv_cam4_dist); - CV_RegisterVar(&cv_cam4_still); - CV_RegisterVar(&cv_cam4_height); - CV_RegisterVar(&cv_cam4_speed); - CV_RegisterVar(&cv_cam4_rotate); - CV_RegisterVar(&cv_cam4_rotspeed); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + CV_RegisterVar(&cv_cam_dist[i]); + CV_RegisterVar(&cv_cam_still[i]); + CV_RegisterVar(&cv_cam_height[i]); + CV_RegisterVar(&cv_cam_speed[i]); + CV_RegisterVar(&cv_cam_rotate[i]); + CV_RegisterVar(&cv_cam_rotspeed[i]); + } CV_RegisterVar(&cv_tilting); CV_RegisterVar(&cv_quaketilt); @@ -1836,7 +1541,6 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_driftsparkpulse); CV_RegisterVar(&cv_gravstretch); CV_RegisterVar(&cv_sloperoll); - CV_RegisterVar(&cv_spriteroll); CV_RegisterVar(&cv_sliptideroll); CV_RegisterVar(&cv_sloperolldist); CV_RegisterVar(&cv_sparkroll); @@ -1847,7 +1551,7 @@ void R_RegisterEngineStuff(void) CV_RegisterVar(&cv_maxportals); - CV_RegisterVar(&cv_grmaxinterpdist); + CV_RegisterVar(&cv_maxinterpdist); CV_RegisterVar(&cv_ripplewater); diff --git a/src/r_main.h b/src/r_main.h index 0bfa8bfa5..523e924d5 100644 --- a/src/r_main.h +++ b/src/r_main.h @@ -72,7 +72,40 @@ extern lighttable_t *zlight[LIGHTLEVELS][MAXLIGHTZ]; #define COLORMAP_REMAPOFFSET COLORMAP_SIZE // Utility functions. -INT32 R_PointOnSide(fixed_t x, fixed_t y, const node_t *node); + +// +// R_PointOnSide +// Traverse BSP (sub) tree, +// check point against partition plane. +// Returns side 0 (front) or 1 (back). +// +// killough 5/2/98: reformatted +// +FUNCINLINE static ATTRINLINE PUREFUNC INT32 R_PointOnSide(fixed_t x, fixed_t y, const node_t *restrict node) +{ + if (!node->dx) + return x <= node->x ? node->dy > 0 : node->dy < 0; + + if (!node->dy) + return y <= node->y ? node->dx < 0 : node->dx > 0; + + x -= node->x; + y -= node->y; + + // Try to quickly decide by looking at sign bits. + // also use a mask to avoid branch prediction + INT32 mask = (node->dy ^ node->dx ^ x ^ y) >> 31; + return (mask & ((node->dy ^ x) < 0)) | // (left is negative) + (~mask & (FixedMul(y, node->dx>>FRACBITS) >= FixedMul(node->dy>>FRACBITS, x))); +} + +// This is not as accurate +// SHOULD NOT BE USED FOR ANYTHING GAMEPLAY RELATED!! +FUNCINLINE static ATTRINLINE PUREFUNC INT32 R_PointOnSideFast(fixed_t x, fixed_t y, const node_t *node) +{ + // use cross product to determine side quickly + return ((INT64)y - node->y) * node->dx - ((INT64)x - node->x) * node->dy > 0; +} FUNCINLINE static ATTRINLINE PUREFUNC INT32 R_PointOnSegSide(fixed_t x, fixed_t y, const seg_t *line) { @@ -81,8 +114,8 @@ FUNCINLINE static ATTRINLINE PUREFUNC INT32 R_PointOnSegSide(fixed_t x, fixed_t fixed_t ldx = line->v2->x - lx; fixed_t ldy = line->v2->y - ly; - // heavily optimized version of R_PointOnSide, stolen from GZDoom. - return (INT64)(y - ly) * ldx + (INT64)(lx - x) * ldy > 0; + // use cross product to determine side quickly + return ((INT64)y - ly) * ldx - ((INT64)x - lx) * ldy > 0; } angle_t R_PointToAngle(fixed_t x, fixed_t y); @@ -91,37 +124,40 @@ angle_t R_PointToAngle2(fixed_t px2, fixed_t py2, fixed_t px1, fixed_t py1); angle_t R_PlayerSliptideAngle(player_t *player); fixed_t R_ScaleFromGlobalAngle(angle_t visangle); -subsector_t *R_PointInSubsector(fixed_t x, fixed_t y); + subsector_t *R_IsPointInSubsector(fixed_t x, fixed_t y); +// +// R_PointInSubsector +// +FUNCINLINE static ATTRINLINE subsector_t *R_PointInSubsector(fixed_t x, fixed_t y) +{ + size_t nodenum = numnodes-1; + + while (!(nodenum & NF_SUBSECTOR)) + nodenum = nodes[nodenum].children[R_PointOnSide(x, y, nodes+nodenum)]; + + return &subsectors[nodenum & ~NF_SUBSECTOR]; +} + +// uses R_PointOnSideFast +// SHOULD NOT BE USED FOR ANYTHING GAMEPLAY RELATED!! +FUNCINLINE static ATTRINLINE subsector_t *R_PointInSubsectorFast(fixed_t x, fixed_t y) +{ + size_t nodenum = numnodes-1; + + while (!(nodenum & NF_SUBSECTOR)) + nodenum = nodes[nodenum].children[R_PointOnSideFast(x, y, nodes+nodenum)]; + + return &subsectors[nodenum & ~NF_SUBSECTOR]; +} + #define R_PointToDist(x, y) R_PointToDist2(viewx, viewy, x, y) #define R_PointToDist2(px2, py2, px1, py1) FixedHypot((px1) - (px2), (py1) - (py2)) - boolean R_DoCulling(line_t *cullheight, line_t *viewcullheight, fixed_t vz, fixed_t bottomh, fixed_t toph); void R_GetRenderBlockMapDimensions(fixed_t drawdist, INT32 *xl, INT32 *xh, INT32 *yl, INT32 *yh); - -typedef struct portal_pair -{ - INT32 line1; - INT32 line2; - UINT8 pass; - struct portal_pair *next; - - fixed_t viewx; - fixed_t viewy; - fixed_t viewz; - angle_t viewangle; - - INT32 start; - INT32 end; - INT16 *ceilingclip; - INT16 *floorclip; - fixed_t *frontscale; -} portal_pair; - - // Performance stats extern precise_t ps_prevframetime;// time when previous frame was rendered extern ps_metric_t ps_rendercalltime; @@ -148,8 +184,8 @@ extern ps_metric_t ps_numpolyobjects; extern consvar_t cv_showhud, cv_translucenthud, cv_uncappedhud; extern consvar_t cv_homremoval; -extern consvar_t cv_chasecam, cv_chasecam2, cv_chasecam3, cv_chasecam4; -extern consvar_t cv_flipcam, cv_flipcam2, cv_flipcam3, cv_flipcam4; +extern consvar_t cv_chasecam[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_flipcam[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_shadow, cv_shadowoffs; extern consvar_t cv_ffloorclip, cv_spriteclip; extern consvar_t cv_translucency; @@ -157,7 +193,7 @@ extern consvar_t cv_drawdist, cv_drawdist_precip, cv_lessprecip, cv_mobjscalepre extern consvar_t cv_fov; extern consvar_t cv_skybox; extern consvar_t cv_tailspickup; -extern consvar_t cv_grmaxinterpdist; +extern consvar_t cv_maxinterpdist; extern consvar_t cv_ripplewater; // Called by startup code. @@ -174,9 +210,9 @@ void R_SetViewSize(void); // do it (sometimes explicitly called) void R_ExecuteSetViewSize(void); -void R_SkyboxFrame(player_t *player); +void R_SkyboxFrame(int s); +void R_SetupFrame(int s, boolean skybox); -void R_SetupFrame(player_t *player, boolean skybox); // Called by G_Drawer. void R_RenderPlayerView(player_t *player); diff --git a/src/r_patch.c b/src/r_patch.c index eea97cfbb..50dda0c5f 100644 --- a/src/r_patch.c +++ b/src/r_patch.c @@ -14,9 +14,11 @@ #include "byteptr.h" #include "dehacked.h" +#include "doomdef.h" #include "i_video.h" #include "r_data.h" #include "r_draw.h" +#include "r_fps.h" #include "r_patch.h" #include "r_things.h" #include "z_zone.h" @@ -775,11 +777,11 @@ static UINT16 GetPatchPixel(patch_t *patch, INT32 x, INT32 y, boolean flip) #ifdef HWRENDER static patch_t *R_CreateHardwarePatch(patch_t *patch) { - GLPatch_t *grPatch = Z_Calloc(sizeof(GLPatch_t), PU_HWRPATCHINFO, NULL); - grPatch->mipmap = Z_Calloc(sizeof(GLMipmap_t), PU_HWRPATCHINFO, NULL); - grPatch->rawpatch = patch; - HWR_MakePatch(patch, grPatch, grPatch->mipmap, false); - return (patch_t *)grPatch; + GLPatch_t *glPatch = Z_Calloc(sizeof(GLPatch_t), PU_HWRPATCHINFO, NULL); + glPatch->mipmap = Z_Calloc(sizeof(GLMipmap_t), PU_HWRPATCHINFO, NULL); + glPatch->rawpatch = patch; + HWR_MakePatch(patch, glPatch, glPatch->mipmap, false); + return (patch_t *)glPatch; } #endif @@ -803,6 +805,14 @@ INT32 R_GetRollAngle(angle_t rollangle) return ra; } +angle_t R_RotationAngle(angle_t ang, angle_t camang, interpmobjstate_t *interp) +{ + return FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), interp->roll) + + FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), interp->pitch) + + FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), interp->sloperoll) + + FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), interp->slopepitch); +} + patch_t *Patch_GetRotatedSprite(spriteframe_t *sprite, size_t frame, size_t spriteangle, boolean flip, boolean adjustfeet, void *info, INT32 rotationangle) { rotsprite_t *rotsprite; @@ -842,8 +852,8 @@ patch_t *Patch_GetRotatedSprite(spriteframe_t *sprite, size_t frame, size_t spri } else { - xpivot = patch->leftoffset; - ypivot = patch->height / 2; + xpivot = SHORT(patch->leftoffset); + ypivot = SHORT(patch->height) / 2; } RotatedPatch_DoRotation(rotsprite, patch, rotationangle, xpivot, ypivot, flip); @@ -902,9 +912,9 @@ void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle size_t size; INT32 bflip = (flip != 0x00); - INT32 width = patch->width; - INT32 height = patch->height; - INT32 leftoffset = patch->leftoffset; + INT32 width = SHORT(patch->width); + INT32 height = SHORT(patch->height); + INT32 leftoffset = SHORT(patch->leftoffset); INT32 newwidth, newheight; fixed_t ca = rollcosang[angle]; @@ -975,7 +985,7 @@ void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle } ox = (newwidth / 2) + (leftoffset - xpivot); - oy = (newheight / 2) + (patch->topoffset - ypivot); + oy = (newheight / 2) + (SHORT(patch->topoffset) - ypivot); width = (maxx - minx); height = (maxy - miny); diff --git a/src/r_patch.h b/src/r_patch.h index ac8072a43..5edaa46fb 100644 --- a/src/r_patch.h +++ b/src/r_patch.h @@ -15,6 +15,7 @@ #define __R_PATCH__ #include "r_defs.h" +#include "r_fps.h" #include "doomdef.h" // Structs @@ -53,6 +54,8 @@ void R_ParseSPRTINFOLump(UINT16 wadNum, UINT16 lumpNum); // Sprite rotation #ifdef ROTSPRITE INT32 R_GetRollAngle(angle_t rollangle); +angle_t R_RotationAngle(angle_t ang, angle_t camang, interpmobjstate_t *interp); + patch_t *Patch_GetRotatedSprite( spriteframe_t *sprite, size_t frame, size_t spriteangle, diff --git a/src/r_plane.c b/src/r_plane.c index 208478440..d8d77457f 100644 --- a/src/r_plane.c +++ b/src/r_plane.c @@ -28,6 +28,7 @@ #include "z_zone.h" #include "p_tick.h" #include "r_fps.h" +#include "r_portal.h" // // opening @@ -39,12 +40,6 @@ // good night sweet prince //#define SHITPLANESPARENCY -//SoM: 3/23/2000: Use Boom visplane hashing. -#define VISPLANEHASHBITS 9 -#define VISPLANEHASHMASK ((1<start; + INT32 end = portal->end; + INT16 *ceil = portal->ceilingclip; + INT16 *floor = portal->floorclip; + fixed_t *scale = portal->frontscale; + + INT32 i; + for (i = 0; i < end-start; i++) + { + *ceil = ceilingclip[start+i]; + ceil++; + *floor = floorclip[start+i]; + floor++; + *scale = frontscale[start+i]; + scale++; + } +} + + +/** Apply the clipping window from a portal. + */ +void Portal_ClipApply (const portal_t* portal) +{ + INT32 i; + INT32 start = portal->start; + INT32 end = portal->end; + INT16 *ceil = portal->ceilingclip; + INT16 *floor = portal->floorclip; + fixed_t *scale = portal->frontscale; + + for (i = 0; i < end-start; i++) + { + ceilingclip[start+i] = *ceil; + ceil++; + floorclip[start+i] = *floor; + floor++; + frontscale[start+i] = *scale; + scale++; + } + + // HACKS FOLLOW + for (i = 0; i < start; i++) + { + floorclip[i] = -1; + ceilingclip[i] = (INT16)viewheight; + } + for (i = end; i < vid.width; i++) + { + floorclip[i] = -1; + ceilingclip[i] = (INT16)viewheight; + } +} + +static portal_t* Portal_Add (const INT16 x1, const INT16 x2) +{ + portal_t *portal = Z_Malloc(sizeof(portal_t), PU_LEVEL, NULL); + INT16 *ceilingclipsave = Z_Malloc(sizeof(INT16)*(x2-x1 + 1), PU_LEVEL, NULL); + INT16 *floorclipsave = Z_Malloc(sizeof(INT16)*(x2-x1 + 1), PU_LEVEL, NULL); + fixed_t *frontscalesave = Z_Malloc(sizeof(fixed_t)*(x2-x1 + 1), PU_LEVEL, NULL); + + // Linked list. + if (!portal_base) + { + portal_base = portal; + portal_cap = portal; + } + else + { + portal_cap->next = portal; + portal_cap = portal; + } + portal->next = NULL; + + // Store clipping values so they can be restored once the portal is rendered. + portal->ceilingclip = ceilingclipsave; + portal->floorclip = floorclipsave; + portal->frontscale = frontscalesave; + portal->start = x1; + portal->end = x2; + + // Increase recursion level. + portal->pass = portalrender+1; + + return portal; +} + +void Portal_Remove (portal_t* portal) +{ + portalcullsector = NULL; + portal_base = portal->next; + Z_Free(portal->ceilingclip); + Z_Free(portal->floorclip); + Z_Free(portal->frontscale); + Z_Free(portal); +} + +/** Creates a portal out of two lines and a determined screen range. + * + * line1 determines the entrance, and line2 the exit. + * x1 and x2 determine the screen's column bounds. + + * The view's offset from the entry line center is obtained, + * and then rotated&translated to the exit line's center. + * When the portal renders, it will create the illusion of + * the two lines being seamed together. + */ +void Portal_Add2Lines (const INT32 line1, const INT32 line2, const INT32 x1, const INT32 x2) +{ + portal_t* portal = Portal_Add(x1, x2); + + // Offset the portal view by the linedef centers + line_t* start = &lines[line1]; + line_t* dest = &lines[line2]; + + angle_t dangle = R_PointToAngle2(0,0,dest->dx,dest->dy) - R_PointToAngle2(start->dx,start->dy,0,0); + + fixed_t disttopoint; + angle_t angtopoint; + + vertex_t dest_c, start_c; + + // looking glass center + start_c.x = (start->v1->x + start->v2->x) / 2; + start_c.y = (start->v1->y + start->v2->y) / 2; + + // other side center + dest_c.x = (dest->v1->x + dest->v2->x) / 2; + dest_c.y = (dest->v1->y + dest->v2->y) / 2; + + disttopoint = R_PointToDist2(start_c.x, start_c.y, viewx, viewy); + angtopoint = R_PointToAngle2(start_c.x, start_c.y, viewx, viewy); + angtopoint += dangle; + + portal->viewx = dest_c.x + FixedMul(FINECOSINE(angtopoint>>ANGLETOFINESHIFT), disttopoint); + portal->viewy = dest_c.y + FixedMul(FINESINE(angtopoint>>ANGLETOFINESHIFT), disttopoint); + portal->viewz = viewz + dest->frontsector->floorheight - start->frontsector->floorheight; + portal->viewangle = viewangle + dangle; + + portal->clipline = line2; + + Portal_ClipRange(portal); + + g_portal = portal; // this tells R_StoreWallRange that curline is a portal seg +} + + diff --git a/src/r_portal.h b/src/r_portal.h new file mode 100644 index 000000000..c944f46d0 --- /dev/null +++ b/src/r_portal.h @@ -0,0 +1,57 @@ +// SONIC ROBO BLAST 2 +//----------------------------------------------------------------------------- +// Copyright (C) 1993-1996 by id Software, Inc. +// Copyright (C) 1998-2000 by DooM Legacy Team. +// Copyright (C) 1999-2018 by Sonic Team Junior. +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- +/// \file r_portal.h +/// \brief Software renderer portal struct, functions, linked list extern. + +#ifndef __R_PORTAL__ +#define __R_PORTAL__ + +#include "r_data.h" + + +/** Portal structure. + */ +typedef struct portal_s +{ + struct portal_s *next; + + // Viewport. + fixed_t viewx; + fixed_t viewy; + fixed_t viewz; + angle_t viewangle; + + UINT8 pass; /**< Keeps track of the portal's recursion depth. */ + INT32 clipline; /**< Optional clipline for line-based portals. */ + + // Clipping information. + INT32 start; /**< First horizontal pixel coordinate to draw at. */ + INT32 end; /**< Last horizontal pixel coordinate to draw at. */ + INT16 *ceilingclip; /**< Temporary screen top clipping array. */ + INT16 *floorclip; /**< Temporary screen bottom clipping array. */ + fixed_t *frontscale;/**< Temporary screen bottom clipping array. */ +} portal_t; + +extern portal_t* portal_base; +extern portal_t* portal_cap; +extern UINT8 portalrender; + +extern line_t *portalclipline; +extern sector_t *portalcullsector; +extern INT32 portalclipstart, portalclipend; + +void Portal_InitList (void); +void Portal_Remove (portal_t* portal); +void Portal_Add2Lines (const INT32 line1, const INT32 line2, const INT32 x1, const INT32 x2); + +void Portal_ClipApply (const portal_t* portal); + +#endif diff --git a/src/r_segs.c b/src/r_segs.c index 452351aa3..d6f7c9d2a 100644 --- a/src/r_segs.c +++ b/src/r_segs.c @@ -15,6 +15,7 @@ #include "r_local.h" #include "r_sky.h" +#include "r_portal.h" #include "r_splats.h" #include "w_wad.h" @@ -660,13 +661,13 @@ static boolean R_IsFFloorTranslucent(visffloor_t *pfloor) // Renders all the thick sides in the given range. void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) { - size_t pindex; + size_t pindex = 0; column_t * col; - INT32 lightnum; - INT32 texnum; + INT32 lightnum; + INT32 texnum; sector_t tempsec; - INT32 templight; - INT32 i, p; + INT32 templight; + INT32 i, p; fixed_t bottombounds = viewheight << FRACBITS; fixed_t topbounds = (con_clipviewtop - 1) << FRACBITS; fixed_t offsetvalue = 0; @@ -1035,6 +1036,7 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) // Check if the current light effects the colormap/lightlevel rlight = &dc_lightlist[i]; lighteffect = !(dc_lightlist[i].flags & FF_NOSHADE); + if (lighteffect) { lightnum = rlight->lightnum; @@ -1232,7 +1234,6 @@ static void R_RenderSegLoop (void) } } - yh = bottomfrac>>HEIGHTBITS; bottom = floorclip[rw_x]-1; @@ -1243,13 +1244,14 @@ static void R_RenderSegLoop (void) if (markfloor) { top = yh < ceilingclip[rw_x] ? ceilingclip[rw_x] : yh; + if (++top <= bottom && floorplane) { floorplane->top[rw_x] = (INT16)top; floorplane->bottom[rw_x] = (INT16)bottom; } } - + rw_floormarked = false; rw_ceilingmarked = false; @@ -1590,6 +1592,8 @@ static void R_RenderSegLoop (void) topfrac += topstep; bottomfrac += bottomstep; } + + //colfunc = wallcolfunc; } // Uses precalculated seg->length @@ -1852,21 +1856,19 @@ void R_StoreWallRange(INT32 start, INT32 stop) rw_toptextureslide = rw_midtextureslide = rw_bottomtextureslide = 0; ceilingfrontslide = floorfrontslide = ceilingbackslide = floorbackslide = 0; - { - angle_t lineangle = R_PointToAngle2(curline->v1->x, curline->v1->y, curline->v2->x, curline->v2->y); + angle_t lineangle = R_PointToAngle2(curline->v1->x, curline->v1->y, curline->v2->x, curline->v2->y); - if (frontsector->f_slope) - floorfrontslide = FixedMul(frontsector->f_slope->zdelta, FINECOSINE((lineangle-frontsector->f_slope->xydirection)>>ANGLETOFINESHIFT)); + if (frontsector->f_slope) + floorfrontslide = FixedMul(frontsector->f_slope->zdelta, FINECOSINE((lineangle-frontsector->f_slope->xydirection)>>ANGLETOFINESHIFT)); - if (frontsector->c_slope) - ceilingfrontslide = FixedMul(frontsector->c_slope->zdelta, FINECOSINE((lineangle-frontsector->c_slope->xydirection)>>ANGLETOFINESHIFT)); + if (frontsector->c_slope) + ceilingfrontslide = FixedMul(frontsector->c_slope->zdelta, FINECOSINE((lineangle-frontsector->c_slope->xydirection)>>ANGLETOFINESHIFT)); - if (backsector && backsector->f_slope) - floorbackslide = FixedMul(backsector->f_slope->zdelta, FINECOSINE((lineangle-backsector->f_slope->xydirection)>>ANGLETOFINESHIFT)); + if (backsector && backsector->f_slope) + floorbackslide = FixedMul(backsector->f_slope->zdelta, FINECOSINE((lineangle-backsector->f_slope->xydirection)>>ANGLETOFINESHIFT)); - if (backsector && backsector->c_slope) - ceilingbackslide = FixedMul(backsector->c_slope->zdelta, FINECOSINE((lineangle-backsector->c_slope->xydirection)>>ANGLETOFINESHIFT)); - } + if (backsector && backsector->c_slope) + ceilingbackslide = FixedMul(backsector->c_slope->zdelta, FINECOSINE((lineangle-backsector->c_slope->xydirection)>>ANGLETOFINESHIFT)); if (!backsector) { @@ -1935,9 +1937,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) ds_p->sprtopclip = ds_p->sprbottomclip = NULL; ds_p->silhouette = 0; - if ( - worldbottomslope > worldlowslope || - worldbottom > worldlow) + if (worldbottomslope > worldlowslope || worldbottom > worldlow) { ds_p->silhouette = SIL_BOTTOM; if ((backsector->f_slope ? P_GetZAt(backsector->f_slope, viewx, viewy) : backsector->floorheight) > viewz) @@ -1952,9 +1952,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) // ds_p->sprbottomclip = negonearray; } - if ( - worldtopslope < worldhighslope || - worldtop < worldhigh) + if (worldtopslope < worldhighslope || worldtop < worldhigh) { ds_p->silhouette |= SIL_TOP; if ((backsector->c_slope ? P_GetZAt(backsector->c_slope, viewx, viewy) : backsector->ceilingheight) < viewz) @@ -2028,7 +2026,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) || frontsector->extra_colormap != backsector->extra_colormap || (frontsector->ffloors != backsector->ffloors && frontsector->tag != backsector->tag)) { - markceiling = true; + markceiling = true; } else { @@ -2044,9 +2042,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) } // check TOP TEXTURE - if (worldhigh < worldtop - || worldhighslope < worldtopslope - ) + if (worldhigh < worldtop || worldhighslope < worldtopslope) { fixed_t texheight; // top texture @@ -2123,7 +2119,6 @@ void R_StoreWallRange(INT32 start, INT32 stop) // Used for height comparisons and etc across FOFs and slopes fixed_t high1, highslope1, low1, lowslope1, high2, highslope2, low2, lowslope2; - //markceiling = markfloor = true; maskedtexture = true; ds_p->thicksidecol = maskedtexturecol = lastopening - rw_x; diff --git a/src/r_splats.h b/src/r_splats.h index 387b29582..b76ab90b4 100644 --- a/src/r_splats.h +++ b/src/r_splats.h @@ -59,9 +59,6 @@ typedef struct floorsplat_s struct floorsplat_s *nextvis; } floorsplat_t; -// p_setup.c -fixed_t P_SegLength(seg_t *seg); - // call at P_SetupLevel() void R_ClearLevelSplats(void); diff --git a/src/r_state.h b/src/r_state.h index 5234d1d62..b48f0268d 100644 --- a/src/r_state.h +++ b/src/r_state.h @@ -94,10 +94,6 @@ extern boolean viewsky, skyVisible; extern boolean skyVisiblePerPlayer[MAXSPLITSCREENPLAYERS]; // saved values of skyVisible of each splitscreen player extern sector_t *viewsector; extern player_t *viewplayer; -extern UINT8 portalrender; -extern sector_t *portalcullsector; -extern line_t *portalclipline; -extern INT32 portalclipstart, portalclipend; extern consvar_t cv_allowmlook; extern consvar_t cv_maxportals; diff --git a/src/r_things.c b/src/r_things.c index 61fdef8dc..94d108fec 100644 --- a/src/r_things.c +++ b/src/r_things.c @@ -31,6 +31,7 @@ #include "dehacked.h" // get_number (for thok) #include "d_netfil.h" // blargh. for nameonly(). #include "m_cheat.h" // objectplace +#include "r_portal.h" #include "k_kart.h" // SRB2kart #include "p_local.h" // stplyr #ifdef HWRENDER @@ -522,7 +523,7 @@ void R_InitSprites(void) // it can be is do before loading config for skin cvar possible value R_InitSkins(); - for (i = 0; i < numwadfiles; i++) + for (i = 0; i < numwadfiles; i++) { R_AddSkins((UINT16)i, false); R_LoadSpriteInfoLumps(i, wadfiles[i]->numlumps); @@ -732,7 +733,7 @@ static void R_DrawVisSprite(vissprite_t *vis) if (overflow_test < 0) overflow_test = -overflow_test; if ((UINT64)overflow_test&0xFFFFFFFF80000000ULL) return; // ditto } - + // TODO This check should not be necessary. But Papersprites near to the camera will sometimes create invalid values // for the vissprite's startfrac. This happens because they are not depth culled like other sprites. // Someone who is more familiar with papersprites pls check and try to fix <3 @@ -964,7 +965,8 @@ static void R_DrawPrecipitationVisSprite(vissprite_t *vis) // // R_SplitSprite -// runs through a sector's lightlist and +// runs through a sector's lightlist and splits the sprite according to the heights +// static void R_SplitSprite(vissprite_t *sprite, mobj_t *thing) { INT32 i, lightnum, lindex; @@ -1114,8 +1116,6 @@ fixed_t R_GetShadowZ(mobj_t *thing, pslope_t **shadowslope) // static void R_ProjectSprite(mobj_t *thing) { - mobj_t *oldthing = thing; - fixed_t tr_x, tr_y; fixed_t gxt, gyt; fixed_t tx, tz; @@ -1133,24 +1133,23 @@ static void R_ProjectSprite(mobj_t *thing) size_t rot; UINT8 flip; - boolean mirrored = thing->mirrored; - boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); - INT32 lindex; vissprite_t *vis; angle_t ang = 0; // gcc 4.6 and lower fix +#ifdef ROTSPRITE angle_t camang = 0; +#endif fixed_t iscale; fixed_t scalestep; // toast '16 fixed_t offset, offset2; - boolean papersprite = (thing->frame & FF_PAPERSPRITE); fixed_t paperoffset = 0, paperdistance = 0; angle_t centerangle = 0; //SoM: 3/17/2000 fixed_t gz, gzt; INT32 heightsec, phs; + INT32 dist = -1; INT32 light = 0; fixed_t this_scale; fixed_t spritexscale, spriteyscale; @@ -1162,21 +1161,28 @@ static void R_ProjectSprite(mobj_t *thing) #ifdef ROTSPRITE patch_t *rotsprite = NULL; INT32 rollangle = 0; - angle_t rollsum = 0; angle_t pitchnroll = 0; angle_t sliptiderollangle = 0; #endif - - INT32 dist = -1; - if (cv_grmaxinterpdist.value) + if (P_MobjWasRemoved(thing) || thing->subsector == NULL) + return; + + mobj_t *oldthing = thing; + + const boolean mirrored = thing->mirrored; + const boolean vflip = (thing->eflags & MFE_VERTICALFLIP); + const boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); + const boolean papersprite = (thing->frame & FF_PAPERSPRITE); + + if (cv_maxinterpdist.value) dist = R_QuickCamDist(thing->x, thing->y); // uncapped/interpolation interpmobjstate_t interp = {0}; // do interpolation - if (R_UsingFrameInterpolation() && !paused && (!cv_grmaxinterpdist.value || dist < cv_grmaxinterpdist.value)) + if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value)) { R_InterpolateMobjState(oldthing, rendertimefrac, &interp); } @@ -1205,7 +1211,7 @@ static void R_ProjectSprite(mobj_t *thing) tx = -(gyt + gxt); // too far off the side? - if (!papersprite && abs(tx) > tz<<2) // papersprite clipping is handled later + if (!papersprite && abs(tx) > (INT64)tz<<2) // papersprite clipping is handled later return; // aspect ratio stuff @@ -1218,7 +1224,13 @@ static void R_ProjectSprite(mobj_t *thing) I_Error("R_ProjectSprite: invalid sprite number %d ", thing->sprite); #endif - rot = thing->frame&FF_FRAMEMASK; + rot = (thing->frame & FF_FRAMEMASK); + +#ifdef ROTSPRITE + // determine here if sprite should rotate for optimization + const boolean sliprollrotate = (cv_sloperoll.value && cv_sliptideroll.value && (thing->player && thing->player->sliproll)); + const boolean shouldrotate = (cv_sloperoll.value && (interp.roll || interp.pitch || interp.sloperoll || interp.slopepitch || thing->rollangle || sliprollrotate)); +#endif //Fab : 02-08-98: 'skin' override spritedef currently used for skin if ((thing->skin || thing->localskin) && thing->sprite == SPR_PLAY) @@ -1249,7 +1261,7 @@ static void R_ProjectSprite(mobj_t *thing) #ifdef ROTSPRITE sprinfo = &spriteinfo[thing->sprite]; #endif - rot = thing->frame&FF_FRAMEMASK; + rot = (thing->frame & FF_FRAMEMASK); if (!thing->skin) { thing->state->sprite = thing->sprite; @@ -1264,11 +1276,18 @@ static void R_ProjectSprite(mobj_t *thing) I_Error("R_ProjectSprite: sprframes NULL for sprite %d\n", thing->sprite); #endif - if (sprframe->rotate != SRF_SINGLE || papersprite || (cv_sloperoll.value == 2 && cv_spriteroll.value)) + if (sprframe->rotate != SRF_SINGLE || papersprite || +#ifdef ROTSPRITE + (shouldrotate) +#endif + ) { - ang = R_PointToAngle (interp.x, interp.y) - interp.angle; - camang = R_PointToAngle (interp.x, interp.y); - + ang = R_PointToAngle(interp.x, interp.y); +#ifdef ROTSPRITE + camang = ang; +#endif + ang -= interp.angle; + if (mirrored) ang = InvAngle(ang); } @@ -1285,9 +1304,9 @@ static void R_ProjectSprite(mobj_t *thing) // choose a different rotation based on player view //ang = R_PointToAngle (interp.x, interp.y) - interpangle; - if ((ang < ANGLE_180) && (sprframe->rotate & SRF_RIGHT)) // See from right + if ((sprframe->rotate & SRF_RIGHT) && (ang < ANGLE_180)) // See from right rot = 6; // F7 slot - else if ((ang >= ANGLE_180) && (sprframe->rotate & SRF_LEFT)) // See from left + else if ((sprframe->rotate & SRF_LEFT) && (ang >= ANGLE_180)) // See from left rot = 2; // F3 slot else // Normal behaviour rot = (ang+ANGLE_202h)>>29; @@ -1298,7 +1317,7 @@ static void R_ProjectSprite(mobj_t *thing) } I_Assert(lump < max_spritelumps); - + if (thing->localskin && ((skin_t *)thing->localskin)->flags & SF_HIRES) this_scale = FixedMul(this_scale, ((skin_t *)thing->localskin)->highresscale); else if (thing->skin && ((skin_t *)thing->skin)->flags & SF_HIRES) @@ -1310,9 +1329,7 @@ static void R_ProjectSprite(mobj_t *thing) spr_topoffset = spritecachedinfo[lump].topoffset; #ifdef ROTSPRITE - pitchnroll = 0; // set this to 0, non-paper sprites will affect this value - - if (cv_spriteroll.value) + if (shouldrotate) { if (papersprite) { @@ -1330,37 +1347,29 @@ static void R_ProjectSprite(mobj_t *thing) { // this is very messy, but it on-the-fly calculates rotations for all the // pitch and roll variables - pitchnroll = FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), interp.roll) + - FixedMul(FINESINE((ang) >> ANGLETOFINESHIFT), interp.pitch) + - FixedMul(FINECOSINE((camang) >> ANGLETOFINESHIFT), interp.sloperoll) + - FixedMul(FINESINE((camang) >> ANGLETOFINESHIFT), interp.slopepitch); - + pitchnroll = R_RotationAngle(ang, camang, &interp); rollangle = thing->rollangle; } - if (rollangle || pitchnroll || (thing->player && thing->player->sliproll)) + if (rollangle || pitchnroll || sliprollrotate) { - rollsum = pitchnroll; - - if (thing->player) + if (sliprollrotate) { - sliptiderollangle = - cv_sliptideroll.value ? thing->player->sliproll * (thing->player->sliptidemem) : 0; - rollsum += thing->rollangle + - FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), sliptiderollangle); + sliptiderollangle = thing->player->sliproll * thing->player->kartstuff[k_aizdriftstrat]; + pitchnroll += rollangle + FixedMul(FINECOSINE((ang) >> ANGLETOFINESHIFT), sliptiderollangle); } else - rollsum += thing->rollangle; + pitchnroll += rollangle; - rollangle = R_GetRollAngle(rollsum); + rollangle = R_GetRollAngle(pitchnroll); rotsprite = Patch_GetRotatedSprite(sprframe, (thing->frame & FF_FRAMEMASK), rot, flip, false, sprinfo, rollangle); if (rotsprite != NULL) { - spr_width = rotsprite->width << FRACBITS; - spr_height = rotsprite->height << FRACBITS; - spr_offset = rotsprite->leftoffset << FRACBITS; - spr_topoffset = rotsprite->topoffset << FRACBITS; + spr_width = SHORT(rotsprite->width) << FRACBITS; + spr_height = SHORT(rotsprite->height) << FRACBITS; + spr_offset = SHORT(rotsprite->leftoffset) << FRACBITS; + spr_topoffset = SHORT(rotsprite->topoffset) << FRACBITS; spr_topoffset += FEETADJUST; // flip -> rotate, not rotate -> flip @@ -1378,21 +1387,8 @@ static void R_ProjectSprite(mobj_t *thing) if (spritexscale < 1 || spriteyscale < 1) return; - if (thing->renderflags & RF_ABSOLUTEOFFSETS) - { - spr_offset = interp.spritexoffset; - spr_topoffset = interp.spriteyoffset; - } - else - { - SINT8 flipoffset = 1; - - if ((thing->renderflags & RF_FLIPOFFSETS) && flip) - flipoffset = -1; - - spr_offset += interp.spritexoffset * flipoffset; - spr_topoffset += interp.spriteyoffset * flipoffset; - } + spr_offset += interp.spritexoffset; + spr_topoffset += interp.spriteyoffset; if (flip) offset = spr_offset - spr_width; @@ -1469,7 +1465,7 @@ static void R_ProjectSprite(mobj_t *thing) tx2 += FixedDiv(tx-tx2, div); tz2 = FixedMul(MINZ, this_scale); } - + if ((tx2 / 4) < -(FixedMul(tz2, fovtan)) || (tx / 4) > FixedMul(tz, fovtan)) // too far off the side? return; @@ -1497,7 +1493,7 @@ static void R_ProjectSprite(mobj_t *thing) return; range++; // fencepost problem - + if (range > 32767) { // If the range happens to be too large for fixed_t, @@ -1548,7 +1544,7 @@ static void R_ProjectSprite(mobj_t *thing) } //SoM: 3/17/2000: Disregard sprites that are out of view.. - if (thing->eflags & MFE_VERTICALFLIP) + if (vflip) { // When vertical flipped, draw sprites from the top down, at least as far as offsets are concerned. // sprite height - sprite topoffset is the proper inverse of the vertical offset, of course. @@ -1612,7 +1608,6 @@ static void R_ProjectSprite(mobj_t *thing) // store information in a vissprite vis = R_NewVisSprite(); - vis->renderflags = thing->renderflags; vis->heightsec = heightsec; //SoM: 3/17/2000 vis->mobjflags = thing->flags; vis->scale = yscale; //<patch = rotsprite; else #endif @@ -1715,10 +1710,7 @@ static void R_ProjectSprite(mobj_t *thing) vis->precip = false; - if (thing->eflags & MFE_VERTICALFLIP) - vis->vflip = true; - else - vis->vflip = false; + vis->vflip = vflip; vis->isScaled = false; @@ -1752,7 +1744,10 @@ static void R_ProjectPrecipitationSprite(precipmobj_t *thing) INT32 dist = 1; - if (cv_grmaxinterpdist.value) + if (!thing || thing->subsector == NULL) + return; + + if (cv_maxinterpdist.value) dist = R_QuickCamDist(thing->x, thing->y); // uncapped/interpolation @@ -1765,7 +1760,7 @@ static void R_ProjectPrecipitationSprite(precipmobj_t *thing) } // do interpolation - if (R_UsingFrameInterpolation() && !paused && (!cv_grmaxinterpdist.value || dist < cv_grmaxinterpdist.value)) + if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value)) { R_InterpolatePrecipMobjState(thing, rendertimefrac, &interp); } @@ -1954,6 +1949,7 @@ void R_AddSprites(sector_t *sec, INT32 lightlevel) // Handle all things in sector. // If a limit exists, handle things a tiny bit different. const fixed_t limit_dist = (fixed_t)(cv_drawdist.value) * mapobjectscale; + for (thing = sec->thinglist; thing; thing = thing->snext) { if (!R_ThingWithinDist(thing, limit_dist)) @@ -1973,7 +1969,8 @@ void R_AddSprites(sector_t *sec, INT32 lightlevel) // void R_AddPrecipitationSprites(void) { - fixed_t drawdist = (fixed_t)(cv_drawdist_precip.value) * (cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT); + fixed_t precipscale = (cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT); + fixed_t drawdist = ((fixed_t)(cv_drawdist_precip.value) * precipscale); INT32 xl, xh, yl, yh, bx, by; precipmobj_t *th, *next; @@ -2383,7 +2380,7 @@ static drawnode_t *R_CreateDrawNode(drawnode_t *link) node->thickseg = NULL; node->ffloor = NULL; node->sprite = NULL; - + ps_numdrawnodes.value.i++; return node; } @@ -2660,7 +2657,7 @@ static void R_ClipVisSprite(vissprite_t *spr, INT32 x1, INT32 x2) if (spr->cliptop[x] == -2) spr->cliptop[x] = -1; } - + // Check if it'll be visible // Not done for floorsprites. if (cv_spriteclip.value) @@ -2735,7 +2732,7 @@ void R_ClipSprites(void) for (; clippedvissprites < visspritecount; clippedvissprites++) { vissprite_t *spr = R_GetVisSprite(clippedvissprites); - + if (cv_spriteclip.value && (spr->szt > vid.height || spr->sz < 0)) { @@ -2760,7 +2757,7 @@ void R_ClipSprites(void) } R_ClipVisSprite(spr, spr->x1, spr->x2); - + if ((spr->cut & SC_NOTVISIBLE) == 0) numvisiblesprites++; } @@ -2772,15 +2769,15 @@ boolean R_ThingVisible (mobj_t *thing) if (thing->sprite == SPR_NULL || thing->flags2 & MF2_DONTDRAW) return false; - if (viewmobj && (thing == viewmobj)) + if (!P_MobjWasRemoved(viewmobj) && (thing == viewmobj)) return false; if (splitscreen) { - if ((viewssnum == 0 && (thing->renderflags & MFE_DRAWONLYFORP1)) - || (viewssnum == 1 && (thing->renderflags & MFE_DRAWONLYFORP2)) - || (viewssnum == 2 && (thing->renderflags & MFE_DRAWONLYFORP2)) - || (viewssnum == 3 && (thing->renderflags & MFE_DRAWONLYFORP4))) + if ((viewssnum == 0 && (thing->eflags & MFE_DRAWONLYFORP1)) + || (viewssnum == 1 && (thing->eflags & MFE_DRAWONLYFORP2)) + || (viewssnum == 2 && (thing->eflags & MFE_DRAWONLYFORP2)) + || (viewssnum == 3 && (thing->eflags & MFE_DRAWONLYFORP4))) return true; } @@ -3287,7 +3284,7 @@ static int skinSortFunc(const void *a, const void *b) //tbh i have no clue what void sortSkinGrid(void) { //CONS_Printf("Sorting skin list (%d)...\n", cv_skinselectgridsort.value); - qs22j(skinsorted, numskins, sizeof(UINT8), skinSortFunc); + qs22j(skinsorted, numskins, sizeof(UINT8), skinSortFunc); } // @@ -3313,12 +3310,12 @@ void R_AddSkins(UINT16 wadnum, boolean local) // advance by default lastlump = lump + 1; - if (numskins >= MAXSKINS) + if (!local && numskins >= MAXSKINS) { CONS_Alert(CONS_WARNING, M_GetText("Unable to add skin, too many characters are loaded (%d maximum)\n"), MAXSKINS); continue; // so we know how many skins couldn't be added } - if (numlocalskins >= MAXLOCALSKINS) + if (local && numlocalskins >= MAXLOCALSKINS) { CONS_Alert(CONS_WARNING, M_GetText("Unable to add localskin, too many localskins are loaded (%d maximum)\n"), MAXLOCALSKINS); continue; // so we know how many skins couldn't be added @@ -3571,7 +3568,7 @@ next_token: Forceskin_cons_t[numskins+1].value = numskins; Forceskin_cons_t[numskins+1].strvalue = skins[numskins].name; } - + skin->localskin = local; // so we dont have to guess @@ -3598,7 +3595,7 @@ next_token: CONS_Debug(DBG_SETUP, M_GetText("Incremented %d, %d to %d\n"), skin->kartspeed, skin->kartweight, skinstatscount[skin->kartspeed - 1][skin->kartweight - 1]); skinsorted[numskins] = numskins; } - + allskins[numallskins] = ( (local) ? localskins : skins )[( (local) ? numlocalskins : numskins )]; local ? numlocalskins++ : numskins++; diff --git a/src/s_sound.c b/src/s_sound.c index 868bccc77..c770957b6 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -656,12 +656,6 @@ void S_StartSound(const void *origin, sfxenum_t sfx_id) { switch (sfx_id) { -// case sfx_altow1: -// case sfx_altow2: -// case sfx_altow3: -// case sfx_altow4: -// sfx_id = sfx_mario8; -// break; case sfx_thok: sfx_id = sfx_mario7; break; @@ -677,15 +671,6 @@ void S_StartSound(const void *origin, sfxenum_t sfx_id) case sfx_itemup: sfx_id = sfx_mario4; break; -// case sfx_tink: -// sfx_id = sfx_mario1; -// break; -// case sfx_cgot: -// sfx_id = sfx_mario9; -// break; -// case sfx_lose: -// sfx_id = sfx_mario2; -// break; default: break; } @@ -1046,7 +1031,7 @@ boolean S_AdjustSoundParams(const mobj_t *listener, const mobj_t *source, INT32 INT64 x, y, yl, yh, xl, xh; fixed_t newdist; - if (R_PointInSubsector(listensource.x, listensource.y)->sector->ceilingpic == skyflatnum) + if (R_PointInSubsectorFast(listensource.x, listensource.y)->sector->ceilingpic == skyflatnum) approx_dist = 0; else { @@ -1059,7 +1044,7 @@ boolean S_AdjustSoundParams(const mobj_t *listener, const mobj_t *source, INT32 for (y = yl; y <= yh; y += FRACUNIT*64) for (x = xl; x <= xh; x += FRACUNIT*64) { - if (R_PointInSubsector(x, y)->sector->ceilingpic == skyflatnum) + if (R_PointInSubsectorFast(x, y)->sector->ceilingpic == skyflatnum) { // Found the outdoors! newdist = S_CalculateSoundDistance(listensource.x, listensource.y, 0, x, y, 0); @@ -1317,175 +1302,191 @@ static UINT32 queue_fadeinms; musicdef_t *musicdefstart = NULL; // First music definition struct cursongcredit cursongcredit; // Currently displayed song credit info -// -// search for music definition in wad -// -static UINT16 W_CheckForMusicDefInPwad(UINT16 wadid) +static boolean +ReadMusicDefFields (UINT16 wadnum, int line, char *stoken, musicdef_t **defp) { - UINT16 i; - lumpinfo_t *lump_p; + musicdef_t *def; - lump_p = wadfiles[wadid]->lumpinfo; - for (i = 0; i < wadfiles[wadid]->numlumps; i++, lump_p++) - if (memcmp(lump_p->name, "MUSICDEF", 8) == 0) - return i; - - return INT16_MAX; // not found -} - -void S_LoadMusicDefs(UINT16 wadnum) -{ - UINT16 lump; - char *buf; - char *buf2; - char *stoken; char *value; - size_t size; - musicdef_t *def, *prev; - UINT16 line = 1; // for better error msgs + char *textline; - lump = W_CheckForMusicDefInPwad(wadnum); - if (lump == INT16_MAX) - return; - - buf = W_CacheLumpNumPwad(wadnum, lump, PU_CACHE); - size = W_LumpLengthPwad(wadnum, lump); - - // for strtok - buf2 = malloc(size+1); - if (!buf2) - I_Error("S_LoadMusicDefs: No more free memory\n"); - M_Memcpy(buf2,buf,size); - buf2[size] = '\0'; - - def = prev = NULL; - - stoken = strtok (buf2, "\r\n "); - // Find music def - while (stoken) + if (!stricmp(stoken, "lump")) { - if (!stricmp(stoken, "lump")) + value = strtok(NULL, " "); + if (!value) { - value = strtok(NULL, "\r\n "); - - if (!value) - { - CONS_Alert(CONS_WARNING, "MUSICDEF: Lump '%s' is missing name. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - stoken = strtok(NULL, "\r\n"); // skip end of line - goto skip_lump; - } - - // No existing musicdefs - if (!musicdefstart) - { - musicdefstart = Z_Calloc(sizeof (musicdef_t), PU_STATIC, NULL); - STRBUFCPY(musicdefstart->name, value); - strlwr(musicdefstart->name); - def = musicdefstart; - //CONS_Printf("S_LoadMusicDefs: Initialized musicdef w/ song '%s'\n", def->name); - } - else - { - def = musicdefstart; - - // Search if this is a replacement - //CONS_Printf("S_LoadMusicDefs: Searching for song replacement...\n"); - while (def) - { - if (!stricmp(def->name, value)) - { - //CONS_Printf("S_LoadMusicDefs: Found song replacement '%s'\n", def->name); - break; - } - - prev = def; - def = def->next; - } - - // Nothing found, add to the end. - if (!def) - { - def = Z_Calloc(sizeof (musicdef_t), PU_STATIC, NULL); - STRBUFCPY(def->name, value); - strlwr(def->name); - if (prev != NULL) - prev->next = def; - //CONS_Printf("S_LoadMusicDefs: Added song '%s'\n", def->name); - } - } - - strncpy(def->filename, wadfiles[wadnum]->filename, 256); - def->filename[256] = '\0'; - -skip_lump: - stoken = strtok(NULL, "\r\n "); - line++; + CONS_Alert(CONS_WARNING, + "MUSICDEF: Field '%s' is missing name. (file %s, line %d)\n", + stoken, wadfiles[wadnum]->filename, line); + return false; } else { - value = strtok(NULL, "\r\n= "); + def = S_FindMusicCredit(value); - if (!value) + // Nothing found, add to the end. + if (!def) { - CONS_Alert(CONS_WARNING, "MUSICDEF: Field '%s' is missing value. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - stoken = strtok(NULL, "\r\n"); // skip end of line - goto skip_field; + def = Z_Calloc(sizeof (musicdef_t), PU_STATIC, NULL); + + STRBUFCPY(def->name, value); + strlwr(def->name); + def->hash = quickncasehash (def->name, 6); + + def->next = musicdefstart; + musicdefstart = def; } + (*defp) = def; + } + } + else + { + value = strtok(NULL, ""); + + if (value) + { + // Find the equals sign. + value = strchr(value, '='); + } + + if (!value) + { + CONS_Alert(CONS_WARNING, + "MUSICDEF: Field '%s' is missing value. (file %s, line %d)\n", + stoken, wadfiles[wadnum]->filename, line); + return false; + } + else + { + def = (*defp); + if (!def) { - CONS_Alert(CONS_ERROR, "MUSICDEF: No music definition before field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - free(buf2); - return; + CONS_Alert(CONS_ERROR, + "MUSICDEF: No music definition before field '%s'. (file %s, line %d)\n", + stoken, wadfiles[wadnum]->filename, line); + return false; } - + + // Skip the equals sign. + value++; + + // Now skip funny whitespace. + value += strspn(value, "\t "); + + textline = value; + +// turn _ into spaces. +#define ADDDEF(field)\ + STRBUFCPY(def->field, textline);\ + for (textline = def->field; *textline; textline++)\ + if (*textline == '_') *textline = ' '; + if (!stricmp(stoken, "usage")) { - STRBUFCPY(def->usage, value); - for (value = def->usage; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set usage to '%s'\n", def->usage); + ADDDEF(usage); } else if (!stricmp(stoken, "source")) { - STRBUFCPY(def->source, value); - for (value = def->source; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + ADDDEF(source); } else if (!stricmp(stoken, "title")) { def->use_info = true; - STRBUFCPY(def->title, value); - for (value = def->title; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + ADDDEF(title); } else if (!stricmp(stoken, "alttitle")) { - STRBUFCPY(def->alttitle, value); - for (value = def->alttitle; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + ADDDEF(alttitle); } else if (!stricmp(stoken, "authors")) { - STRBUFCPY(def->authors, value); - for (value = def->authors; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); + ADDDEF(authors); } else CONS_Alert(CONS_WARNING, "MUSICDEF: Invalid field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - -skip_field: - stoken = strtok(NULL, "\r\n= "); - line++; +#undef ADDDEF } } - free(buf2); - return; + return true; +} + +void S_LoadMusicDefs(UINT16 wadnum) +{ + UINT16 lumpnum; + char *lump; + char *musdeftext; + size_t size; + + char *lf; + char *stoken; + + size_t nlf; + size_t ncr; + + musicdef_t *def = NULL; + int line = 1; // for better error msgs + + for (int k = 0; k < 2; k++) + { + lumpnum = W_CheckNumForNamePwad((k == 1 ? "MUSCINFO" : "MUSICDEF") , wadnum, 0); //check for MUSCINFO lump on 2nd iteration + + if (lumpnum == INT16_MAX) + continue; + + lump = W_CacheLumpNumPwad(wadnum, lumpnum, PU_CACHE); + size = W_LumpLengthPwad(wadnum, lumpnum); + + // Null-terminated MUSICDEF lump. + musdeftext = malloc(size+1); + if (!musdeftext) + I_Error("S_LoadMusicDefs: No more free memory for the parser\n"); + M_Memcpy(musdeftext, lump, size); + musdeftext[size] = '\0'; + + // Find music def + stoken = musdeftext; + for (;;) + { + lf = strpbrk(stoken, "\r\n"); + if (lf) + { + if (*lf == '\n') + nlf = 1; + else + nlf = 0; + *lf++ = '\0';/* now we can delimit to here */ + } + + stoken = strtok(stoken, " "); + if (stoken) + { + if (! ReadMusicDefFields(wadnum, line, stoken, &def)) + break; + } + + if (lf) + { + do + { + line += nlf; + ncr = strspn(lf, "\r");/* skip CR */ + lf += ncr; + nlf = strspn(lf, "\n"); + lf += nlf; + } + while (nlf || ncr) ; + + stoken = lf;/* now the next nonempty line */ + } + else + break;/* EOF */ + } + + free(musdeftext); + } } // @@ -1500,164 +1501,6 @@ void S_InitMusicDefs(void) S_LoadMusicDefs(i); } -// -// search for music definition in wad -// -static UINT16 W_CheckForMusicInfoInPwad(UINT16 wadid) -{ - UINT16 i; - lumpinfo_t *lump_p; - - lump_p = wadfiles[wadid]->lumpinfo; - for (i = 0; i < wadfiles[wadid]->numlumps; i++, lump_p++) - if (memcmp(lump_p->name, "MUSCINFO", 8) == 0) - return i; - - return INT16_MAX; // not found -} - -void S_LoadMTDefs(UINT16 wadnum) -{ - UINT16 lump; - char *buf; - char *buf2; - char *stoken; - char *value; - size_t size; - musicdef_t *def, *prev; - UINT16 line = 1; // for better error msgs - - lump = W_CheckForMusicInfoInPwad(wadnum); - if (lump == INT16_MAX) - return; - - buf = W_CacheLumpNumPwad(wadnum, lump, PU_CACHE); - size = W_LumpLengthPwad(wadnum, lump); - - // for strtok - buf2 = malloc(size+1); - if (!buf2) - I_Error("S_LoadMTDefs: No more free memory\n"); - M_Memcpy(buf2,buf,size); - buf2[size] = '\0'; - - def = prev = NULL; - - stoken = strtok (buf2, "\r\n "); - // Find music def - while (stoken) - { - if (!stricmp(stoken, "lump")) - { - value = strtok(NULL, "\r\n "); - - if (!value) - { - CONS_Alert(CONS_WARNING, "MUSICDEF: Lump '%s' is missing name. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - stoken = strtok(NULL, "\r\n"); // skip end of line - goto skip_lump; - } - - // No existing musicdefs - if (!musicdefstart) - { - musicdefstart = Z_Calloc(sizeof (musicdef_t), PU_STATIC, NULL); - STRBUFCPY(musicdefstart->name, value); - strlwr(musicdefstart->name); - def = musicdefstart; - //CONS_Printf("S_LoadMusicDefs: Initialized musicdef w/ song '%s'\n", def->name); - } - else - { - def = musicdefstart; - - // Search if this is a replacement - //CONS_Printf("S_LoadMusicDefs: Searching for song replacement...\n"); - while (def) - { - if (!stricmp(def->name, value)) - { - //CONS_Printf("S_LoadMusicDefs: Found song replacement '%s'\n", def->name); - break; - } - - prev = def; - def = def->next; - } - - // Nothing found, abort. - if (!def) - { - CONS_Alert(CONS_WARNING, "MUSCINFO: Music def for '%s' does not exist. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - free(buf2); - return; - } - } - -skip_lump: - stoken = strtok(NULL, "\r\n "); - line++; - } - else - { - value = strtok(NULL, "\r\n= "); - - if (!value) - { - CONS_Alert(CONS_WARNING, "MUSCINFO: Field '%s' is missing value. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - stoken = strtok(NULL, "\r\n"); // skip end of line - goto skip_field; - } - - if (!def) - { - CONS_Alert(CONS_ERROR, "MUSCINFO: No music definition before field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - free(buf2); - return; - } - - if (!stricmp(stoken, "title")) - { - def->use_info = true; - STRBUFCPY(def->title, value); - for (value = def->title; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); - } - else if (!stricmp(stoken, "alttitle")) - { - STRBUFCPY(def->alttitle, value); - for (value = def->alttitle; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); - } - else if (!stricmp(stoken, "authors")) - { - STRBUFCPY(def->authors, value); - for (value = def->authors; *value; value++) - if (*value == '_') *value = ' '; // turn _ into spaces. - //CONS_Printf("S_LoadMusicDefs: Set source to '%s'\n", def->source); - } - else - CONS_Alert(CONS_WARNING, "MUSCINFO: Invalid field '%s'. (file %s, line %d)\n", stoken, wadfiles[wadnum]->filename, line); - -skip_field: - stoken = strtok(NULL, "\r\n= "); - line++; - } - } - - free(buf2); - return; -} - -void S_InitMTDefs(void) -{ - UINT16 i; - for (i = 0; i < numwadfiles; i++) - S_LoadMTDefs(i); -} - // // S_FindMusicCredit // @@ -1665,19 +1508,17 @@ void S_InitMTDefs(void) // musicdef_t *S_FindMusicCredit(const char *musname) { - musicdef_t *def = musicdefstart; + UINT32 hash = quickncasehash (musname, 6); + musicdef_t *def; - if (!def) // No definitions - return NULL; - - while (def) + for (def = musicdefstart; def; def = def->next) { - if (!stricmp(def->name, musname)) - { - return def; - } - else - def = def->next; + if (hash != def->hash) + continue; + if (stricmp(def->name, musname)) + continue; + + return def; } return NULL; @@ -1966,6 +1807,15 @@ void S_ChangeMusicEx(const char *mmusic, UINT16 mflags, boolean looping, UINT32 { char newmusic[7] = {0}; + struct MusicChange hook_param = { + newmusic, + &mflags, + &looping, + &position, + &prefadems, + &fadeinms + }; + if (S_MusicDisabled() || demo.rewinding // Don't mess with music while rewinding! || demo.title) // SRB2Kart: Demos don't interrupt title screen music @@ -1975,7 +1825,7 @@ void S_ChangeMusicEx(const char *mmusic, UINT16 mflags, boolean looping, UINT32 S_CheckEventMus(newmusic); - if (LUAh_MusicChange(music_name, newmusic, &mflags, &looping, &position, &prefadems, &fadeinms)) + if (LUA_HookMusicChange(music_name, &hook_param)) return; // No Music (empty string) @@ -2048,10 +1898,7 @@ void S_StopMusic(void) || demo.title) // SRB2Kart: Demos don't interrupt title screen music return; - if (cv_birdmusic.value && (strcasecmp(music_name, mapmusname) == 0)) - mapmusresume = I_GetSongPosition(); - else - mapmusresume = 0; + mapmusresume = (cv_birdmusic.value && (strcasecmp(music_name, mapmusname) == 0)) ? I_GetSongPosition() : 0; if (I_SongPaused()) I_ResumeSong(); @@ -2186,18 +2033,21 @@ boolean S_FadeOutStopMusic(UINT32 ms) return false; }*/ -static INT16 oldmap = 0; -static boolean oldencore = false; static boolean skipmusic = false; boolean skipintromus = false; -static const char *musicexception_list[16] = { +static const char *musicexception_list[17] = { "vote", "voteea", "voteeb", "racent", "krwin", "krok", "krlose", "krfail", "kbwin", "kbok", - "kblose", "kstart", "estart", "wait2j", "CHRSHP", - "CHRSHF" + "kblose", "kstart", "estart", "wait2j", "titles", + "CHRSHF", "CHRSHP" // no clue what those are tbh }; +void S_ResetKeepAndSpecialMus(void) +{ + keepmusic = skipintromus = false; +} + //checks for any kind of event music like intermission, vote etc. //always runs when musicchange gets invoked static void S_CheckEventMus(const char *newmus) @@ -2207,22 +2057,25 @@ static void S_CheckEventMus(const char *newmus) if (!cv_keepmusic.value) return; - for (int i = 0; i < 16; i++) + for (int i = 0; i < 17; i++) if (stricmp(music_name, musicexception_list[i]) == 0 || stricmp(newmus, musicexception_list[i]) == 0) // weird? sure! but were lucky enough newmus reflects whats being replaced { skipmusic = true; break; } - //CONS_Printf("musname = %s\n", music_name); + //CONS_Printf("music_name = %s\n", music_name); //CONS_Printf("newmus = %s\n", newmus); - //CONS_Printf("newmus = %d\n", skipmusic); + //CONS_Printf("skipmusic = %d\n", skipmusic); } //this one compares map and encoremode instead of the music itself //makes tunes work and stuff void S_CheckMap(void) { + static INT16 oldmap = 0; + static boolean oldencore = false; + if (!cv_keepmusic.value) { keepmusic = false; @@ -2231,6 +2084,8 @@ void S_CheckMap(void) keepmusic = (!skipmusic && gamestate == GS_LEVEL && oldmap == gamemap && oldencore == encoremode); + //CONS_Printf("keepmusic = %s\n", keepmusic); + oldencore = encoremode; oldmap = gamemap; } @@ -2242,15 +2097,7 @@ void S_CheckMap(void) // void S_InitMapMusic(void) { - if (!cv_skipintromusic.value) - skipintromus = false; - else - { - char *maptitle = G_BuildMapTitle(gamemap); - skipintromus = cv_skipintromusic.value && stricmp(maptitle, "Wandering Falls") != 0; // thanks diggle! - if (maptitle) - Z_Free(maptitle); - } + skipintromus = false; if (mapmusflags & MUSIC_RELOADRESET) { @@ -2268,6 +2115,15 @@ void S_InitMapMusic(void) // lug: but not when we keep the map music lol S_StopMusic(); + if (cv_skipintromusic.value) + { + char *maptitle = G_BuildMapTitle(gamemap); + // for some reason, occasionally the title screen music doesent seem to be reset in time, so skipping the intro may make it just continue playing it instead, weird.. + skipintromus = (stricmp(music_name, "titles") != 0) && (maptitle && (stricmp(maptitle, "Wandering Falls") != 0)); // thanks diggle! + if (maptitle) + Z_Free(maptitle); + } + if (skipintromus) return; @@ -2276,13 +2132,13 @@ void S_InitMapMusic(void) //S_ChangeMusicEx((encoremode ? "estart" : "kstart"), 0, false, mapmusposition, 0, 0); } -void S_StartMapMusic(boolean restore) +void S_StartMapMusic(void) { //no need to constantly run this after race has started if (leveltime > MUSICSTARTTIME) return; - if (keepmusic && !restore) // make sure this doesent kill the music when its called from P_RestoreMusic in some cases + if (keepmusic) return; if (skipintromus) @@ -2317,6 +2173,8 @@ void S_RestartMusic(void) S_SetMusicVolume(cv_digmusicvolume.value, cv_midimusicvolume.value); #endif + S_ResetKeepAndSpecialMus(); + if (Playing()) // Gotta make sure the player is in a level P_RestoreMusic(&players[consoleplayer]); else @@ -2421,6 +2279,8 @@ static void Command_RestartAudio_f(void) S_StartSound(NULL, sfx_strpst); + S_ResetKeepAndSpecialMus(); + if (Playing()) // Gotta make sure the player is in a level P_RestoreMusic(&players[consoleplayer]); else @@ -2498,6 +2358,8 @@ static void GameDigiMusic_OnChange(void) I_StartupSound(); // will return early if initialised I_InitMusic(); + S_ResetKeepAndSpecialMus(); + if (Playing()) P_RestoreMusic(&players[consoleplayer]); else @@ -2583,6 +2445,9 @@ static void GameMIDIMusic_OnChange(void) { midi_disabled = false; I_InitMusic(); + + S_ResetKeepAndSpecialMus(); + if (Playing()) P_RestoreMusic(&players[consoleplayer]); else diff --git a/src/s_sound.h b/src/s_sound.h index 887cdd878..be4ed381d 100644 --- a/src/s_sound.h +++ b/src/s_sound.h @@ -109,8 +109,10 @@ void S_InitSfxChannels(INT32 sfxVolume); void S_StopSounds(void); void S_ClearSfx(void); +void S_ResetKeepAndSpecialMus(void); + void S_InitMapMusic(void); -void S_StartMapMusic(boolean restore); +void S_StartMapMusic(void); void S_CheckMap(void); @@ -168,6 +170,7 @@ boolean S_SpeedMusic(float speed); typedef struct musicdef_s { char name[7]; + UINT32 hash; char usage[256]; char source[256]; char filename[256+1]; @@ -228,6 +231,16 @@ UINT32 S_GetMusicPosition(void); // Music Playback // +/* this is for the sake of the hook */ +struct MusicChange { + char * newname; + UINT16 * mflags; + boolean * looping; + UINT32 * position; + UINT32 * prefadems; + UINT32 * fadeinms; +}; + // Start music track, arbitrary, given its name, and set whether looping // note: music flags 12 bits for tracknum (gme, other formats with more than one track) // 13-15 aren't used yet diff --git a/src/screen.c b/src/screen.c index 22ce5e8f1..249c7225c 100644 --- a/src/screen.c +++ b/src/screen.c @@ -82,7 +82,8 @@ static void SCR_ChangeFullscreen (void); consvar_t cv_fullscreen = {"fullscreen", "Yes", CV_SAVE|CV_CALL, CV_YesNo, SCR_ChangeFullscreen, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_accuratefps = {"accuratefpscounter", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t accuratefps_cons_t[] = {{0, "Inaccurate"}, {1, "Accurate"}, {0, NULL}}; +consvar_t cv_accuratefps = {"fpssampling", "1", CV_SAVE, accuratefps_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; // ========================================================================= // SCREEN VARIABLES @@ -272,10 +273,13 @@ void SCR_Recalc(void) vid.fsmalldupy = vid.smalldupy*FRACUNIT; #endif - // toggle off automap because some screensize-dependent values will + // toggle off (then back on) the automap because some screensize-dependent values will // be calculated next time the automap is activated. if (automapactive) - AM_Stop(); + { + am_recalc = true; + AM_Start(); + } // set the screen[x] ptrs on the new vidbuffers V_Init(); @@ -354,11 +358,7 @@ void SCR_ChangeFullscreen(void) boolean SCR_IsAspectCorrect(INT32 width, INT32 height) { - return - ( width % BASEVIDWIDTH == 0 - && height % BASEVIDHEIGHT == 0 - && width / BASEVIDWIDTH == height / BASEVIDHEIGHT - ); + return (width % BASEVIDWIDTH == 0 && height % BASEVIDHEIGHT == 0 && width / BASEVIDWIDTH == height / BASEVIDHEIGHT); } double averageFPS = 0.0f; @@ -411,7 +411,6 @@ void SCR_CalculateFPS(void) if (total_frame_time >= MAX_FRAME_TIME) { static int sampleIndex = 0; - int i; fps_samples[sampleIndex] = frameElapsed; @@ -420,7 +419,7 @@ void SCR_CalculateFPS(void) sampleIndex = 0; averageFPS = 0.0; - for (i = 0; i < NUM_FPS_SAMPLES; i++) + for (int i = 0; i < NUM_FPS_SAMPLES; i++) { averageFPS += fps_samples[i]; } @@ -458,7 +457,7 @@ void SCR_DisplayTicRate(void) return; // new kart counter - if ((cv_ticrate.value == 1) || (cv_ticrate.value == 2)) + if (cv_ticrate.value == 1 || cv_ticrate.value == 2) { // draw "FPS" if (cv_ticrate.value == 1) @@ -492,7 +491,7 @@ void SCR_DisplayTicRate(void) // draw our actual framerate V_DrawPingNum(x, 190, fpsflags, fps, ticcntcolor); } - else if ((cv_ticrate.value == 3)||(cv_ticrate.value == 4)) // kart v1.0/srb2 counter + else if (cv_ticrate.value == 3 || cv_ticrate.value == 4) // kart v1.0/srb2 counter { if (fps > (benchmark - 5)) ticcntcolor2 = V_GREENMAP; diff --git a/src/sdl/Srb2SDL.dsp b/src/sdl/Srb2SDL.dsp index 92821295d..6f799f4fb 100644 --- a/src/sdl/Srb2SDL.dsp +++ b/src/sdl/Srb2SDL.dsp @@ -572,7 +572,7 @@ SOURCE=..\hardware\hw_draw.c # End Source File # Begin Source File -SOURCE=..\hardware\hw_drv.h +SOURCE=..\hardware\hw_gl.h # End Source File # Begin Source File diff --git a/src/sdl/hwsym_sdl.c b/src/sdl/hwsym_sdl.c index 23526a98f..d3da79355 100644 --- a/src/sdl/hwsym_sdl.c +++ b/src/sdl/hwsym_sdl.c @@ -43,14 +43,6 @@ #define _CREATE_DLL_ // necessary for Unix AND Windows -#ifdef HWRENDER -#include "../hardware/hw_drv.h" -#include "ogl_sdl.h" -#ifdef STATIC_OPENGL -#include "../hardware/r_opengl/r_opengl.h" -#endif -#endif - #ifdef HW3SOUND #include "../hardware/hw3dsdrv.h" #endif @@ -73,55 +65,7 @@ void *hwSym(const char *funcName,void *handle) { void *funcPointer = NULL; -#ifdef HWRENDER - if (0 == strcmp("SetTexturePalette", funcName)) - funcPointer = &OglSdlSetPalette; - - GETFUNC(Init); - GETFUNC(SetupGLInfo); - GETFUNC(Draw2DLine); - GETFUNC(DrawPolygon); - GETFUNC(DrawIndexedTriangles); - GETFUNC(SetBlend); - GETFUNC(ClearBuffer); - GETFUNC(SetTexture); - GETFUNC(UpdateTexture); - GETFUNC(DeleteTexture); - GETFUNC(ReadScreenTexture); - GETFUNC(GClipRect); - GETFUNC(ClearMipMapCache); - GETFUNC(SetSpecialState); - GETFUNC(GetTextureUsed); - GETFUNC(DrawModel); - GETFUNC(CreateModelVBOs); - GETFUNC(SetTransform); - GETFUNC(PostImgRedraw); - GETFUNC(FlushScreenTextures); - GETFUNC(DoScreenWipe); - GETFUNC(DrawScreenTexture); - GETFUNC(MakeScreenTexture); - GETFUNC(RenderVhsEffect); - GETFUNC(DrawScreenFinalTexture); - - GETFUNC(RenderSkyDome); - - GETFUNC(InitShaders); - GETFUNC(LoadShader); - GETFUNC(CompileShader); - GETFUNC(SetShader); - GETFUNC(UnSetShader); - - GETFUNC(SetShaderInfo); - - GETFUNC(SetPaletteLookup); - GETFUNC(CreateLightTable); - GETFUNC(ClearLightTables); - GETFUNC(SetScreenPalette); - -#else //HWRENDER - if (0 == strcmp("FinishUpdate", funcName)) - return funcPointer; //&FinishUpdate; -#endif //!HWRENDER + if (0) ; #ifdef STATIC3DS GETFUNC(Startup); GETFUNC(AddSfx); diff --git a/src/sdl/i_system.c b/src/sdl/i_system.c index f999d8684..882535203 100644 --- a/src/sdl/i_system.c +++ b/src/sdl/i_system.c @@ -401,39 +401,15 @@ static void JoyReset(SDLJoyInfo_t *JoySet) //JoySet->scale } -/** \brief First joystick up and running +/** \brief joystick up and running */ -static INT32 joystick_started = 0; +static INT32 joystick_started[MAXSPLITSCREENPLAYERS] = {0, 0, 0, 0}; -/** \brief SDL info about joystick 1 +/** \brief SDL info about joystick */ -SDLJoyInfo_t JoyInfo; +SDLJoyInfo_t JoyInfo[MAXSPLITSCREENPLAYERS]; -/** \brief Second joystick up and running -*/ -static INT32 joystick2_started = 0; - -/** \brief SDL info about joystick 2 -*/ -SDLJoyInfo_t JoyInfo2; - -/** \brief Third joystick up and running -*/ -static INT32 joystick3_started = 0; - -/** \brief SDL info about joystick 3 -*/ -SDLJoyInfo_t JoyInfo3; - -/** \brief Fourth joystick up and running -*/ -static INT32 joystick4_started = 0; - -/** \brief SDL info about joystick 4 -*/ -SDLJoyInfo_t JoyInfo4; - #ifdef HAVE_TERMIOS static INT32 fdmouse2 = -1; static INT32 mouse2_started = 0; @@ -1079,26 +1055,26 @@ INT32 I_GetKey (void) // void I_JoyScale(void) { - Joystick.bGamepadStyle = cv_joyscale.value==0; - JoyInfo.scale = Joystick.bGamepadStyle?1:cv_joyscale.value; + Joystick[0].bGamepadStyle = cv_joyscale[0].value==0; + JoyInfo[0].scale = Joystick[0].bGamepadStyle?1:cv_joyscale[0].value; } void I_JoyScale2(void) { - Joystick2.bGamepadStyle = cv_joyscale2.value==0; - JoyInfo2.scale = Joystick2.bGamepadStyle?1:cv_joyscale2.value; + Joystick[1].bGamepadStyle = cv_joyscale[1].value==0; + JoyInfo[1].scale = Joystick[1].bGamepadStyle?1:cv_joyscale[1].value; } void I_JoyScale3(void) { - Joystick3.bGamepadStyle = cv_joyscale3.value==0; - JoyInfo3.scale = Joystick3.bGamepadStyle?1:cv_joyscale3.value; + Joystick[2].bGamepadStyle = cv_joyscale[2].value==0; + JoyInfo[2].scale = Joystick[2].bGamepadStyle?1:cv_joyscale[2].value; } void I_JoyScale4(void) { - Joystick4.bGamepadStyle = cv_joyscale4.value==0; - JoyInfo4.scale = Joystick4.bGamepadStyle?1:cv_joyscale4.value; + Joystick[3].bGamepadStyle = cv_joyscale[3].value==0; + JoyInfo[3].scale = Joystick[3].bGamepadStyle?1:cv_joyscale[3].value; } // Cheat to get the device index for a joystick handle @@ -1116,219 +1092,70 @@ INT32 I_GetJoystickDeviceIndex(SDL_GameController *dev) return -1; } -// Misleading function: updates device indices for all players BUT the one specified. -// Necessary for SDL_JOYDEVICEADDED events -void I_UpdateJoystickDeviceIndices(INT32 player) +void I_UpdateJoystickDeviceIndex(UINT8 player) { - if (player != 1) // This is a fucking mess. + /////////////////////////////////////////////// + // update this joystick's device index (wow) // + /////////////////////////////////////////////// + if (JoyInfo[player].dev) { - ////////////////////////////// - // update joystick 1's device index - ////////////////////////////// - - if (JoyInfo.dev) - cv_usejoystick.value = I_GetJoystickDeviceIndex(JoyInfo.dev) + 1; - // is cv_usejoystick used? - else if (// don't check JoyInfo or cv_usejoystick; we're currently operating on those - atoi(cv_usejoystick.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick2.value - && atoi(cv_usejoystick.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick3.value - && atoi(cv_usejoystick.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick4.value) - cv_usejoystick.value = atoi(cv_usejoystick.string); - // is cv_usejoystick2 used? - else if ( // don't check JoyInfo or cv_usejoystick; we're currently operating on those - atoi(cv_usejoystick2.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick2.value - && atoi(cv_usejoystick2.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick3.value - && atoi(cv_usejoystick2.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick4.value) - cv_usejoystick.value = atoi(cv_usejoystick2.string); - // is cv_usejoystick3 used? - else if (// don't check JoyInfo or cv_usejoystick; we're currently operating on those - atoi(cv_usejoystick3.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick2.value - && atoi(cv_usejoystick3.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick3.value - && atoi(cv_usejoystick3.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick4.value) - cv_usejoystick.value = atoi(cv_usejoystick3.string); - // is cv_usejoystick4 used? - else if (// don't check JoyInfo or cv_usejoystick; we're currently operating on those - atoi(cv_usejoystick4.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick2.value - && atoi(cv_usejoystick4.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick3.value - && atoi(cv_usejoystick4.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick4.value) - cv_usejoystick.value = atoi(cv_usejoystick4.string); - else // we tried... - cv_usejoystick.value = 0; + cv_usejoystick[player].value = I_GetJoystickDeviceIndex(JoyInfo[player].dev) + 1; } - - if (player != 2) + else { - ////////////////////////////// - // update joystick 2's device index - ////////////////////////////// - - if (JoyInfo2.dev) - cv_usejoystick2.value = I_GetJoystickDeviceIndex(JoyInfo2.dev) + 1; - // is cv_usejoystick2 used? - else if (atoi(cv_usejoystick2.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick.value - // don't check JoyInfo2 or cv_usejoystick2; we're currently operating on those - && atoi(cv_usejoystick2.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick3.value - && atoi(cv_usejoystick2.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick4.value) - cv_usejoystick2.value = atoi(cv_usejoystick2.string); - // is cv_usejoystick used? - else if (atoi(cv_usejoystick.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick.value - // don't check JoyInfo2 or cv_usejoystick2; we're currently operating on those - && atoi(cv_usejoystick.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick3.value - && atoi(cv_usejoystick.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick4.value) - cv_usejoystick2.value = atoi(cv_usejoystick.string); - // is cv_usejoystick3 used? - else if (atoi(cv_usejoystick3.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick.value - // don't check JoyInfo2 or cv_usejoystick2; we're currently operating on those - && atoi(cv_usejoystick3.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick3.value - && atoi(cv_usejoystick3.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick4.value) - cv_usejoystick2.value = atoi(cv_usejoystick3.string); - // is cv_usejoystick4 used? - else if (atoi(cv_usejoystick4.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick.value - // don't check JoyInfo2 or cv_usejoystick2; we're currently operating on those - && atoi(cv_usejoystick4.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick3.value - && atoi(cv_usejoystick4.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick4.value) - cv_usejoystick2.value = atoi(cv_usejoystick4.string); - else // we tried... - cv_usejoystick2.value = 0; - } - - if (player != 3) - { - ////////////////////////////// - // update joystick 3's device index - ////////////////////////////// - - if (JoyInfo3.dev) - cv_usejoystick3.value = I_GetJoystickDeviceIndex(JoyInfo3.dev) + 1; - // is cv_usejoystick3 used? - else if (atoi(cv_usejoystick3.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick.value - && atoi(cv_usejoystick3.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick2.value - // don't check JoyInfo3 or cv_usejoystick3; we're currently operating on those - && atoi(cv_usejoystick3.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick4.value) - cv_usejoystick3.value = atoi(cv_usejoystick3.string); - // is cv_usejoystick used? - else if (atoi(cv_usejoystick.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick.value - && atoi(cv_usejoystick.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick2.value - // don't check JoyInfo3 or cv_usejoystick3; we're currently operating on those - && atoi(cv_usejoystick.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick4.value) - cv_usejoystick3.value = atoi(cv_usejoystick.string); - // is cv_usejoystick2 used? - else if (atoi(cv_usejoystick2.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick.value - && atoi(cv_usejoystick2.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick2.value - // don't check JoyInfo3 or cv_usejoystick3; we're currently operating on those - && atoi(cv_usejoystick2.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick4.value) - cv_usejoystick3.value = atoi(cv_usejoystick2.string); - // is cv_usejoystick4 used? - else if (atoi(cv_usejoystick4.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick.value - && atoi(cv_usejoystick4.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick2.value - // don't check JoyInfo3 or cv_usejoystick3; we're currently operating on those - && atoi(cv_usejoystick4.string) != JoyInfo4.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick4.value) - cv_usejoystick3.value = atoi(cv_usejoystick4.string); - else // we tried... - cv_usejoystick3.value = 0; - } - - if (player != 4) - { - ////////////////////////////// - // update joystick 4's device index - ////////////////////////////// - - if (JoyInfo4.dev) - cv_usejoystick4.value = I_GetJoystickDeviceIndex(JoyInfo4.dev) + 1; - // is cv_usejoystick4 used? - else if (atoi(cv_usejoystick4.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick.value - && atoi(cv_usejoystick4.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick2.value - && atoi(cv_usejoystick4.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick4.string) != cv_usejoystick3.value) - // don't check JoyInfo4 or cv_usejoystick4; we're currently operating on those - cv_usejoystick4.value = atoi(cv_usejoystick4.string); - // is cv_usejoystick used? - else if (atoi(cv_usejoystick.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick.value - && atoi(cv_usejoystick.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick2.value - && atoi(cv_usejoystick.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick.string) != cv_usejoystick3.value) - // don't check JoyInfo4 or cv_usejoystick4; we're currently operating on those - cv_usejoystick4.value = atoi(cv_usejoystick.string); - // is cv_usejoystick2 used? - else if (atoi(cv_usejoystick2.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick.value - && atoi(cv_usejoystick2.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick2.value - && atoi(cv_usejoystick2.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick2.string) != cv_usejoystick3.value) - // don't check JoyInfo4 or cv_usejoystick4; we're currently operating on those - cv_usejoystick4.value = atoi(cv_usejoystick2.string); - // is cv_usejoystick3 used? - else if (atoi(cv_usejoystick3.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick.value - && atoi(cv_usejoystick3.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick2.value - && atoi(cv_usejoystick3.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick3.string) != cv_usejoystick3.value) - // don't check JoyInfo4 or cv_usejoystick4; we're currently operating on those - cv_usejoystick4.value = atoi(cv_usejoystick3.string); - else // we tried... - cv_usejoystick4.value = 0; + UINT8 joystickID, compareJoystick; + for (joystickID = 0; joystickID < MAXSPLITSCREENPLAYERS; joystickID++) + { + // is this cv_usejoystick used? + const INT32 value = atoi(cv_usejoystick[joystickID].string); + for (compareJoystick = 0; compareJoystick < MAXSPLITSCREENPLAYERS; compareJoystick++) + { + if (compareJoystick == player) + continue; + if (value == JoyInfo[compareJoystick].oldjoy || value == cv_usejoystick[compareJoystick].value) + break; + } + if (compareJoystick == MAXSPLITSCREENPLAYERS) + { + // We DID make it through the whole loop, so we can use this one! + cv_usejoystick[player].value = value; + break; + } + } + if (joystickID == MAXSPLITSCREENPLAYERS) + { + // We DID NOT make it through the whole loop, so we can't assign this joystick to anything. + // When you try your best, but you don't succeed... + cv_usejoystick[player].value = 0; + } } } -/** \brief Joystick 1 buttons states +void I_UpdateJoystickDeviceIndices(UINT8 excludePlayer) +{ + UINT8 player; + + for (player = 0; player < MAXSPLITSCREENPLAYERS; player++) + { + if (player == excludePlayer) + continue; + + I_UpdateJoystickDeviceIndex(player); + } +} + +/** \brief Joystick buttons states */ -static UINT64 lastjoybuttons = 0; +static UINT64 lastjoybuttons[MAXSPLITSCREENPLAYERS] = {0,0,0,0}; -/** \brief Joystick 1 hats state +/** \brief Joystick hats state */ -static UINT64 lastjoyhats = 0; - -/** \brief Shuts down joystick 1 - +static UINT64 lastjoyhats[MAXSPLITSCREENPLAYERS] = {0,0,0,0}; +/** \brief Shuts down joystick \return void - - */ -void I_ShutdownJoystick(void) +void I_ShutdownJoystick(UINT8 index) { INT32 i; event_t event; @@ -1336,7 +1163,7 @@ void I_ShutdownJoystick(void) event.data2 = 0; event.data3 = 0; - lastjoybuttons = lastjoyhats = 0; + lastjoybuttons[index] = lastjoyhats[index] = 0; // emulate the up of all joystick buttons for (i=0;i= 0; i--) - { - joybuttons <<= 1; - if (SDL_JoystickGetButton(JoyInfo.dev,i)) - joybuttons |= 1; - } + joyhats |= SDL_GameControllerGetButton(JoyInfo[index].dev, SDL_CONTROLLER_BUTTON_DPAD_UP); + joyhats |= SDL_GameControllerGetButton(JoyInfo[index].dev, SDL_CONTROLLER_BUTTON_DPAD_DOWN) << 1; + joyhats |= SDL_GameControllerGetButton(JoyInfo[index].dev, SDL_CONTROLLER_BUTTON_DPAD_LEFT) << 2; + joyhats |= SDL_GameControllerGetButton(JoyInfo[index].dev, SDL_CONTROLLER_BUTTON_DPAD_RIGHT) << 3; - if (joybuttons != lastjoybuttons) + if (joyhats != lastjoyhats[index]) { INT64 j = 1; // keep only bits that changed since last time - INT64 newbuttons = joybuttons ^ lastjoybuttons; - lastjoybuttons = joybuttons; - - for (i = 0; i < JOYBUTTONS; i++, j <<= 1) - { - if (newbuttons & j) // button changed state? - { - if (joybuttons & j) - event.type = ev_keydown; - else - event.type = ev_keyup; - event.data1 = KEY_JOY1 + i; - D_PostEvent(&event); - } - } - } -#endif - - joyhats |= SDL_GameControllerGetButton(JoyInfo.dev, SDL_CONTROLLER_BUTTON_DPAD_UP); - joyhats |= SDL_GameControllerGetButton(JoyInfo.dev, SDL_CONTROLLER_BUTTON_DPAD_DOWN) << 1; - joyhats |= SDL_GameControllerGetButton(JoyInfo.dev, SDL_CONTROLLER_BUTTON_DPAD_LEFT) << 2; - joyhats |= SDL_GameControllerGetButton(JoyInfo.dev, SDL_CONTROLLER_BUTTON_DPAD_RIGHT) << 3; - - if (joyhats != lastjoyhats) - { - INT64 j = 1; // keep only bits that changed since last time - INT64 newhats = joyhats ^ lastjoyhats; - lastjoyhats = joyhats; + INT64 newhats = joyhats ^ lastjoyhats[index]; + lastjoyhats[index] = joyhats; for (i = 0; i < JOYHATS*4; i++, j <<= 1) { @@ -1437,59 +1229,6 @@ void I_GetJoystickEvents(void) } } } - -#if 0 - // send joystick axis positions - event.type = ev_joystick; - - for (i = JOYAXISSET - 1; i >= 0; i--) - { - event.data1 = i; - if (i*2 + 1 <= JoyInfo.axises) - axisx = SDL_JoystickGetAxis(JoyInfo.dev, i*2 + 0); - else axisx = 0; - if (i*2 + 2 <= JoyInfo.axises) - axisy = SDL_JoystickGetAxis(JoyInfo.dev, i*2 + 1); - else axisy = 0; - - // -32768 to 32767 - axisx = axisx/32; - axisy = axisy/32; - - if (Joystick.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (axisx < -(JOYAXISRANGE/2)) - event.data2 = -1; - else if (axisx > (JOYAXISRANGE/2)) - event.data2 = 1; - else - event.data2 = 0; - if (axisy < -(JOYAXISRANGE/2)) - event.data3 = -1; - else if (axisy > (JOYAXISRANGE/2)) - event.data3 = 1; - else - event.data3 = 0; - } - else - { - - axisx = JoyInfo.scale?((axisx/JoyInfo.scale)*JoyInfo.scale):axisx; - axisy = JoyInfo.scale?((axisy/JoyInfo.scale)*JoyInfo.scale):axisy; - -#ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= axisx && axisx <= SDL_JDEADZONE) axisx = 0; - if (-SDL_JDEADZONE <= axisy && axisy <= SDL_JDEADZONE) axisy = 0; -#endif - - // analog control style , just send the raw data - event.data2 = axisx; // x axis - event.data3 = axisy; // y axis - } - D_PostEvent(&event); - } -#endif } /** \brief Open joystick handle @@ -1500,7 +1239,7 @@ void I_GetJoystickEvents(void) */ -static int joy_open(int joyindex) +static int joy_open(int playerIndex, int joyIndex) { SDL_GameController *newdev = NULL; int num_joy = 0; @@ -1516,7 +1255,7 @@ static int joy_open(int joyindex) return -1; } - if (joyindex <= 0) + if (joyIndex <= 0) return -1; num_joy = SDL_NumJoysticks(); @@ -1527,7 +1266,7 @@ static int joy_open(int joyindex) return -1; } - newdev = SDL_GameControllerOpen(joyindex-1); + newdev = SDL_GameControllerOpen(joyIndex-1); // Handle the edge case where the device <-> joystick index assignment can change due to hotplugging // This indexing is SDL's responsibility and there's not much we can do about it. @@ -1539,869 +1278,51 @@ static int joy_open(int joyindex) // 4. Unplug Controller B -> Index 0 inactive, Index 1 closed // 5. Plug Controller B -> Index 0 opened // 6. Plug Controller A -> Index 0 REPLACED, opened as Controller A; Index 1 is now Controller B - if (JoyInfo.dev) + if (JoyInfo[playerIndex].dev) { - if (JoyInfo.dev == newdev // same device, nothing to do - || (newdev == NULL && SDL_GameControllerGetAttached(JoyInfo.dev))) // we failed, but already have a working device + if (JoyInfo[playerIndex].dev == newdev // same device, nothing to do + || (newdev == NULL && SDL_GameControllerGetAttached(JoyInfo[playerIndex].dev))) // we failed, but already have a working device return SDL_CONTROLLER_AXIS_MAX; // Else, we're changing devices, so send neutral joy events CONS_Debug(DBG_GAMELOGIC, "Joystick1 device is changing; resetting events...\n"); - I_ShutdownJoystick(); + I_ShutdownJoystick(playerIndex); } - JoyInfo.dev = newdev; + JoyInfo[playerIndex].dev = newdev; - if (JoyInfo.dev == NULL) + if (JoyInfo[playerIndex].dev == NULL) { CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick1: Couldn't open device - %s\n"), SDL_GetError()); return -1; } else { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick1: %s\n"), SDL_GameControllerName(JoyInfo.dev)); - JoyInfo.axises = SDL_CONTROLLER_AXIS_MAX; - if (JoyInfo.axises > JOYAXISSET*2) - JoyInfo.axises = JOYAXISSET*2; - /* if (joyaxes<2) - { - I_OutputMsg("Not enought axes?\n"); - return 0; - }*/ + CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick1: %s\n"), SDL_GameControllerName(JoyInfo[playerIndex].dev)); + JoyInfo[playerIndex].axises = SDL_CONTROLLER_AXIS_MAX; - JoyInfo.buttons = SDL_CONTROLLER_BUTTON_MAX ; // dpad is 4 buttons - if (JoyInfo.buttons > JOYBUTTONS) - JoyInfo.buttons = JOYBUTTONS; + if (JoyInfo[playerIndex].axises > JOYAXISSET*2) + JoyInfo[playerIndex].axises = JOYAXISSET*2; - JoyInfo.hats = 4; - if (JoyInfo.hats > JOYHATS) - JoyInfo.hats = JOYHATS; + JoyInfo[playerIndex].buttons = SDL_CONTROLLER_BUTTON_MAX ; // dpad is 4 buttons + if (JoyInfo[playerIndex].buttons > JOYBUTTONS) + JoyInfo[playerIndex].buttons = JOYBUTTONS; - JoyInfo.balls = 0; + JoyInfo[playerIndex].hats = 4; + if (JoyInfo[playerIndex].hats > JOYHATS) + JoyInfo[playerIndex].hats = JOYHATS; - //Joystick.bGamepadStyle = !stricmp(SDL_JoystickName(JoyInfo.dev), "pad"); + JoyInfo[playerIndex].balls = 0; - return JoyInfo.axises; - } -} - -//Joystick2 - -/** \brief Joystick 2 buttons states -*/ -static UINT64 lastjoy2buttons = 0; - -/** \brief Joystick 2 hats state -*/ -static UINT64 lastjoy2hats = 0; - -/** \brief Shuts down joystick 2 - - - \return void -*/ -void I_ShutdownJoystick2(void) -{ - INT32 i; - event_t event; - event.type = ev_keyup; - event.data2 = 0; - event.data3 = 0; - - lastjoy2buttons = lastjoy2hats = 0; - - // emulate the up of all joystick buttons - for (i = 0; i < JOYBUTTONS; i++) - { - event.data1 = KEY_2JOY1 + i; - D_PostEvent(&event); - } - - // emulate the up of all joystick hats - for (i = 0; i < JOYHATS*4; i++) - { - event.data1 = KEY_2HAT1 + i; - D_PostEvent(&event); - } - - // reset joystick position - event.type = ev_joystick2; - for (i = 0; i < JOYAXISSET; i++) - { - event.data1 = i; - D_PostEvent(&event); - } - - joystick2_started = 0; - JoyReset(&JoyInfo2); - - // don't shut down the subsystem here, because hotplugging -} - -void I_GetJoystick2Events(void) -{ - static event_t event = {0,0,0,0}; - INT32 i = 0; - UINT64 joyhats = 0; -#if 0 - UINT64 joybuttons = 0; - UINT32 axisx, axisy; -#endif - - if (!joystick2_started) - return; - - if (!JoyInfo2.dev) //I_ShutdownJoystick2(); - return; - -#if 0 - //faB: look for as much buttons as g_input code supports, - // we don't use the others - for (i = JoyInfo2.buttons - 1; i >= 0; i--) - { - joybuttons <<= 1; - if (SDL_JoystickGetButton(JoyInfo2.dev,i)) - joybuttons |= 1; - } - - if (joybuttons != lastjoy2buttons) - { - INT64 j = 1; // keep only bits that changed since last time - INT64 newbuttons = joybuttons ^ lastjoy2buttons; - lastjoy2buttons = joybuttons; - - for (i = 0; i < JOYBUTTONS; i++, j <<= 1) - { - if (newbuttons & j) // button changed state? - { - if (joybuttons & j) - event.type = ev_keydown; - else - event.type = ev_keyup; - event.data1 = KEY_2JOY1 + i; - D_PostEvent(&event); - } - } - } -#endif - - joyhats |= SDL_GameControllerGetButton(JoyInfo2.dev, SDL_CONTROLLER_BUTTON_DPAD_UP); - joyhats |= SDL_GameControllerGetButton(JoyInfo2.dev, SDL_CONTROLLER_BUTTON_DPAD_DOWN) << 1; - joyhats |= SDL_GameControllerGetButton(JoyInfo2.dev, SDL_CONTROLLER_BUTTON_DPAD_LEFT) << 2; - joyhats |= SDL_GameControllerGetButton(JoyInfo2.dev, SDL_CONTROLLER_BUTTON_DPAD_RIGHT) << 3; - - if (joyhats != lastjoy2hats) - { - INT64 j = 1; // keep only bits that changed since last time - INT64 newhats = joyhats ^ lastjoy2hats; - lastjoy2hats = joyhats; - - for (i = 0; i < JOYHATS*4; i++, j <<= 1) - { - if (newhats & j) // hat changed state? - { - if (joyhats & j) - event.type = ev_keydown; - else - event.type = ev_keyup; - event.data1 = KEY_2HAT1 + i; - D_PostEvent(&event); - } - } - } - -#if 0 - // send joystick axis positions - event.type = ev_joystick2; - - for (i = JOYAXISSET - 1; i >= 0; i--) - { - event.data1 = i; - if (i*2 + 1 <= JoyInfo2.axises) - axisx = SDL_JoystickGetAxis(JoyInfo2.dev, i*2 + 0); - else axisx = 0; - if (i*2 + 2 <= JoyInfo2.axises) - axisy = SDL_JoystickGetAxis(JoyInfo2.dev, i*2 + 1); - else axisy = 0; - - // -32768 to 32767 - axisx = axisx/32; - axisy = axisy/32; - - if (Joystick2.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (axisx < -(JOYAXISRANGE/2)) - event.data2 = -1; - else if (axisx > (JOYAXISRANGE/2)) - event.data2 = 1; - else - event.data2 = 0; - if (axisy < -(JOYAXISRANGE/2)) - event.data3 = -1; - else if (axisy > (JOYAXISRANGE/2)) - event.data3 = 1; - else - event.data3 = 0; - } - else - { - - axisx = JoyInfo2.scale?((axisx/JoyInfo2.scale)*JoyInfo2.scale):axisx; - axisy = JoyInfo2.scale?((axisy/JoyInfo2.scale)*JoyInfo2.scale):axisy; - -#ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= axisx && axisx <= SDL_JDEADZONE) axisx = 0; - if (-SDL_JDEADZONE <= axisy && axisy <= SDL_JDEADZONE) axisy = 0; -#endif - - // analog control style , just send the raw data - event.data2 = axisx; // x axis - event.data3 = axisy; // y axis - } - D_PostEvent(&event); - } -#endif -} - -/** \brief Open joystick handle - - \param fname name of joystick - - \return axises - - -*/ -static int joy_open2(int joyindex) -{ - SDL_GameController *newdev = NULL; - int num_joy = 0; - - if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) - { - CONS_Printf(M_GetText("Joystick subsystem not started\n")); - return -1; - } - if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) - { - CONS_Printf(M_GetText("Game Controller subsystem not started\n")); - return -1; - } - - if (joyindex <= 0) - return -1; - - num_joy = SDL_NumJoysticks(); - - if (num_joy == 0) - { - CONS_Printf("%s", M_GetText("Found no joysticks on this system\n")); - return -1; - } - - newdev = SDL_GameControllerOpen(joyindex-1); - - // Handle the edge case where the device <-> joystick index assignment can change due to hotplugging - // This indexing is SDL's responsibility and there's not much we can do about it. - // - // Example: - // 1. Plug Controller A -> Index 0 opened - // 2. Plug Controller B -> Index 1 opened - // 3. Unplug Controller A -> Index 0 closed, Index 1 active - // 4. Unplug Controller B -> Index 0 inactive, Index 1 closed - // 5. Plug Controller B -> Index 0 opened - // 6. Plug Controller A -> Index 0 REPLACED, opened as Controller A; Index 1 is now Controller B - if (JoyInfo2.dev) - { - if (JoyInfo2.dev == newdev // same device, nothing to do - || (newdev == NULL && SDL_GameControllerGetAttached(JoyInfo2.dev))) // we failed, but already have a working device - return SDL_CONTROLLER_AXIS_MAX; - // Else, we're changing devices, so send neutral joy events - CONS_Debug(DBG_GAMELOGIC, "Joystick2 device is changing; resetting events...\n"); - I_ShutdownJoystick2(); - } - - JoyInfo2.dev = newdev; - - if (JoyInfo2.dev == NULL) - { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick2: couldn't open device - %s\n"), SDL_GetError()); - return -1; - } - else - { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick2: %s\n"), SDL_GameControllerName(JoyInfo2.dev)); - JoyInfo2.axises = SDL_CONTROLLER_AXIS_MAX; - if (JoyInfo2.axises > JOYAXISSET*2) - JoyInfo2.axises = JOYAXISSET*2; -/* if (joyaxes<2) - { - I_OutputMsg("Not enought axes?\n"); - return 0; - }*/ - - JoyInfo2.buttons = SDL_CONTROLLER_BUTTON_MAX ; // dpad is 4 buttons - if (JoyInfo2.buttons > JOYBUTTONS) - JoyInfo2.buttons = JOYBUTTONS; - - JoyInfo2.hats = 4; - if (JoyInfo2.hats > JOYHATS) - JoyInfo2.hats = JOYHATS; - - JoyInfo2.balls = 0; - - //Joystick.bGamepadStyle = !stricmp(SDL_JoystickName(JoyInfo2.dev), "pad"); - - return JoyInfo2.axises; - } -} - -//Joystick3 - -/** \brief Joystick 3 buttons states -*/ -static UINT64 lastjoy3buttons = 0; - -/** \brief Joystick 3 hats state -*/ -static UINT64 lastjoy3hats = 0; - -/** \brief Shuts down joystick 3 - - -\return void -*/ -void I_ShutdownJoystick3(void) -{ - INT32 i; - event_t event; - event.type = ev_keyup; - event.data2 = 0; - event.data3 = 0; - - lastjoy3buttons = lastjoy3hats = 0; - - // emulate the up of all joystick buttons - for (i = 0; i < JOYBUTTONS; i++) - { - event.data1 = KEY_3JOY1 + i; - D_PostEvent(&event); - } - - // emulate the up of all joystick hats - for (i = 0; i < JOYHATS*4; i++) - { - event.data1 = KEY_3HAT1 + i; - D_PostEvent(&event); - } - - // reset joystick position - event.type = ev_joystick3; - for (i = 0; i < JOYAXISSET; i++) - { - event.data1 = i; - D_PostEvent(&event); - } - - joystick3_started = 0; - JoyReset(&JoyInfo3); - - // don't shutdown the subsystem here, because hotplugging -} - -void I_GetJoystick3Events(void) -{ - static event_t event = {0,0,0,0}; - INT32 i = 0; - UINT64 joyhats = 0; -#if 0 - UINT64 joybuttons = 0; - UINT32 axisx, axisy; -#endif - - if (!joystick3_started) - return; - - if (!JoyInfo3.dev) //I_ShutdownJoystick3(); - return; - -#if 0 - //faB: look for as much buttons as g_input code supports, - // we don't use the others - for (i = JoyInfo3.buttons - 1; i >= 0; i--) - { - joybuttons <<= 1; - if (SDL_JoystickGetButton(JoyInfo3.dev,i)) - joybuttons |= 1; - } - - if (joybuttons != lastjoy3buttons) - { - INT64 j = 1; // keep only bits that changed since last time - INT64 newbuttons = joybuttons ^ lastjoy3buttons; - lastjoy3buttons = joybuttons; - - for (i = 0; i < JOYBUTTONS; i++, j <<= 1) - { - if (newbuttons & j) // button changed state? - { - if (joybuttons & j) - event.type = ev_keydown; - else - event.type = ev_keyup; - event.data1 = KEY_3JOY1 + i; - D_PostEvent(&event); - } - } - } -#endif - - joyhats |= SDL_GameControllerGetButton(JoyInfo3.dev, SDL_CONTROLLER_BUTTON_DPAD_UP); - joyhats |= SDL_GameControllerGetButton(JoyInfo3.dev, SDL_CONTROLLER_BUTTON_DPAD_DOWN) << 1; - joyhats |= SDL_GameControllerGetButton(JoyInfo3.dev, SDL_CONTROLLER_BUTTON_DPAD_LEFT) << 2; - joyhats |= SDL_GameControllerGetButton(JoyInfo3.dev, SDL_CONTROLLER_BUTTON_DPAD_RIGHT) << 3; - - if (joyhats != lastjoy3hats) - { - INT64 j = 1; // keep only bits that changed since last time - INT64 newhats = joyhats ^ lastjoy3hats; - lastjoy3hats = joyhats; - - for (i = 0; i < JOYHATS*4; i++, j <<= 1) - { - if (newhats & j) // hat changed state? - { - if (joyhats & j) - event.type = ev_keydown; - else - event.type = ev_keyup; - event.data1 = KEY_3HAT1 + i; - D_PostEvent(&event); - } - } - } - -#if 0 - // send joystick axis positions - event.type = ev_joystick3; - - for (i = JOYAXISSET - 1; i >= 0; i--) - { - event.data1 = i; - if (i*2 + 1 <= JoyInfo3.axises) - axisx = SDL_JoystickGetAxis(JoyInfo3.dev, i*2 + 0); - else axisx = 0; - if (i*2 + 2 <= JoyInfo3.axises) - axisy = SDL_JoystickGetAxis(JoyInfo3.dev, i*2 + 1); - else axisy = 0; - - // -32768 to 32767 - axisx = axisx/32; - axisy = axisy/32; - - if (Joystick3.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (axisx < -(JOYAXISRANGE/2)) - event.data2 = -1; - else if (axisx > (JOYAXISRANGE/2)) - event.data2 = 1; - else - event.data2 = 0; - if (axisy < -(JOYAXISRANGE/2)) - event.data3 = -1; - else if (axisy > (JOYAXISRANGE/2)) - event.data3 = 1; - else - event.data3 = 0; - } - else - { - - axisx = JoyInfo3.scale?((axisx/JoyInfo3.scale)*JoyInfo3.scale):axisx; - axisy = JoyInfo3.scale?((axisy/JoyInfo3.scale)*JoyInfo3.scale):axisy; - -#ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= axisx && axisx <= SDL_JDEADZONE) axisx = 0; - if (-SDL_JDEADZONE <= axisy && axisy <= SDL_JDEADZONE) axisy = 0; -#endif - - // analog control style , just send the raw data - event.data2 = axisx; // x axis - event.data3 = axisy; // y axis - } - D_PostEvent(&event); - } -#endif -} - -/** \brief Open joystick handle - - \param fname name of joystick - - \return axises - - -*/ -static int joy_open3(int joyindex) -{ - SDL_GameController *newdev = NULL; - int num_joy = 0; - - if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) - { - CONS_Printf(M_GetText("Joystick subsystem not started\n")); - return -1; - } - if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) - { - CONS_Printf(M_GetText("Game Controller subsystem not started\n")); - return -1; - } - - if (joyindex <= 0) - return -1; - - num_joy = SDL_NumJoysticks(); - - if (num_joy == 0) - { - CONS_Printf("%s", M_GetText("Found no joysticks on this system\n")); - return -1; - } - - newdev = SDL_GameControllerOpen(joyindex - 1); - - // Handle the edge case where the device <-> joystick index assignment can change due to hotplugging - // This indexing is SDL's responsibility and there's not much we can do about it. - // - // Example: - // 1. Plug Controller A -> Index 0 opened - // 2. Plug Controller B -> Index 1 opened - // 3. Unplug Controller A -> Index 0 closed, Index 1 active - // 4. Unplug Controller B -> Index 0 inactive, Index 1 closed - // 5. Plug Controller B -> Index 0 opened - // 6. Plug Controller A -> Index 0 REPLACED, opened as Controller A; Index 1 is now Controller B - if (JoyInfo3.dev) - { - if (JoyInfo3.dev == newdev // same device, nothing to do - || (newdev == NULL && SDL_GameControllerGetAttached(JoyInfo3.dev))) // we failed, but already have a working device - return SDL_CONTROLLER_AXIS_MAX; - // Else, we're changing devices, so send neutral joy events - CONS_Debug(DBG_GAMELOGIC, "Joystick3 device is changing; resetting events...\n"); - I_ShutdownJoystick3(); - } - - JoyInfo3.dev = newdev; - - if (JoyInfo3.dev == NULL) - { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick3: couldn't open device - %s\n"), SDL_GetError()); - return -1; - } - else - { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick3: %s\n"), SDL_GameControllerName(JoyInfo3.dev)); - JoyInfo3.axises = SDL_CONTROLLER_AXIS_MAX; - if (JoyInfo3.axises > JOYAXISSET * 2) - JoyInfo3.axises = JOYAXISSET * 2; - /* if (joyaxes<2) - { - I_OutputMsg("Not enought axes?\n"); - return 0; - }*/ - - JoyInfo3.buttons = SDL_CONTROLLER_BUTTON_MAX ; // dpad is 4 buttons - if (JoyInfo3.buttons > JOYBUTTONS) - JoyInfo3.buttons = JOYBUTTONS; - - JoyInfo3.hats = 4; - if (JoyInfo3.hats > JOYHATS) - JoyInfo3.hats = JOYHATS; - - JoyInfo3.balls = 0; - - //Joystick.bGamepadStyle = !stricmp(SDL_JoystickName(JoyInfo3.dev), "pad"); - - return JoyInfo3.axises; - } -} - -//Joystick4 - -/** \brief Joystick 4 buttons states -*/ -static UINT64 lastjoy4buttons = 0; - -/** \brief Joystick 4 hats state -*/ -static UINT64 lastjoy4hats = 0; - -/** \brief Shuts down joystick 4 - - -\return void -*/ -void I_ShutdownJoystick4(void) -{ - INT32 i; - event_t event; - event.type = ev_keyup; - event.data2 = 0; - event.data3 = 0; - - lastjoy4buttons = lastjoy4hats = 0; - - // emulate the up of all joystick buttons - for (i = 0; i < JOYBUTTONS; i++) - { - event.data1 = KEY_4JOY1 + i; - D_PostEvent(&event); - } - - // emulate the up of all joystick hats - for (i = 0; i < JOYHATS*4; i++) - { - event.data1 = KEY_4HAT1 + i; - D_PostEvent(&event); - } - - // reset joystick position - event.type = ev_joystick4; - for (i = 0; i < JOYAXISSET; i++) - { - event.data1 = i; - D_PostEvent(&event); - } - - joystick4_started = 0; - JoyReset(&JoyInfo4); - - // don't shutdown the subsystem here, because hotplugging -} - -void I_GetJoystick4Events(void) -{ - static event_t event = {0,0,0,0}; - INT32 i = 0; - UINT64 joyhats = 0; -#if 0 - UINT64 joybuttons = 0; - UINT32 axisx, axisy; -#endif - - if (!joystick4_started) - return; - - if (!JoyInfo4.dev) //I_ShutdownJoystick4(); - return; - -#if 0 - //faB: look for as much buttons as g_input code supports, - // we don't use the others - for (i = JoyInfo4.buttons - 1; i >= 0; i--) - { - joybuttons <<= 1; - if (SDL_JoystickGetButton(JoyInfo4.dev,i)) - joybuttons |= 1; - } - - if (joybuttons != lastjoy4buttons) - { - INT64 j = 1; // keep only bits that changed since last time - INT64 newbuttons = joybuttons ^ lastjoy4buttons; - lastjoy4buttons = joybuttons; - - for (i = 0; i < JOYBUTTONS; i++, j <<= 1) - { - if (newbuttons & j) // button changed state? - { - if (joybuttons & j) - event.type = ev_keydown; - else - event.type = ev_keyup; - event.data1 = KEY_4JOY1 + i; - D_PostEvent(&event); - } - } - } -#endif - - joyhats |= SDL_GameControllerGetButton(JoyInfo4.dev, SDL_CONTROLLER_BUTTON_DPAD_UP); - joyhats |= SDL_GameControllerGetButton(JoyInfo4.dev, SDL_CONTROLLER_BUTTON_DPAD_DOWN) << 1; - joyhats |= SDL_GameControllerGetButton(JoyInfo4.dev, SDL_CONTROLLER_BUTTON_DPAD_LEFT) << 2; - joyhats |= SDL_GameControllerGetButton(JoyInfo4.dev, SDL_CONTROLLER_BUTTON_DPAD_RIGHT) << 3; - - if (joyhats != lastjoy4hats) - { - INT64 j = 1; // keep only bits that changed since last time - INT64 newhats = joyhats ^ lastjoy4hats; - lastjoy4hats = joyhats; - - for (i = 0; i < JOYHATS*4; i++, j <<= 1) - { - if (newhats & j) // hat changed state? - { - if (joyhats & j) - event.type = ev_keydown; - else - event.type = ev_keyup; - event.data1 = KEY_4HAT1 + i; - D_PostEvent(&event); - } - } - } - -#if 0 - // send joystick axis positions - event.type = ev_joystick4; - - for (i = JOYAXISSET - 1; i >= 0; i--) - { - event.data1 = i; - if (i*2 + 1 <= JoyInfo4.axises) - axisx = SDL_JoystickGetAxis(JoyInfo4.dev, i*2 + 0); - else axisx = 0; - if (i*2 + 2 <= JoyInfo4.axises) - axisy = SDL_JoystickGetAxis(JoyInfo4.dev, i*2 + 1); - else axisy = 0; - - // -32768 to 32767 - axisx = axisx/32; - axisy = axisy/32; - - if (Joystick4.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (axisx < -(JOYAXISRANGE/2)) - event.data2 = -1; - else if (axisx > (JOYAXISRANGE/2)) - event.data2 = 1; - else - event.data2 = 0; - if (axisy < -(JOYAXISRANGE/2)) - event.data3 = -1; - else if (axisy > (JOYAXISRANGE/2)) - event.data3 = 1; - else - event.data3 = 0; - } - else - { - - axisx = JoyInfo4.scale?((axisx/JoyInfo4.scale)*JoyInfo4.scale):axisx; - axisy = JoyInfo4.scale?((axisy/JoyInfo4.scale)*JoyInfo4.scale):axisy; - -#ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= axisx && axisx <= SDL_JDEADZONE) axisx = 0; - if (-SDL_JDEADZONE <= axisy && axisy <= SDL_JDEADZONE) axisy = 0; -#endif - - // analog control style , just send the raw data - event.data2 = axisx; // x axis - event.data3 = axisy; // y axis - } - D_PostEvent(&event); - } -#endif -} - -/** \brief Open joystick handle - - \param fname name of joystick - - \return axises - - -*/ -static int joy_open4(int joyindex) -{ - SDL_GameController *newdev = NULL; - int num_joy = 0; - - if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) - { - CONS_Printf(M_GetText("Joystick subsystem not started\n")); - return -1; - } - if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) - { - CONS_Printf(M_GetText("Game Controller subsystem not started\n")); - return -1; - } - - if (joyindex <= 0) - return -1; - - num_joy = SDL_NumJoysticks(); - - if (num_joy == 0) - { - CONS_Printf("%s", M_GetText("Found no joysticks on this system\n")); - return -1; - } - - newdev = SDL_GameControllerOpen(joyindex - 1); - - // Handle the edge case where the device <-> joystick index assignment can change due to hotplugging - // This indexing is SDL's responsibility and there's not much we can do about it. - // - // Example: - // 1. Plug Controller A -> Index 0 opened - // 2. Plug Controller B -> Index 1 opened - // 3. Unplug Controller A -> Index 0 closed, Index 1 active - // 4. Unplug Controller B -> Index 0 inactive, Index 1 closed - // 5. Plug Controller B -> Index 0 opened - // 6. Plug Controller A -> Index 0 REPLACED, opened as Controller A; Index 1 is now Controller B - if (JoyInfo4.dev) - { - if (JoyInfo4.dev == newdev // same device, nothing to do - || (newdev == NULL && SDL_GameControllerGetAttached(JoyInfo4.dev))) // we failed, but already have a working device - return SDL_CONTROLLER_AXIS_MAX; - // Else, we're changing devices, so send neutral joy events - CONS_Debug(DBG_GAMELOGIC, "Joystick4 device is changing; resetting events...\n"); - I_ShutdownJoystick4(); - } - - JoyInfo4.dev = newdev; - - if (JoyInfo4.dev == NULL) - { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick4: couldn't open device - %s\n"), SDL_GetError()); - return -1; - } - else - { - CONS_Debug(DBG_GAMELOGIC, M_GetText("Joystick4: %s\n"), SDL_GameControllerName(JoyInfo4.dev)); - JoyInfo4.axises = SDL_CONTROLLER_AXIS_MAX; - if (JoyInfo4.axises > JOYAXISSET * 2) - JoyInfo4.axises = JOYAXISSET * 2; - /* if (joyaxes<2) - { - I_OutputMsg("Not enought axes?\n"); - return 0; - }*/ - - JoyInfo4.buttons = SDL_CONTROLLER_BUTTON_MAX ; // dpad is 4 buttons - if (JoyInfo4.buttons > JOYBUTTONS) - JoyInfo4.buttons = JOYBUTTONS; - - JoyInfo4.hats = 4; - if (JoyInfo4.hats > JOYHATS) - JoyInfo4.hats = JOYHATS; - - JoyInfo4.balls = 0; - - //Joystick.bGamepadStyle = !stricmp(SDL_JoystickName(JoyInfo4.dev), "pad"); - - return JoyInfo4.axises; + return JoyInfo[playerIndex].axises; } } // // I_InitJoystick // -void I_InitJoystick(void) +void I_InitJoystick(UINT8 index) { + UINT8 i; SDL_GameController *newcontroller = NULL; //I_ShutdownJoystick(); @@ -2434,192 +1355,80 @@ void I_InitJoystick(void) } } - if (cv_usejoystick.value) - newcontroller = SDL_GameControllerOpen(cv_usejoystick.value-1); + if (cv_usejoystick[index].value) + newcontroller = SDL_GameControllerOpen(cv_usejoystick[index].value-1); - if (newcontroller && (JoyInfo2.dev == newcontroller || JoyInfo3.dev == newcontroller || JoyInfo4.dev == newcontroller)) // don't override an active device - cv_usejoystick.value = I_GetJoystickDeviceIndex(JoyInfo.dev) + 1; - else if (newcontroller && joy_open(cv_usejoystick.value) != -1) + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (i == index) + continue; + + if (JoyInfo[i].dev == newcontroller) + break; + } + + if (newcontroller && i < MAXSPLITSCREENPLAYERS) // don't override an active device + { + cv_usejoystick[index].value = I_GetJoystickDeviceIndex(JoyInfo[index].dev) + 1; + } + else if (newcontroller && joy_open(index, cv_usejoystick[index].value) != -1) { // SDL's device indexes are unstable, so cv_usejoystick may not match // the actual device index. So let's cheat a bit and find the device's current index. - JoyInfo.oldjoy = I_GetJoystickDeviceIndex(JoyInfo.dev) + 1; - joystick_started = 1; + JoyInfo[index].oldjoy = I_GetJoystickDeviceIndex(JoyInfo[index].dev) + 1; + joystick_started[index] = 1; } else { - if (JoyInfo.oldjoy) - I_ShutdownJoystick(); - cv_usejoystick.value = 0; - joystick_started = 0; + if (JoyInfo[index].oldjoy) + I_ShutdownJoystick(index); + cv_usejoystick[index].value = 0; + joystick_started[index] = 0; } - if (JoyInfo.dev != newcontroller && JoyInfo2.dev != newcontroller && JoyInfo3.dev != newcontroller && JoyInfo4.dev != newcontroller) + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (JoyInfo[i].dev == newcontroller) + break; + } + + if (i == MAXSPLITSCREENPLAYERS) + { + // Joystick didn't end up being used SDL_GameControllerClose(newcontroller); + } +} + +void I_InitJoystick1(void) +{ + I_InitJoystick(0); } void I_InitJoystick2(void) { - SDL_GameController *newcontroller = NULL; - - //I_ShutdownJoystick2(); - //SDL_SetHintWithPriority("SDL_XINPUT_ENABLED", "0", SDL_HINT_OVERRIDE); - if (M_CheckParm("-nojoy")) - return; - - if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) - { - CONS_Printf("I_InitJoystick2()...\n"); - if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) - { - CONS_Printf(M_GetText("Couldn't initialize joystick: %s\n"), SDL_GetError()); - return; - } - } - if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) - { - if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1) - { - CONS_Printf(M_GetText("Couldn't initialize gamepads: %s\n"), SDL_GetError()); - return; - } - } - - if (cv_usejoystick2.value) - newcontroller = SDL_GameControllerOpen(cv_usejoystick2.value-1); - - if (newcontroller && (JoyInfo.dev == newcontroller || JoyInfo3.dev == newcontroller || JoyInfo4.dev == newcontroller)) // don't override an active device - cv_usejoystick2.value = I_GetJoystickDeviceIndex(JoyInfo2.dev) + 1; - else if (newcontroller && joy_open2(cv_usejoystick2.value) != -1) - { - // SDL's device indexes are unstable, so cv_usejoystick may not match - // the actual device index. So let's cheat a bit and find the device's current index. - JoyInfo2.oldjoy = I_GetJoystickDeviceIndex(JoyInfo2.dev) + 1; - joystick2_started = 1; - } - else - { - if (JoyInfo2.oldjoy) - I_ShutdownJoystick2(); - cv_usejoystick2.value = 0; - joystick2_started = 0; - } - - if (JoyInfo.dev != newcontroller && JoyInfo2.dev != newcontroller && JoyInfo3.dev != newcontroller && JoyInfo4.dev != newcontroller) - SDL_GameControllerClose(newcontroller); + I_InitJoystick(1); } void I_InitJoystick3(void) { - SDL_GameController *newcontroller = NULL; - - //I_ShutdownJoystick3(); - //SDL_SetHintWithPriority("SDL_XINPUT_ENABLED", "0", SDL_HINT_OVERRIDE); - if (M_CheckParm("-nojoy")) - return; - - if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) - { - CONS_Printf("I_InitJoystick3()...\n"); - if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) - { - CONS_Printf(M_GetText("Couldn't initialize joystick: %s\n"), SDL_GetError()); - return; - } - } - if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) - { - if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1) - { - CONS_Printf(M_GetText("Couldn't initialize gamepads: %s\n"), SDL_GetError()); - return; - } - } - - if (cv_usejoystick3.value) - newcontroller = SDL_GameControllerOpen(cv_usejoystick3.value - 1); - - if (newcontroller && (JoyInfo.dev == newcontroller || JoyInfo2.dev == newcontroller || JoyInfo4.dev == newcontroller)) // don't override an active device - cv_usejoystick3.value = I_GetJoystickDeviceIndex(JoyInfo3.dev) + 1; - else if (newcontroller && joy_open3(cv_usejoystick3.value) != -1) - { - // SDL's device indexes are unstable, so cv_usejoystick may not match - // the actual device index. So let's cheat a bit and find the device's current index. - JoyInfo3.oldjoy = I_GetJoystickDeviceIndex(JoyInfo3.dev) + 1; - joystick3_started = 1; - } - else - { - if (JoyInfo3.oldjoy) - I_ShutdownJoystick3(); - cv_usejoystick3.value = 0; - joystick3_started = 0; - } - - if (JoyInfo.dev != newcontroller && JoyInfo2.dev != newcontroller && JoyInfo3.dev != newcontroller && JoyInfo4.dev != newcontroller) - SDL_GameControllerClose(newcontroller); + I_InitJoystick(2); } void I_InitJoystick4(void) { - SDL_GameController *newcontroller = NULL; - - //I_ShutdownJoystick4(); - //SDL_SetHintWithPriority("SDL_XINPUT_ENABLED", "0", SDL_HINT_OVERRIDE); - if (M_CheckParm("-nojoy")) - return; - - if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) - { - CONS_Printf("I_InitJoystick4()...\n"); - if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) - { - CONS_Printf(M_GetText("Couldn't initialize joystick: %s\n"), SDL_GetError()); - return; - } - } - if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) - { - if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1) - { - CONS_Printf(M_GetText("Couldn't initialize gamepads: %s\n"), SDL_GetError()); - return; - } - } - - if (cv_usejoystick4.value) - newcontroller = SDL_GameControllerOpen(cv_usejoystick4.value - 1); - - if (newcontroller && (JoyInfo.dev == newcontroller || JoyInfo2.dev == newcontroller || JoyInfo4.dev == newcontroller)) // don't override an active device - cv_usejoystick4.value = I_GetJoystickDeviceIndex(JoyInfo4.dev) + 1; - else if (newcontroller && joy_open4(cv_usejoystick4.value) != -1) - { - // SDL's device indexes are unstable, so cv_usejoystick may not match - // the actual device index. So let's cheat a bit and find the device's current index. - JoyInfo4.oldjoy = I_GetJoystickDeviceIndex(JoyInfo4.dev) + 1; - joystick4_started = 1; - } - else - { - if (JoyInfo4.oldjoy) - I_ShutdownJoystick4(); - cv_usejoystick4.value = 0; - joystick4_started = 0; - } - - if (JoyInfo.dev != newcontroller && JoyInfo2.dev != newcontroller && JoyInfo3.dev != newcontroller && JoyInfo4.dev != newcontroller) - SDL_GameControllerClose(newcontroller); + I_InitJoystick(3); } static void I_ShutdownInput(void) { + UINT8 i; + // Yes, the name is misleading: these send neutral events to // clean up the unplugged joystick's input // Note these methods are internal to this file, not called elsewhere. - I_ShutdownJoystick(); - I_ShutdownJoystick2(); - I_ShutdownJoystick3(); - I_ShutdownJoystick4(); + + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + I_ShutdownJoystick(i); if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == SDL_INIT_GAMECONTROLLER) { diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 241f09e05..7af6455fe 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -74,15 +74,17 @@ #include "../i_video.h" #include "../console.h" #include "../command.h" -#include "sdlmain.h" #include "../i_system.h" #include "../hu_stuff.h" // for chat_on + +#include "sdlmain.h" + #ifdef HWRENDER #include "../hardware/hw_main.h" -#include "../hardware/hw_drv.h" +#include "../hardware/hw_gl.h" #include "../hardware/r_opengl/r_opengl.h" //for supportFBO -// For dynamic referencing of HW rendering functions -#include "hwsym_sdl.h" + +#include "hwsym_sdl.h" // For dynamic referencing of HW rendering functions #include "ogl_sdl.h" #endif @@ -128,6 +130,10 @@ consvar_t cv_keyboardlayout = {"keyboardlayout", "Default US", CV_SAVE|CV_CALL, static void Impl_SetVsync(void); +static INT32 desktopwidth = 0, desktopheight = 0; + +static void I_CheckDesktopRes(void); + // synchronize page flipping with screen refresh consvar_t cv_vidwait = {"vid_wait", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, Impl_SetVsync, 0, NULL, NULL, 0, 0, NULL}; static consvar_t cv_stretch = {"stretch", "Off", CV_SAVE|CV_NOSHOWHELP, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -217,10 +223,6 @@ static SDL_bool Impl_CreateWindow(SDL_bool fullscreen); static void Impl_SetWindowIcon(void); #ifdef USE_FBO_OGL -#if defined (__unix__) -static void I_FixXwaylandNvidia(void); -boolean xwaylandcrap = false; -#endif boolean downsample = false; void RefreshOGLSDLSurface(void) { @@ -278,10 +280,8 @@ static void SDLSetMode(INT32 width, INT32 height, SDL_bool fullscreen) #ifdef HWRENDER if (rendermode == render_opengl) { + I_CheckDesktopRes(); #ifdef USE_FBO_OGL -#if defined (__unix__) - I_FixXwaylandNvidia(); -#endif I_DownSample(); #endif OglSdlSurface(vid.width, vid.height); @@ -667,152 +667,121 @@ static INT32 SDLJoyAxis(const Sint16 axis, evtype_t which) { // -32768 to 32767 INT32 raxis = axis/32; + UINT8 pid; + if (which == ev_joystick) - { - if (Joystick.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (raxis < -(JOYAXISRANGE/2)) - raxis = -1; - else if (raxis > (JOYAXISRANGE/2)) - raxis = 1; - else - raxis = 0; - } - else - { - raxis = JoyInfo.scale!=1?((raxis/JoyInfo.scale)*JoyInfo.scale):raxis; - -#ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= raxis && raxis <= SDL_JDEADZONE) - raxis = 0; -#endif - } - } + pid = 0; else if (which == ev_joystick2) - { - if (Joystick2.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (raxis < -(JOYAXISRANGE/2)) - raxis = -1; - else if (raxis > (JOYAXISRANGE/2)) - raxis = 1; - else raxis = 0; - } - else - { - raxis = JoyInfo2.scale!=1?((raxis/JoyInfo2.scale)*JoyInfo2.scale):raxis; - -#ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= raxis && raxis <= SDL_JDEADZONE) - raxis = 0; -#endif - } - } + pid = 1; else if (which == ev_joystick3) - { - if (Joystick3.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (raxis < -(JOYAXISRANGE/2)) - raxis = -1; - else if (raxis > (JOYAXISRANGE/2)) - raxis = 1; - else raxis = 0; - } - else - { - raxis = JoyInfo3.scale!=1?((raxis/JoyInfo3.scale)*JoyInfo3.scale):raxis; - -#ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= raxis && raxis <= SDL_JDEADZONE) - raxis = 0; -#endif - } - } + pid = 2; else if (which == ev_joystick4) + pid = 3; + else + return 0; + + if (Joystick[pid].bGamepadStyle) { - if (Joystick4.bGamepadStyle) - { - // gamepad control type, on or off, live or die - if (raxis < -(JOYAXISRANGE/2)) - raxis = -1; - else if (raxis > (JOYAXISRANGE/2)) - raxis = 1; - else raxis = 0; - } + // gamepad control type, on or off, live or die + if (raxis < -(JOYAXISRANGE/2)) + raxis = -1; + else if (raxis > (JOYAXISRANGE/2)) + raxis = 1; else - { - raxis = JoyInfo4.scale!=1?((raxis/JoyInfo4.scale)*JoyInfo4.scale):raxis; + raxis = 0; + } + else + { + raxis = JoyInfo[pid].scale!=1?((raxis/JoyInfo[pid].scale)*JoyInfo[pid].scale):raxis; #ifdef SDL_JDEADZONE - if (-SDL_JDEADZONE <= raxis && raxis <= SDL_JDEADZONE) - raxis = 0; + if (-SDL_JDEADZONE <= raxis && raxis <= SDL_JDEADZONE) + raxis = 0; #endif - } } return raxis; } +static void I_CheckDesktopRes(void) +{ + int currentDisplayIndex = -1; + SDL_DisplayMode curmode; + + if (desktopwidth == vid.width && desktopheight == vid.height) + { + return; + } + + desktopwidth = 0; + desktopheight = 0; + + currentDisplayIndex = SDL_GetWindowDisplayIndex(window); + + // No valid index + if (currentDisplayIndex < 0) + { + return; + } + + if (SDL_GetCurrentDisplayMode(currentDisplayIndex, &curmode) != 0) + { + return; + } + + desktopwidth = curmode.w; + desktopheight = curmode.h; +} + +boolean I_CheckNativeRes(void) +{ + return (vid.width == desktopwidth && vid.height == desktopheight); +} + #ifdef USE_FBO_OGL void I_DownSample(void) { - if (!cv_grframebuffer.value || !supportFBO) //no sense to do this crap if we cant benefit from it + boolean needrefresh = false; + + if (!cv_glframebuffer.value || !supportFBO || (cv_glscreentextures.value == 0)) // no sense to do this crap if we cant benefit from it { downsample = false; return; } - int currentDisplayIndex = SDL_GetWindowDisplayIndex(window); - SDL_DisplayMode curmode; - - if (SDL_GetCurrentDisplayMode(currentDisplayIndex, &curmode) != 0) + if (I_CheckNativeRes() && (downsample == true)) { - downsample = false; // couldnt get display info so turn the thing off + downsample = false; RefreshOGLSDLSurface(); return; } - if ((vid.width > curmode.w) || (vid.height > curmode.h)) //check if current resolution is higher than current display resolution + if ((vid.width > desktopwidth) || (vid.height > desktopheight)) //check if current resolution is higher than current display resolution { downsample = true; - RefreshOGLSDLSurface(); + needrefresh = true; } - else + else if (downsample == true) { - downsample = false; // its not so no need to do crap - RefreshOGLSDLSurface(); - } -} - -#if defined (__unix__) -static void I_FixXwaylandNvidia(void) //dumbass crap, fix ur shit nvidia -{ - if (!supportFBO) - { - xwaylandcrap = false; - return; + downsample = false; + needrefresh = true; } - // enable fbo resize shit, update the ogl surface and turn crap back off lol - xwaylandcrap = true; - RefreshOGLSDLSurface(); - xwaylandcrap = false; - RefreshOGLSDLSurface(); + if (needrefresh) + { + RefreshOGLSDLSurface(); + needrefresh = false; + } } #endif -#endif static void Impl_HandleWindowEvent(SDL_WindowEvent evt) { -#define FOCUSUNION (mousefocus | (kbfocus << 1)) +#define FOCUSUNION (mousefocus | (kbfocus << 1) | (windowmoved << 2)) + static SDL_bool firsttimeonmouse = SDL_TRUE; static SDL_bool mousefocus = SDL_TRUE; static SDL_bool kbfocus = SDL_TRUE; -#ifdef USE_FBO_OGL static SDL_bool windowmoved = SDL_FALSE; -#endif const unsigned int oldfocus = FOCUSUNION; @@ -834,11 +803,9 @@ static void Impl_HandleWindowEvent(SDL_WindowEvent evt) break; case SDL_WINDOWEVENT_MAXIMIZED: break; -#ifdef USE_FBO_OGL case SDL_WINDOWEVENT_MOVED: windowmoved = SDL_TRUE; break; -#endif } if (FOCUSUNION == oldfocus) // No state change @@ -846,12 +813,13 @@ static void Impl_HandleWindowEvent(SDL_WindowEvent evt) return; } -#ifdef USE_FBO_OGL if (windowmoved && rendermode == render_opengl) { + I_CheckDesktopRes(); +#ifdef USE_FBO_OGL I_DownSample(); - } #endif + } if (mousefocus && kbfocus) { @@ -1034,12 +1002,13 @@ static void Impl_HandleControllerAxisEvent(SDL_ControllerAxisEvent evt) event_t event; SDL_JoystickID joyid[4]; INT32 value; + UINT8 i; // Determine the Joystick IDs for each current open joystick - joyid[0] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo.dev)); - joyid[1] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo2.dev)); - joyid[2] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo3.dev)); - joyid[3] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo4.dev)); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + joyid[i] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo[i].dev)); + } event.data1 = event.data2 = event.data3 = INT32_MAX; @@ -1060,9 +1029,11 @@ static void Impl_HandleControllerAxisEvent(SDL_ControllerAxisEvent evt) event.type = ev_joystick4; } else return; + //axis if (evt.axis > JOYAXISSET*2) return; + //vaule value = SDLJoyAxis(evt.value, event.type); switch (evt.axis) @@ -1097,43 +1068,17 @@ static void Impl_HandleControllerAxisEvent(SDL_ControllerAxisEvent evt) D_PostEvent(&event); } -#if 0 -static void Impl_HandleJoystickHatEvent(SDL_JoyHatEvent evt) -{ - event_t event; - SDL_JoystickID joyid[2]; - - // Determine the Joystick IDs for each current open joystick - joyid[0] = SDL_JoystickInstanceID(JoyInfo.dev); - joyid[1] = SDL_JoystickInstanceID(JoyInfo2.dev); - - if (evt.hat >= JOYHATS) - return; // ignore hats with too high an index - - if (evt.which == joyid[0]) - { - event.data1 = KEY_HAT1 + (evt.hat*4); - } - else if (evt.which == joyid[1]) - { - event.data1 = KEY_2HAT1 + (evt.hat*4); - } - else return; - - // NOTE: UNFINISHED -} -#endif - static void Impl_HandleControllerButtonEvent(SDL_ControllerButtonEvent evt, Uint32 type) { event_t event; SDL_JoystickID joyid[4]; + UINT8 i; // Determine the Joystick IDs for each current open joystick - joyid[0] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo.dev)); - joyid[1] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo2.dev)); - joyid[2] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo3.dev)); - joyid[3] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo4.dev)); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + joyid[i] = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(JoyInfo[i].dev)); + } if (evt.button == SDL_CONTROLLER_BUTTON_DPAD_UP || evt.button == SDL_CONTROLLER_BUTTON_DPAD_DOWN @@ -1180,8 +1125,6 @@ static void Impl_HandleControllerButtonEvent(SDL_ControllerButtonEvent evt, Uint if (event.type != ev_console) D_PostEvent(&event); } - - void I_GetEvent(void) { SDL_Event evt; @@ -1189,6 +1132,7 @@ void I_GetEvent(void) // We only want the first motion event, // otherwise we'll end up catching the warp back to center. //int mouseMotionOnce = 0; + INT32 i; if (!graphics_started) { @@ -1254,77 +1198,42 @@ void I_GetEvent(void) // * BUT: If that default index is being occupied, use ANOTHER cv_usejoystick's default value! //////////////////////////////////////////////////////////// - ////////////////////////////// - // PLAYER 1 - ////////////////////////////// - - if (newcontroller && (!JoyInfo.dev || !SDL_GameControllerGetAttached(JoyInfo.dev)) - && JoyInfo2.dev != newcontroller && JoyInfo3.dev != newcontroller && JoyInfo4.dev != newcontroller) // don't override a currently active device + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { - cv_usejoystick.value = evt.cdevice.which + 1; - I_UpdateJoystickDeviceIndices(1); - } + if (newcontroller && (!JoyInfo[i].dev || !SDL_GameControllerGetAttached(JoyInfo[i].dev))) + { + UINT8 j; - ////////////////////////////// - // PLAYER 2 - ////////////////////////////// + for (j = 0; j < MAXSPLITSCREENPLAYERS; j++) + { + if (i == j) + continue; - else if (newcontroller && (!JoyInfo2.dev || !SDL_GameControllerGetAttached(JoyInfo2.dev)) - && JoyInfo.dev != newcontroller && JoyInfo3.dev != newcontroller && JoyInfo4.dev != newcontroller) // don't override a currently active device - { - cv_usejoystick2.value = evt.cdevice.which + 1; - I_UpdateJoystickDeviceIndices(2); - } + if (JoyInfo[j].dev == newcontroller) + break; + } - ////////////////////////////// - // PLAYER 3 - ////////////////////////////// - - else if (newcontroller && (!JoyInfo3.dev || !SDL_GameControllerGetAttached(JoyInfo3.dev)) - && JoyInfo.dev != newcontroller && JoyInfo2.dev != newcontroller && JoyInfo4.dev != newcontroller) // don't override a currently active device - { - cv_usejoystick3.value = evt.cdevice.which + 1; - I_UpdateJoystickDeviceIndices(3); - } - - ////////////////////////////// - // PLAYER 4 - ////////////////////////////// - - else if (newcontroller && (!JoyInfo4.dev || !SDL_GameControllerGetAttached(JoyInfo4.dev)) - && JoyInfo.dev != newcontroller && JoyInfo2.dev != newcontroller && JoyInfo3.dev != newcontroller) // don't override a currently active device - { - cv_usejoystick4.value = evt.cdevice.which + 1; - I_UpdateJoystickDeviceIndices(4); + if (j == MAXSPLITSCREENPLAYERS) + { + // ensures we aren't overriding a currently active device + cv_usejoystick[i].value = evt.jdevice.which + 1; + I_UpdateJoystickDeviceIndices(0); + } + } } //////////////////////////////////////////////////////////// // Was cv_usejoystick disabled in settings? //////////////////////////////////////////////////////////// - if (!strcmp(cv_usejoystick.string, "0") || !cv_usejoystick.value) - cv_usejoystick.value = 0; - else if (atoi(cv_usejoystick.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick, cv_usejoystick.value); - - if (!strcmp(cv_usejoystick2.string, "0") || !cv_usejoystick2.value) - cv_usejoystick2.value = 0; - else if (atoi(cv_usejoystick2.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick2.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick2, cv_usejoystick2.value); - - if (!strcmp(cv_usejoystick3.string, "0") || !cv_usejoystick3.value) - cv_usejoystick3.value = 0; - else if (atoi(cv_usejoystick3.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick3.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick3, cv_usejoystick3.value); - - if (!strcmp(cv_usejoystick4.string, "0") || !cv_usejoystick4.value) - cv_usejoystick4.value = 0; - else if (atoi(cv_usejoystick4.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick4.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick4, cv_usejoystick4.value); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (!strcmp(cv_usejoystick[i].string, "0") || !cv_usejoystick[i].value) + cv_usejoystick[i].value = 0; + else if (atoi(cv_usejoystick[i].string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys + && cv_usejoystick[i].value) // update the cvar ONLY if a device exists + CV_SetValue(&cv_usejoystick[i], cv_usejoystick[i].value); + } //////////////////////////////////////////////////////////// // Update all joysticks' init states @@ -1333,23 +1242,25 @@ void I_GetEvent(void) // if the device is already active, this should do nothing, effectively. //////////////////////////////////////////////////////////// - I_InitJoystick(); - I_InitJoystick2(); - I_InitJoystick3(); - I_InitJoystick4(); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + I_InitJoystick(i); //////////////////////////////////////////////////////////// - CONS_Debug(DBG_GAMELOGIC, "Joystick1 device index: %d\n", JoyInfo.oldjoy); - CONS_Debug(DBG_GAMELOGIC, "Joystick2 device index: %d\n", JoyInfo2.oldjoy); - CONS_Debug(DBG_GAMELOGIC, "Joystick3 device index: %d\n", JoyInfo3.oldjoy); - CONS_Debug(DBG_GAMELOGIC, "Joystick4 device index: %d\n", JoyInfo4.oldjoy); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + CONS_Debug(DBG_GAMELOGIC, "Joystick%d device index: %d\n", i+1, JoyInfo[i].oldjoy); // update the menu if (currentMenu == &OP_JoystickSetDef) M_SetupJoystickMenu(0); - if (JoyInfo.dev != newcontroller && JoyInfo2.dev != newcontroller && JoyInfo3.dev != newcontroller && JoyInfo4.dev != newcontroller) + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (JoyInfo[i].dev == newcontroller) + break; + } + + if (i == MAXSPLITSCREENPLAYERS) SDL_GameControllerClose(newcontroller); } break; @@ -1357,28 +1268,13 @@ void I_GetEvent(void) //////////////////////////////////////////////////////////// case SDL_CONTROLLERDEVICEREMOVED: - if (JoyInfo.dev && !SDL_GameControllerGetAttached(JoyInfo.dev)) + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { - CONS_Debug(DBG_GAMELOGIC, "Joystick1 removed, device index: %d\n", JoyInfo.oldjoy); - I_ShutdownJoystick(); - } - - if (JoyInfo2.dev && !SDL_GameControllerGetAttached(JoyInfo2.dev)) - { - CONS_Debug(DBG_GAMELOGIC, "Joystick2 removed, device index: %d\n", JoyInfo2.oldjoy); - I_ShutdownJoystick2(); - } - - if (JoyInfo3.dev && !SDL_GameControllerGetAttached(JoyInfo3.dev)) - { - CONS_Debug(DBG_GAMELOGIC, "Joystick3 removed, device index: %d\n", JoyInfo3.oldjoy); - I_ShutdownJoystick3(); - } - - if (JoyInfo4.dev && !SDL_GameControllerGetAttached(JoyInfo4.dev)) - { - CONS_Debug(DBG_GAMELOGIC, "Joystick4 removed, device index: %d\n", JoyInfo4.oldjoy); - I_ShutdownJoystick4(); + if (JoyInfo[i].dev && !SDL_GameControllerGetAttached(JoyInfo[i].dev)) + { + CONS_Debug(DBG_GAMELOGIC, "Joystick%d removed, device index: %d\n", i+1, JoyInfo[i].oldjoy); + I_ShutdownJoystick(i); + } } //////////////////////////////////////////////////////////// @@ -1387,124 +1283,32 @@ void I_GetEvent(void) // * BUT: If that default index is being occupied, use ANOTHER cv_usejoystick's default value! //////////////////////////////////////////////////////////// - if (JoyInfo.dev) - cv_usejoystick.value = JoyInfo.oldjoy = I_GetJoystickDeviceIndex(JoyInfo.dev) + 1; - else if (atoi(cv_usejoystick.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo4.oldjoy) - cv_usejoystick.value = atoi(cv_usejoystick.string); - else if (atoi(cv_usejoystick2.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo4.oldjoy) - cv_usejoystick.value = atoi(cv_usejoystick2.string); - else if (atoi(cv_usejoystick3.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo4.oldjoy) - cv_usejoystick.value = atoi(cv_usejoystick3.string); - else if (atoi(cv_usejoystick4.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo4.oldjoy) - cv_usejoystick.value = atoi(cv_usejoystick4.string); - else // we tried... - cv_usejoystick.value = 0; - - if (JoyInfo2.dev) - cv_usejoystick2.value = JoyInfo2.oldjoy = I_GetJoystickDeviceIndex(JoyInfo2.dev) + 1; - else if (atoi(cv_usejoystick.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo4.oldjoy) - cv_usejoystick2.value = atoi(cv_usejoystick.string); - else if (atoi(cv_usejoystick2.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo4.oldjoy) - cv_usejoystick2.value = atoi(cv_usejoystick2.string); - else if (atoi(cv_usejoystick3.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo4.oldjoy) - cv_usejoystick2.value = atoi(cv_usejoystick3.string); - else if (atoi(cv_usejoystick4.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo3.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo4.oldjoy) - cv_usejoystick2.value = atoi(cv_usejoystick4.string); - else // we tried... - cv_usejoystick2.value = 0; - - if (JoyInfo3.dev) - cv_usejoystick3.value = JoyInfo3.oldjoy = I_GetJoystickDeviceIndex(JoyInfo3.dev) + 1; - else if (atoi(cv_usejoystick.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo4.oldjoy) - cv_usejoystick3.value = atoi(cv_usejoystick.string); - else if (atoi(cv_usejoystick2.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo4.oldjoy) - cv_usejoystick3.value = atoi(cv_usejoystick2.string); - else if (atoi(cv_usejoystick3.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo4.oldjoy) - cv_usejoystick3.value = atoi(cv_usejoystick3.string); - else if (atoi(cv_usejoystick4.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo4.oldjoy) - cv_usejoystick3.value = atoi(cv_usejoystick4.string); - else // we tried... - cv_usejoystick3.value = 0; - - if (JoyInfo4.dev) - cv_usejoystick4.value = JoyInfo4.oldjoy = I_GetJoystickDeviceIndex(JoyInfo4.dev) + 1; - else if (atoi(cv_usejoystick.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick.string) != JoyInfo3.oldjoy) - cv_usejoystick4.value = atoi(cv_usejoystick.string); - else if (atoi(cv_usejoystick2.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick2.string) != JoyInfo3.oldjoy) - cv_usejoystick4.value = atoi(cv_usejoystick2.string); - else if (atoi(cv_usejoystick3.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick3.string) != JoyInfo3.oldjoy) - cv_usejoystick4.value = atoi(cv_usejoystick3.string); - else if (atoi(cv_usejoystick4.string) != JoyInfo.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo2.oldjoy - && atoi(cv_usejoystick4.string) != JoyInfo3.oldjoy) - cv_usejoystick4.value = atoi(cv_usejoystick4.string); - else // we tried... - cv_usejoystick4.value = 0; + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + I_UpdateJoystickDeviceIndex(i); + } //////////////////////////////////////////////////////////// // Was cv_usejoystick disabled in settings? //////////////////////////////////////////////////////////// - if (!strcmp(cv_usejoystick.string, "0")) - cv_usejoystick.value = 0; - else if (atoi(cv_usejoystick.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick, cv_usejoystick.value); - - if (!strcmp(cv_usejoystick2.string, "0")) - cv_usejoystick2.value = 0; - else if (atoi(cv_usejoystick2.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick2.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick2, cv_usejoystick2.value); - - if (!strcmp(cv_usejoystick3.string, "0")) - cv_usejoystick3.value = 0; - else if (atoi(cv_usejoystick3.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick3.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick3, cv_usejoystick3.value); - - if (!strcmp(cv_usejoystick4.string, "0")) - cv_usejoystick4.value = 0; - else if (atoi(cv_usejoystick4.string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys - && cv_usejoystick4.value) // update the cvar ONLY if a device exists - CV_SetValue(&cv_usejoystick4, cv_usejoystick4.value); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (!strcmp(cv_usejoystick[i].string, "0")) + { + cv_usejoystick[i].value = 0; + } + else if (atoi(cv_usejoystick[i].string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys + && cv_usejoystick[i].value) // update the cvar ONLY if a device exists + { + CV_SetValue(&cv_usejoystick[i], cv_usejoystick[i].value); + } + } //////////////////////////////////////////////////////////// - CONS_Debug(DBG_GAMELOGIC, "Joystick1 device index: %d\n", JoyInfo.oldjoy); - CONS_Debug(DBG_GAMELOGIC, "Joystick2 device index: %d\n", JoyInfo2.oldjoy); - CONS_Debug(DBG_GAMELOGIC, "Joystick3 device index: %d\n", JoyInfo3.oldjoy); - CONS_Debug(DBG_GAMELOGIC, "Joystick4 device index: %d\n", JoyInfo4.oldjoy); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + CONS_Debug(DBG_GAMELOGIC, "Joystick%d device index: %d\n", i+1, JoyInfo[i].oldjoy); // update the menu if (currentMenu == &OP_JoystickSetDef) @@ -1566,16 +1370,15 @@ void I_StartupMouse(void) void I_OsPolling(void) { SDL_Keymod mod; + INT32 i; if (consolevent) I_GetConsoleEvents(); if (SDL_WasInit(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) == (SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER)) { SDL_GameControllerUpdate(); - I_GetJoystickEvents(); - I_GetJoystick2Events(); - I_GetJoystick3Events(); - I_GetJoystick4Events(); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + I_GetJoystickEvents(i); } I_GetMouseEvents(); @@ -2214,27 +2017,27 @@ void I_StartupGraphics(void) else if (M_CheckParm("-opengl")) rendermode = render_opengl; - msaa = 0; boolean msaa_set = false; - a2c = false; boolean a2c_set = false; + msaa = 0; boolean msaa_set = false; + a2c = false; boolean a2c_set = false; - if (M_CheckParm("-msaa") && M_IsNextParm()) - { - const char* str = M_GetNextParm(); - if (sscanf(str, "%u", &msaa)) - { - msaa_set = true; - } - } + if (M_CheckParm("-msaa") && M_IsNextParm()) + { + const char* str = M_GetNextParm(); + if (sscanf(str, "%u", &msaa)) + { + msaa_set = true; + } + } - if (M_CheckParm("-a2c")) - { - a2c = true; - a2c_set = true; - } - else if (M_CheckParm("-noa2c")) - { - a2c_set = true; - } + if (M_CheckParm("-a2c")) + { + a2c = true; + a2c_set = true; + } + else if (M_CheckParm("-noa2c")) + { + a2c_set = true; + } { char line[16]; @@ -2244,52 +2047,52 @@ void I_StartupGraphics(void) { while (fgets(line, sizeof line, file) != NULL) { - word = strtok(line, " \n"); + word = strtok(line, " \n"); - if (rendermode == render_none) - { - if (strcasecmp(word, "software") == 0) - { - rendermode = render_soft; - } - else if (strcasecmp(word, "opengl") == 0) - { - rendermode = render_opengl; - } + if (rendermode == render_none) + { + if (strcasecmp(word, "software") == 0) + { + rendermode = render_soft; + } + else if (strcasecmp(word, "opengl") == 0) + { + rendermode = render_opengl; + } - if (rendermode != render_none) - { - CONS_Printf("Using last known renderer: %s\n", line); - } + if (rendermode != render_none) + { + CONS_Printf("Using last known renderer: %s\n", line); + } } - if (!msaa_set) - { - if (strcasecmp(word, "msaa") == 0) - { - const char *nextword = strtok(NULL, " \n"); + if (!msaa_set) + { + if (strcasecmp(word, "msaa") == 0) + { + const char *nextword = strtok(NULL, " \n"); - if (!nextword || !sscanf(nextword, "%u", &msaa)) - { - CONS_Alert(CONS_ERROR, "Malformed MSAA entry in renderer.txt\n"); - } - else - { - CONS_Printf("Using last know MSAA value: %u\n", msaa); - } - } - } + if (!nextword || !sscanf(nextword, "%u", &msaa)) + { + CONS_Alert(CONS_ERROR, "Malformed MSAA entry in renderer.txt\n"); + } + else + { + CONS_Printf("Using last know MSAA value: %u\n", msaa); + } + } + } - if (!a2c_set) - { - if (strcasecmp(word, "a2c") == 0) - { - a2c = true; + if (!a2c_set) + { + if (strcasecmp(word, "a2c") == 0) + { + a2c = true; - CONS_Printf("Using a2c because it was specified to be used earlier\n"); - } - } - } + CONS_Printf("Using a2c because it was specified to be used earlier\n"); + } + } + } fclose(file); } @@ -2321,13 +2124,13 @@ void I_StartupGraphics(void) } #ifdef HWRENDER - fprintf(file, "msaa %u\n", msaa); + fprintf(file, "msaa %u\n", msaa); - if (a2c) - fputs("a2c\n", file); + if (a2c) + fputs("a2c\n", file); #endif - fclose(file); + fclose(file); } else { @@ -2338,55 +2141,13 @@ void I_StartupGraphics(void) usesdl2soft = M_CheckParm("-softblit"); borderlesswindow = M_CheckParm("-borderless"); - //SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY>>1,SDL_DEFAULT_REPEAT_INTERVAL<<2); VID_Command_ModeList_f(); + #ifdef HWRENDER if (rendermode == render_opengl) { - HWD.pfnInit = hwSym("Init",NULL); - HWD.pfnSetupGLInfo = hwSym("SetupGLInfo",NULL); - HWD.pfnFinishUpdate = NULL; - HWD.pfnDraw2DLine = hwSym("Draw2DLine",NULL); - HWD.pfnDrawPolygon = hwSym("DrawPolygon",NULL); - HWD.pfnDrawIndexedTriangles = hwSym("DrawIndexedTriangles",NULL); - HWD.pfnSetBlend = hwSym("SetBlend",NULL); - HWD.pfnClearBuffer = hwSym("ClearBuffer",NULL); - HWD.pfnSetTexture = hwSym("SetTexture",NULL); - HWD.pfnUpdateTexture = hwSym("UpdateTexture",NULL); - HWD.pfnDeleteTexture = hwSym("DeleteTexture",NULL); - HWD.pfnReadScreenTexture= hwSym("ReadScreenTexture",NULL); - HWD.pfnGClipRect = hwSym("GClipRect",NULL); - HWD.pfnClearMipMapCache = hwSym("ClearMipMapCache",NULL); - HWD.pfnSetSpecialState = hwSym("SetSpecialState",NULL); - HWD.pfnSetTexturePalette= hwSym("SetTexturePalette",NULL); - HWD.pfnGetTextureUsed = hwSym("GetTextureUsed",NULL); - HWD.pfnDrawModel = hwSym("DrawModel",NULL); - HWD.pfnCreateModelVBOs = hwSym("CreateModelVBOs",NULL); - HWD.pfnSetTransform = hwSym("SetTransform",NULL); - HWD.pfnPostImgRedraw = hwSym("PostImgRedraw",NULL); - HWD.pfnFlushScreenTextures=hwSym("FlushScreenTextures",NULL); - HWD.pfnDoScreenWipe = hwSym("DoScreenWipe",NULL); - HWD.pfnDrawScreenTexture= hwSym("DrawScreenTexture",NULL); - HWD.pfnMakeScreenTexture= hwSym("MakeScreenTexture",NULL); - HWD.pfnRenderVhsEffect = hwSym("RenderVhsEffect",NULL); - HWD.pfnDrawScreenFinalTexture=hwSym("DrawScreenFinalTexture",NULL); + vid.glstate = (VID_LoadOGLAPI() && GL_Init()) ? VID_GL_LIBRARY_LOADED : VID_GL_LIBRARY_ERROR; - HWD.pfnRenderSkyDome = hwSym("RenderSkyDome",NULL); - - HWD.pfnInitShaders = hwSym("InitShaders",NULL); - HWD.pfnLoadShader = hwSym("LoadShader",NULL); - HWD.pfnCompileShader = hwSym("CompileShader",NULL); - HWD.pfnSetShader = hwSym("SetShader",NULL); - HWD.pfnUnSetShader = hwSym("UnSetShader",NULL); - - HWD.pfnSetShaderInfo = hwSym("SetShaderInfo",NULL); - - HWD.pfnSetPaletteLookup = hwSym("SetPaletteLookup",NULL); - HWD.pfnCreateLightTable = hwSym("CreateLightTable",NULL); - HWD.pfnClearLightTables = hwSym("ClearLightTables",NULL); - HWD.pfnSetScreenPalette = hwSym("SetScreenPalette",NULL); - - vid.glstate = HWD.pfnInit() ? VID_GL_LIBRARY_LOADED : VID_GL_LIBRARY_ERROR; // let load the OpenGL library if (vid.glstate == VID_GL_LIBRARY_ERROR) { rendermode = render_soft; @@ -2512,4 +2273,5 @@ static void Impl_SetVsync(void) } #endif } + #endif diff --git a/src/sdl/macosx/Srb2mac.pbproj/project.pbxproj b/src/sdl/macosx/Srb2mac.pbproj/project.pbxproj index ee0bf4697..a4888ec50 100644 --- a/src/sdl/macosx/Srb2mac.pbproj/project.pbxproj +++ b/src/sdl/macosx/Srb2mac.pbproj/project.pbxproj @@ -1060,8 +1060,8 @@ 8417773A085A106C000C01D8 = { fileEncoding = 30; isa = PBXFileReference; - name = hw_drv.h; - path = ../../hardware/hw_drv.h; + name = hw_gl.h; + path = ../../hardware/hw_gl.h; refType = 2; }; 8417773C085A106C000C01D8 = { diff --git a/src/sdl/macosx/Srb2mac.xcodeproj/project.pbxproj b/src/sdl/macosx/Srb2mac.xcodeproj/project.pbxproj index 00930bfb3..9ec22ebcc 100644 --- a/src/sdl/macosx/Srb2mac.xcodeproj/project.pbxproj +++ b/src/sdl/macosx/Srb2mac.xcodeproj/project.pbxproj @@ -180,7 +180,7 @@ 1E44AE630B67CC2B00BAD059 /* hw3sound.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; name = hw3sound.c; path = ../../hardware/hw3sound.c; sourceTree = SOURCE_ROOT; }; 1E44AE640B67CC2B00BAD059 /* hw_cache.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; name = hw_cache.c; path = ../../hardware/hw_cache.c; sourceTree = SOURCE_ROOT; }; 1E44AE650B67CC2B00BAD059 /* hw_dll.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = hw_dll.h; path = ../../hardware/hw_dll.h; sourceTree = SOURCE_ROOT; }; - 1E44AE660B67CC2B00BAD059 /* hw_drv.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = hw_drv.h; path = ../../hardware/hw_drv.h; sourceTree = SOURCE_ROOT; }; + 1E44AE660B67CC2B00BAD059 /* hw_gl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = hw_gl.h; path = ../../hardware/hw_gl.h; sourceTree = SOURCE_ROOT; }; 1E44AE680B67CC2B00BAD059 /* hw_light.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; name = hw_light.c; path = ../../hardware/hw_light.c; sourceTree = SOURCE_ROOT; }; 1E44AE690B67CC2B00BAD059 /* hw_light.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = hw_light.h; path = ../../hardware/hw_light.h; sourceTree = SOURCE_ROOT; }; 1E44AE6A0B67CC2B00BAD059 /* hw3sound.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = hw3sound.h; path = ../../hardware/hw3sound.h; sourceTree = SOURCE_ROOT; }; @@ -533,7 +533,7 @@ 1E44AE630B67CC2B00BAD059 /* hw3sound.c */, 1E44AE640B67CC2B00BAD059 /* hw_cache.c */, 1E44AE650B67CC2B00BAD059 /* hw_dll.h */, - 1E44AE660B67CC2B00BAD059 /* hw_drv.h */, + 1E44AE660B67CC2B00BAD059 /* hw_gl.h */, 1E44AE680B67CC2B00BAD059 /* hw_light.c */, 1E44AE690B67CC2B00BAD059 /* hw_light.h */, 1E44AE6A0B67CC2B00BAD059 /* hw3sound.h */, diff --git a/src/sdl/mixer_sound.c b/src/sdl/mixer_sound.c index 20cd3107c..ced911eba 100644 --- a/src/sdl/mixer_sound.c +++ b/src/sdl/mixer_sound.c @@ -615,6 +615,7 @@ Countstutter (int len) } else bytes = ( music_bytes - music_stutter_bytes ); + I_SetSongPosition((int)( bytes/4/44100.0*1000 )); } } diff --git a/src/sdl/ogl_sdl.c b/src/sdl/ogl_sdl.c index 4adc3dae8..65fae4dd4 100644 --- a/src/sdl/ogl_sdl.c +++ b/src/sdl/ogl_sdl.c @@ -38,6 +38,7 @@ #ifdef HWRENDER #include "../hardware/r_opengl/r_opengl.h" #include "../hardware/hw_main.h" +#include "../hardware/hw_gl.h" #include "ogl_sdl.h" #include "../i_system.h" #include "hwsym_sdl.h" @@ -68,10 +69,20 @@ PFNglGetIntegerv pglGetIntegerv; PFNglGetString pglGetString; #endif -#if defined (__unix__) #ifdef USE_FBO_OGL -static boolean isnvidiagpu = false; + +#if defined (__unix__) +static boolean xwaylandcrap = false; #endif + +boolean UseScreenFBO(void) +{ + return ((supportFBO && cv_glframebuffer.value && downsample) +#if defined (__unix__) + || (supportFBO && xwaylandcrap) +#endif + ); +} #endif /** \brief SDL video display surface @@ -84,7 +95,7 @@ void *GetGLFunc(const char *proc) return SDL_GL_GetProcAddress(proc); } -boolean LoadGL(void) +boolean VID_LoadOGLAPI(void) { #ifndef STATIC_OPENGL const char *OGLLibname = NULL; @@ -101,7 +112,7 @@ boolean LoadGL(void) return 0; } #endif - return SetupGLfunc(); + return true; } /** \brief The OglSdlSurface function @@ -112,10 +123,11 @@ boolean LoadGL(void) \return if true, changed video mode */ +static boolean first_init = false; + boolean OglSdlSurface(INT32 w, INT32 h) { INT32 cbpp = cv_scr_depth.value < 16 ? 16 : cv_scr_depth.value; - static boolean first_init = false; const char *gllogdir = NULL; oglflags = 0; @@ -139,6 +151,8 @@ boolean OglSdlSurface(INT32 w, INT32 h) gl_version = pglGetString(GL_VERSION); gl_renderer = pglGetString(GL_RENDERER); gl_extensions = pglGetString(GL_EXTENSIONS); + pglGetIntegerv(GL_NUM_EXTENSIONS, (GLint*)&gl_num_extensions); + gl_vendor = pglGetString(GL_VENDOR); GL_DBG_Printf("OpenGL %s\n", gl_version); GL_DBG_Printf("GPU: %s\n", gl_renderer); @@ -166,57 +180,53 @@ boolean OglSdlSurface(INT32 w, INT32 h) else supportMipMap = true; - if (isExtAvailable("GL_EXT_texture_filter_anisotropic", gl_extensions)) + if (GL_isExtAvailable("GL_EXT_texture_filter_anisotropic", gl_extensions)) pglGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maximumAnisotropy); else maximumAnisotropy = 1; - granisotropicmode_cons_t[1].value = maximumAnisotropy; + glanisotropicmode_cons_t[1].value = maximumAnisotropy; #if defined (__unix__) #ifdef USE_FBO_OGL - if (strstr((const char*)gl_renderer, "NVIDIA")) - isnvidiagpu = true; + if (supportFBO && strstr((const char*)gl_renderer, "NVIDIA")) + xwaylandcrap = true; #endif #endif } - first_init = true; SDL_GL_SetSwapInterval(cv_vidwait.value ? 1 : 0); // The screen textures need to be flushed if the width or height change so that they be remade for the correct size if (screen_width != w || screen_height != h) { - FlushScreenTextures(); + GL_FlushScreenTextures(); #ifdef USE_FBO_OGL - GLFramebuffer_DeleteAttachments(); + GL_Framebuffer_DeleteAttachments(); #endif } screen_width = (GLint)w; screen_height = (GLint)h; - SetModelView(w, h); - SetStates(); + GL_SetModelView(w, h); + GL_SetStates(); pglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); #ifdef USE_FBO_OGL - RenderToFramebuffer = ((FrameBufferEnabled && supportFBO && downsample) -#if defined (__unix__) - || (isnvidiagpu && xwaylandcrap) -#endif - ); - - if (RenderToFramebuffer) - GLFramebuffer_Enable(); + if (UseScreenFBO()) + GL_Framebuffer_Enable(); else - GLFramebuffer_Disable(); + GL_Framebuffer_Disable(); #endif - HWR_Startup(); + if (!first_init) + HWR_Startup(); textureformatGL = cbpp > 16 ? GL_RGBA : GL_RGB5_A1; + first_init = true; + return true; } @@ -230,6 +240,11 @@ void OglSdlFinishUpdate(boolean waitvbl) { static boolean oldwaitvbl = false; int sdlw, sdlh; + +#ifdef USE_FBO_OGL + const boolean usefbo = UseScreenFBO(); +#endif + if (oldwaitvbl != waitvbl) { SDL_GL_SetSwapInterval(waitvbl ? 1 : 0); @@ -241,44 +256,40 @@ void OglSdlFinishUpdate(boolean waitvbl) HWR_MakeScreenFinalTexture(); #ifdef USE_FBO_OGL - RenderToFramebuffer = ((FrameBufferEnabled && supportFBO && downsample) -#if defined (__unix__) - || (isnvidiagpu && xwaylandcrap) + if (usefbo) + { + GL_Framebuffer_Unbind(); + } #endif - ); - if (RenderToFramebuffer) - GLFramebuffer_Unbind(); -#endif - - HWR_DrawScreenFinalTexture(sdlw, sdlh); + GL_DrawScreenFinalTexture(HWD_SCREENTEXTURE_GENERIC2, sdlw, sdlh, HWR_ShouldUsePaletteRendering()); #ifdef USE_FBO_OGL - if (RenderToFramebuffer) - GLFramebuffer_Enable(); + if (usefbo) + { + GL_Framebuffer_Enable(); + } #endif SDL_GL_SwapWindow(window); - GClipRect(0, 0, realwidth, realheight, NZCLIP_PLANE, FAR_ZCLIP_DEFAULT); + GL_GClipRect(0, 0, realwidth, realheight, NZCLIP_PLANE, FAR_ZCLIP_DEFAULT); // Sryder: We need to draw the final screen texture again into the other buffer in the original position so that // effects that want to take the old screen can do so after this - HWR_DrawScreenFinalTexture(realwidth, realheight); -} + // well we dont need it on native res it seems +#ifdef USE_FBO_OGL + if ((!I_CheckNativeRes() && !usefbo) || WipeInAction) +#else + if (!I_CheckNativeRes() || WipeInAction) +#endif + HWR_DrawScreenFinalTexture(realwidth, realheight, false); -EXPORT void HWRAPI(OglSdlSetPalette) (RGBA_t *palette) -{ - INT32 i; - - for (i = 0; i < 256; i++) - { - myPaletteData[i].s.red = palette[i].s.red; - myPaletteData[i].s.green = palette[i].s.green; - myPaletteData[i].s.blue = palette[i].s.blue; - myPaletteData[i].s.alpha = palette[i].s.alpha; - } - Flush(); +#if defined (__unix__) +#ifdef USE_FBO_OGL + xwaylandcrap = false; +#endif +#endif } #endif //HWRENDER diff --git a/src/sdl/ogl_sdl.h b/src/sdl/ogl_sdl.h index ad153da93..6d614cd22 100644 --- a/src/sdl/ogl_sdl.h +++ b/src/sdl/ogl_sdl.h @@ -21,12 +21,10 @@ boolean OglSdlSurface(INT32 w, INT32 h); void OglSdlFinishUpdate(boolean vidwait); +boolean VID_LoadOGLAPI(void); extern SDL_Renderer *renderer; extern SDL_GLContext sdlglcontext; extern Uint16 realwidth; extern Uint16 realheight; -#ifdef _CREATE_DLL_ -EXPORT void HWRAPI( OglSdlSetPalette ) (RGBA_t *palette); -#endif diff --git a/src/sdl/sdlmain.h b/src/sdl/sdlmain.h index 01edd866a..0ba8da762 100644 --- a/src/sdl/sdlmain.h +++ b/src/sdl/sdlmain.h @@ -59,38 +59,24 @@ typedef struct SDLJoyInfo_s /** \brief SDL info about controller 1 */ -extern SDLJoyInfo_t JoyInfo; +extern SDLJoyInfo_t JoyInfo[4]; //MAXSPLITSCREENPLAYERS /** \brief joystick axis deadzone */ #define SDL_JDEADZONE 153 #undef SDL_JDEADZONE -/** \brief SDL inof about controller 2 -*/ -extern SDLJoyInfo_t JoyInfo2; - -/** \brief SDL inof about controller 3 -*/ -extern SDLJoyInfo_t JoyInfo3; - -/** \brief SDL inof about controller 4 -*/ -extern SDLJoyInfo_t JoyInfo4; - void I_GetConsoleEvents(void); // So we can call this from i_video event loop -void I_ShutdownJoystick(void); -void I_ShutdownJoystick2(void); -void I_ShutdownJoystick3(void); -void I_ShutdownJoystick4(void); +void I_ShutdownJoystick(UINT8 index); // Cheat to get the device index for a game controller handle INT32 I_GetJoystickDeviceIndex(SDL_GameController *dev); // Quick thing to make SDL_JOYDEVICEADDED events less of an abomination -void I_UpdateJoystickDeviceIndices(INT32 player); +void I_UpdateJoystickDeviceIndex(UINT8 player); +void I_UpdateJoystickDeviceIndices(UINT8 excludePlayer); void I_GetConsoleEvents(void); diff --git a/src/sounds.c b/src/sounds.c index 51961b906..c3d92c853 100644 --- a/src/sounds.c +++ b/src/sounds.c @@ -14,7 +14,7 @@ #include "doomtype.h" #include "i_sound.h" #include "sounds.h" -#include "s_sound.h" //for soundprecaching +#include "s_sound.h" // for soundprecaching #include "m_argv.h" #include "r_defs.h" #include "r_things.h" diff --git a/src/sounds.h b/src/sounds.h index 6621dc6bf..a6128189d 100644 --- a/src/sounds.h +++ b/src/sounds.h @@ -14,6 +14,8 @@ #ifndef __SOUNDS__ #define __SOUNDS__ +#include "doomdef.h" + // Customisable sounds for Skins typedef enum { diff --git a/src/st_stuff.c b/src/st_stuff.c index 8b15e711a..30b8b5cf7 100644 --- a/src/st_stuff.c +++ b/src/st_stuff.c @@ -15,6 +15,7 @@ #include "doomdef.h" #include "g_game.h" +#include "g_input.h" #include "r_local.h" #include "p_local.h" #include "f_finale.h" @@ -731,7 +732,7 @@ static void ST_overlayDrawer(void) { if (renderisnewtic) { - LUAh_GameHUD(luahuddrawlist_game[stplyrnum]); + LUA_HUDHOOK(game, luahuddrawlist_game[stplyrnum]); } } @@ -773,10 +774,33 @@ static void ST_overlayDrawer(void) } else { - V_DrawString(2, BASEVIDHEIGHT-40, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF|V_YELLOWMAP, M_GetText("- SPECTATING -")); - V_DrawString(2, BASEVIDHEIGHT-30, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, itemtxt); - V_DrawString(2, BASEVIDHEIGHT-20, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, M_GetText("Accelerate - Float")); - V_DrawString(2, BASEVIDHEIGHT-10, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, M_GetText("Brake - Sink")); + if (cv_showdirectorhud.value) + { + V_DrawString(2, BASEVIDHEIGHT-50, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF|V_YELLOWMAP, M_GetText("- SPECTATING -")); + V_DrawString(2, BASEVIDHEIGHT-40, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, itemtxt); + V_DrawString(2, BASEVIDHEIGHT-30, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, M_GetText("Accelerate - Float")); + V_DrawString(2, BASEVIDHEIGHT-20, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, M_GetText("Brake - Sink")); + + char directortoggle[32] = {0}; + const char *item1 = gamecontrol[gc_director][0] != 0 ? G_KeynumToString(gamecontrol[gc_director][0]) : NULL; + const char *item2 = gamecontrol[gc_director][1] != 0 ? G_KeynumToString(gamecontrol[gc_director][1]) : NULL; + + if (item1 != NULL && item2 != NULL) + snprintf(directortoggle, 32, "%s/%s - Toggle Director", item1, item2); + else + snprintf(directortoggle, 32, "%s - Toggle Director", item1 != NULL ? item1 : item2 != NULL ? item2 : "Not Bound"); + + V_DrawString(2, BASEVIDHEIGHT-10, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, directortoggle); + + directortextactive = true; + } + else + { + V_DrawString(2, BASEVIDHEIGHT-40, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF|V_YELLOWMAP, M_GetText("- SPECTATING -")); + V_DrawString(2, BASEVIDHEIGHT-30, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, itemtxt); + V_DrawString(2, BASEVIDHEIGHT-20, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, M_GetText("Accelerate - Float")); + V_DrawString(2, BASEVIDHEIGHT-10, V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_HUDTRANSHALF, M_GetText("Brake - Sink")); + } } } } @@ -945,10 +969,6 @@ void ST_Drawer(void) } #endif - // Doom's status bar only updated if necessary. - // However, ours updates every frame regardless, so the "refresh" param was removed - //(void)refresh; - // force a set of the palette by using doPaletteStuff() if (vid.recalc) st_palette = -1; diff --git a/src/v_video.c b/src/v_video.c index fb5fb7a90..987a40a03 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -138,7 +138,11 @@ static boolean InitCube(void) #define diffcons(cv) (cv.value != atoi(cv.defaultvalue)) +#ifdef BACKWARDSCOMPATCORRECTION + doinggamma = (cv_globalgamma.value < 0); //dont mess up gamma when raising brightness pls +#else doinggamma = diffcons(cv_globalgamma); +#endif #define gammascale 8 globalgammamul = (cv_globalgamma.value ? ((255 - (gammascale*abs(cv_globalgamma.value)))/255.0) : 1.0); @@ -438,44 +442,21 @@ static void LoadPalette(const char *lumpname) pLocalPalette[i].s.alpha = 0xFF; // lerp of colour cubing! if you want, make it smoother yourself - if (Cubeapply) - V_CubeApply(&pLocalPalette[i].s.red, &pLocalPalette[i].s.green, &pLocalPalette[i].s.blue); + + if (!Cubeapply) + continue; + + V_CubeApply(&pLocalPalette[i].s.red, &pLocalPalette[i].s.green, &pLocalPalette[i].s.blue); } } -#ifdef BACKWARDSCOMPATCORRECTION -static boolean V_ShouldCube(void) -{ -#define diffcons(cv) (cv.value != atoi(cv.defaultvalue)) - return (diffcons(cv_globalsaturation) - || diffcons(cv_rhue) - || diffcons(cv_yhue) - || diffcons(cv_ghue) - || diffcons(cv_chue) - || diffcons(cv_bhue) - || diffcons(cv_mhue) - || diffcons(cv_rgamma) - || diffcons(cv_ygamma) - || diffcons(cv_ggamma) - || diffcons(cv_cgamma) - || diffcons(cv_bgamma) - || diffcons(cv_mgamma) - || (cv_globalgamma.value <= 0)); -#undef diffcons -} -#endif - void V_CubeApply(UINT8 *red, UINT8 *green, UINT8 *blue) { float working[4][3]; float linear; UINT8 q; - if (!Cubeapply -#ifdef BACKWARDSCOMPATCORRECTION - || !V_ShouldCube() -#endif - ) + if (!Cubeapply) return; linear = (*red/255.0); @@ -1112,7 +1093,7 @@ void V_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) if (x >= vid.width || y >= vid.height) return; // off the screen - + if (x < 0) { w += x; @@ -1126,7 +1107,7 @@ void V_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) if (w <= 0 || h <= 0) return; // zero width/height wouldn't draw anything - + if (x + w > vid.width) w = vid.width-x; if (y + h > vid.height) @@ -1149,7 +1130,7 @@ void V_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) } c &= 255; - + if (alphalevel) { const UINT8 *fadetable = ((UINT8 *)transtables + ((alphalevel-1)< 3 || view > splitscreen) return; + if (!player->postimgflags) + return; + if ((view == 1 && splitscreen == 1) || view >= 2) yoffset = viewheight; else @@ -3217,10 +3207,11 @@ void V_DoPostProcessor(INT32 view, postimg_t type, INT32 param) else xoffset = 0; - if (type == postimg_water) + UINT8 *tmpscr = screens[4]; + UINT8 *srcscr = screens[0]; + + if (player->postimgflags & POSTIMG_WATER) { - UINT8 *tmpscr = screens[4]; - UINT8 *srcscr = screens[0]; INT32 y; // Set disStart to a range from 0 to FINEANGLE, incrementing by 128 per tic angle_t disStart = (((leveltime-1)*128) + (rendertimefrac / (FRACUNIT/128))) & FINEMASK; @@ -3257,29 +3248,30 @@ void V_DoPostProcessor(INT32 view, postimg_t type, INT32 param) } /* - Unoptimized version - for (x = 0; x < vid.width*vid.bpp; x++) - { - newpix = (x + sine); + Unoptimized version + for (x = 0; x < vid.width*vid.bpp; x++) + { + newpix = (x + sine); - if (newpix < 0) - newpix = 0; - else if (newpix >= vid.width) - newpix = vid.width-1; + if (newpix < 0) + newpix = 0; + else if (newpix >= vid.width) + newpix = vid.width-1; + + tmpscr[y*vid.width + x] = srcscr[y*vid.width+newpix]; // *(transme + (srcscr[y*vid.width+x]<<8) + srcscr[y*vid.width+newpix]); + }*/ - tmpscr[y*vid.width + x] = srcscr[y*vid.width+newpix]; // *(transme + (srcscr[y*vid.width+x]<<8) + srcscr[y*vid.width+newpix]); - }*/ disStart += 22;//the offset into the displacement map, increment each game loop disStart &= FINEMASK; //clip it to FINEMASK } - VID_BlitLinearScreen(tmpscr+vid.width*vid.bpp*yoffset+xoffset, screens[0]+vid.width*vid.bpp*yoffset+xoffset, - viewwidth*vid.bpp, viewheight, vid.width*vid.bpp, vid.width); + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } - else if (type == postimg_motion) // Motion Blur! - { - UINT8 *tmpscr = screens[4]; - UINT8 *srcscr = screens[0]; + + /*if (player->postimgflags & POSTIMG_MOTION) // Motion Blur! + { INT32 x, y; // TODO: Add a postimg_param so that we can pick the translucency level... @@ -3288,30 +3280,12 @@ void V_DoPostProcessor(INT32 view, postimg_t type, INT32 param) for (y = yoffset; y < yoffset+viewheight; y++) { for (x = xoffset; x < xoffset+viewwidth; x++) - { - tmpscr[y*vid.width + x] - = colormaps[*(transme + (srcscr [(y*vid.width)+x ] <<8) + (tmpscr[(y*vid.width)+x]))]; - } + tmpscr[y*vid.width + x] = colormaps[*(transme + (srcscr [(y*vid.width)+x ] <<8) + (tmpscr[(y*vid.width)+x]))]; } - VID_BlitLinearScreen(tmpscr+vid.width*vid.bpp*yoffset+xoffset, screens[0]+vid.width*vid.bpp*yoffset+xoffset, - viewwidth*vid.bpp, viewheight, vid.width*vid.bpp, vid.width); - } - else if (type == postimg_flip) // Flip the screen upside-down - { - UINT8 *tmpscr = screens[4]; - UINT8 *srcscr = screens[0]; - INT32 y, y2; + }*/ - for (y = yoffset, y2 = yoffset+viewheight - 1; y < yoffset+viewheight; y++, y2--) - M_Memcpy(&tmpscr[(y2*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); - - VID_BlitLinearScreen(tmpscr+vid.width*vid.bpp*yoffset+xoffset, screens[0]+vid.width*vid.bpp*yoffset+xoffset, - viewwidth*vid.bpp, viewheight, vid.width*vid.bpp, vid.width); - } - else if (type == postimg_heat) // Heat wave + if (player->postimgflags & POSTIMG_HEAT) // Heat wave { - UINT8 *tmpscr = screens[4]; - UINT8 *srcscr = screens[0]; INT32 y; // Make sure table is built @@ -3352,40 +3326,53 @@ void V_DoPostProcessor(INT32 view, postimg_t type, INT32 param) heatindex[view] %= vid.height; } - VID_BlitLinearScreen(tmpscr+vid.width*vid.bpp*yoffset+xoffset, screens[0]+vid.width*vid.bpp*yoffset+xoffset, - viewwidth*vid.bpp, viewheight, vid.width*vid.bpp, vid.width); + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } - else if (type == postimg_mirror) // Flip the screen on the x axis + + if ((player->postimgflags & POSTIMG_FLIP) && !(player->postimgflags & POSTIMG_MIRROR)) // Flip the screen upside-down + { + INT32 y, y2; + + for (y = yoffset, y2 = yoffset+viewheight - 1; y < yoffset+viewheight; y++, y2--) + M_Memcpy(&tmpscr[(y2*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); + + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; + } + else if ((player->postimgflags & POSTIMG_MIRROR) && !(player->postimgflags & POSTIMG_FLIP)) // Flip the screen on the x axis { - UINT8 *tmpscr = screens[4]; - UINT8 *srcscr = screens[0]; INT32 y, x, x2; for (y = yoffset; y < yoffset+viewheight; y++) - { for (x = xoffset, x2 = xoffset+((viewwidth*vid.bpp)-1); x < xoffset+(viewwidth*vid.bpp); x++, x2--) tmpscr[y*vid.width + x2] = srcscr[y*vid.width + x]; - } - VID_BlitLinearScreen(tmpscr+vid.width*vid.bpp*yoffset+xoffset, screens[0]+vid.width*vid.bpp*yoffset+xoffset, - viewwidth*vid.bpp, viewheight, vid.width*vid.bpp, vid.width); + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } - else if (type == postimg_mirrorflip) // Flip the screen upside-down and on the x axis + else if ((player->postimgflags & POSTIMG_MIRROR) && (player->postimgflags & POSTIMG_FLIP)) // Flip the screen upside-down and on the x axis { - UINT8 *tmpscr = screens[4]; - UINT8 *srcscr = screens[0]; INT32 y, x; for (y = yoffset; y < yoffset + viewheight; y++) for (x = xoffset; x < xoffset + viewwidth; x++) tmpscr[((yoffset + viewheight - 1 - y) * vid.width) + xoffset + viewwidth - (x - xoffset) - 1] = srcscr[(y * vid.width) + x]; - VID_BlitLinearScreen(tmpscr+vid.width*vid.bpp*yoffset+xoffset, screens[0]+vid.width*vid.bpp*yoffset+xoffset, - viewwidth*vid.bpp, viewheight, vid.width*vid.bpp, vid.width); + UINT8 *tmp = tmpscr; + tmpscr = srcscr; + srcscr = tmp; } + + VID_BlitLinearScreen(srcscr+vid.width*vid.bpp*yoffset+xoffset, tmpscr+vid.width*vid.bpp*yoffset+xoffset, + viewwidth*vid.bpp, viewheight, vid.width*vid.bpp, vid.width); #endif } + // Taken from my videos-in-SRB2 project // Generates a color look-up table // which has up to 64 colors at each channel diff --git a/src/v_video.h b/src/v_video.h index bc1e8c546..dfab7dfde 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -182,6 +182,9 @@ void V_DrawFadeScreen(UINT16 color, UINT8 strength); void V_DrawFadeConsBack(INT32 plines); +// allow menu text to be displayed in lowercase +#define MENUCAPS (!cv_menucaps.value ? V_ALLOWLOWERCASE : 0) + // draw a single character void V_DrawCharacter(INT32 x, INT32 y, INT32 c, boolean lowercaseallowed); // draw a single character, but for the chat @@ -251,7 +254,9 @@ INT32 V_SubStringLengthToFit(const char *string, INT32 width, INT32 option); char V_GetSkincolorChar(INT32 color); -void V_DoPostProcessor(INT32 view, postimg_t type, INT32 param); +typedef struct player_s player_t; + +void V_DoPostProcessor(INT32 view, player_t *player, INT32 param); void V_DrawPatchFill(patch_t *pat); diff --git a/src/w_wad.c b/src/w_wad.c index a24686e28..ad506240d 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -1699,7 +1699,7 @@ void *W_CacheLumpName(const char *name, INT32 tag) #ifdef HWRENDER FUNCINLINE static ATTRINLINE void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, INT32 tag) { - GLPatch_t *grPatch; + GLPatch_t *glPatch; if (rendermode == render_soft || rendermode == render_none) return W_CacheLumpNumPwad(wad, lump, tag); @@ -1707,29 +1707,29 @@ FUNCINLINE static ATTRINLINE void *W_CachePatchNumPwad(UINT16 wad, UINT16 lump, if (!TestValidLump(wad, lump)) return NULL; - grPatch = HWR_GetCachedGLPatchPwad(wad, lump); + glPatch = HWR_GetCachedGLPatchPwad(wad, lump); - if (grPatch->mipmap->data) + if (glPatch->mipmap->data) { if (tag == PU_CACHE) tag = PU_HWRCACHE; - Z_ChangeTag(grPatch->mipmap->data, tag); + Z_ChangeTag(glPatch->mipmap->data, tag); } else { patch_t *ptr = NULL; - // Only load the patch if we haven't initialised the grPatch yet - if (grPatch->mipmap->width == 0) - ptr = W_CacheLumpNumPwad(grPatch->wadnum, grPatch->lumpnum, PU_STATIC); + // Only load the patch if we haven't initialised the glPatch yet + if (glPatch->mipmap->width == 0) + ptr = W_CacheLumpNumPwad(glPatch->wadnum, glPatch->lumpnum, PU_STATIC); // Run HWR_MakePatch in all cases, to recalculate some things - HWR_MakePatch(ptr, grPatch, grPatch->mipmap, false); + HWR_MakePatch(ptr, glPatch, glPatch->mipmap, false); Z_Free(ptr); } // return GLPatch_t, which can be casted to (patch_t) with valid patch header info - return (void *)grPatch; + return (void *)glPatch; } void *W_CachePatchNum(lumpnum_t lumpnum, INT32 tag) @@ -2120,6 +2120,225 @@ int W_VerifyNMUSlumps(const char *filename) return W_VerifyFile(filename, NMUSlist, false); } +static int W_NameStartsWith(const char *name, lumpchecklist_t *checklist) +{ + size_t j; + for (j = 0; checklist[j].len && checklist[j].name; ++j) + { + if (strncasecmp(name, checklist[j].name, checklist[j].len) == 0) + return true; + } + return false; +} + +// Checks if file contains at least one lump which name starts with one of strings in checklist +static int W_CheckWADContains(FILE *fp, lumpchecklist_t *checklist) +{ + size_t i, j; + // if we're here it's a WAD file + wadinfo_t header; + filelump_t lumpinfo; + + // read the header + if (fread(&header, 1, sizeof header, fp) == sizeof header + && header.numlumps < INT16_MAX + && strncmp(header.identification, "ZWAD", 4) + && strncmp(header.identification, "IWAD", 4) + && strncmp(header.identification, "PWAD", 4) + && strncmp(header.identification, "SDLL", 4)) + { + return true; + } + + header.numlumps = LONG(header.numlumps); + header.infotableofs = LONG(header.infotableofs); + + // let seek to the lumpinfo list + if (fseek(fp, header.infotableofs, SEEK_SET) == -1) + return true; + + for (i = 0; i < header.numlumps; i++) + { + // fill in lumpinfo for this wad file directory + if (fread(&lumpinfo, sizeof (lumpinfo), 1 , fp) != 1) + return -1; + + lumpinfo.filepos = LONG(lumpinfo.filepos); + lumpinfo.size = LONG(lumpinfo.size); + + if (lumpinfo.size == 0) + continue; + + for (j = 0; j < NUMSPRITES; j++) + if (!strncmp(lumpinfo.name, sprnames[j], 4)) // Sprites + continue; + + if (W_NameStartsWith(lumpinfo.name, checklist)) + return true; + } + return false; +} + +static int W_CheckPK3Contains(FILE *fp, lumpchecklist_t *checklist) +{ + zend_t zend; + zlentry_t zlentry; + + long file_size;/* size of zip file */ + long data_size;/* size of data inside zip file */ + + UINT16 numlumps; + size_t i; + + char pat_central[] = {0x50, 0x4b, 0x01, 0x02, 0x00}; + char pat_end[] = {0x50, 0x4b, 0x05, 0x06, 0x00}; + + char lumpname[9]; + + // Haha the ResGetLumpsZip function doesn't + // check for file errors, so neither will I. + + // Central directory bullshit + + fseek(fp, 0, SEEK_END); + file_size = ftell(fp); + + if (!ResFindSignature(fp, pat_end, max(0, ftell(fp) - (22 + 65536)))) + return true; + + fseek(fp, -4, SEEK_CUR); + if (fread(&zend, 1, sizeof zend, fp) < sizeof zend) + return true; + + data_size = sizeof zend; + + numlumps = SHORT(zend.entries); + + fseek(fp, LONG(zend.cdiroffset), SEEK_SET); + + char *cdir = (char*)(malloc(LONG(zend.cdirsize))); + + if (fread(cdir, 1, LONG(zend.cdirsize), fp) < (UINT32)(LONG(zend.cdirsize))) + return true; + + size_t offset = 0; + + for (i = 0; i < numlumps; i++) + { + zentry_t *zentry = (zentry_t*)(cdir + offset); + char* fullname; + char* trimname; + char* dotpos; + + if (memcmp(zentry->signature, pat_central, 4) != 0) + return false; + + fullname = (char*)(malloc(SHORT(zentry->namelen) + 1)); + strlcpy(fullname, (char*)(zentry + 1), SHORT(zentry->namelen) + 1); + + // Strip away file address and extension for the 8char name. + if ((trimname = strrchr(fullname, '/')) != 0) + trimname++; + else + trimname = fullname; // Care taken for root files. + + if (*trimname) // Ignore directories, well kinda + { + if ((dotpos = strrchr(trimname, '.')) == 0) + dotpos = fullname + strlen(fullname); // Watch for files without extension. + + memset(lumpname, '\0', 9); // Making sure they're initialized to 0. Is it necessary? + strncpy(lumpname, trimname, min(8, dotpos - trimname)); + + if (W_NameStartsWith(lumpname, checklist)) + return true; + } + + if (W_NameStartsWith(fullname, checklist)) + return true; + + free(fullname); + + offset += sizeof *zentry + SHORT(zentry->namelen) + SHORT(zentry->xtralen) + SHORT(zentry->commlen); + + data_size += + sizeof *zentry + SHORT(zentry->namelen) + SHORT(zentry->xtralen) + SHORT(zentry->commlen); + + if (fseek(fp, LONG(zentry->offset), SEEK_SET) != 0) + return false; + + if (fread(&zlentry, 1, sizeof(zlentry_t), fp) < sizeof (zlentry_t)) + return false; + + data_size += + sizeof zlentry + SHORT(zlentry.namelen) + SHORT(zlentry.xtralen) + LONG(zlentry.compsize); + } + + free(cdir); + + if (data_size < file_size) + { + const char * error = "ZIP file has holes (%ld extra bytes)\n"; + CONS_Alert(CONS_ERROR, error, (file_size - data_size)); + return -1; + } + else if (data_size > file_size) + { + const char * error = "Reported size of ZIP file contents exceeds file size (%ld extra bytes)\n"; + CONS_Alert(CONS_ERROR, error, (data_size - file_size)); + return -1; + } + else + { + return false; + } +} + +static int W_CheckFileContains(const char *filename, lumpchecklist_t *checklist) +{ + FILE *handle; + int contains = false; + + if (!checklist) + I_Error("No checklist for %s\n", filename); + // open wad file + if ((handle = W_OpenWadFile(&filename, false)) == NULL) + return -1; + + if (stricmp(&filename[strlen(filename) - 4], ".pk3") == 0) + contains = W_CheckPK3Contains(handle, checklist); + else + { + // detect wad file by the absence of the other supported extensions + if (stricmp(&filename[strlen(filename) - 4], ".soc") + && stricmp(&filename[strlen(filename) - 4], ".lua")) + { + contains = W_CheckWADContains(handle, checklist); + } + } + fclose(handle); + return contains; +} + +int W_CheckPostLoadList(const char *filename) +{ + static lumpchecklist_t postloadlist[] = + { + {"Lua/", 4}, + {"SOC/", 4}, + {"Skins/", 6}, + {"S_SKIN", 6}, + {"LUA_", 4}, + {"SOC_", 4}, + {"MAINCFG", 7}, + {"OBJCTCFG", 8}, + {"MAP", 3}, + + {NULL, 0}, + }; + return W_CheckFileContains(filename, postloadlist); +} + /** \brief Generates a virtual resource used for level data loading. * * \param lumpnum_t reference diff --git a/src/w_wad.h b/src/w_wad.h index 4e84ea0e4..fd2038db2 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -226,4 +226,6 @@ void W_VerifyFileMD5(UINT16 wadfilenum, const char *matchmd5); int W_VerifyNMUSlumps(const char *filename); +int W_CheckPostLoadList(const char *filename); + #endif // __W_WAD__ diff --git a/src/y_inter.c b/src/y_inter.c index b62566e0a..61f4a069b 100644 --- a/src/y_inter.c +++ b/src/y_inter.c @@ -57,26 +57,6 @@ typedef struct typedef union { - /*struct - { - char passed1[21]; // KNUCKLES GOT / CRAWLA HONCHO - char passed2[16]; // THROUGH THE ACT / PASSED THE ACT - INT32 passedx1; - INT32 passedx2; - - y_bonus_t bonuses[4]; - patch_t *bonuspatches[4]; - - SINT8 gotperfbonus; // Used for visitation flags. - - UINT32 score, total; // fake score, total - UINT32 tics; // time - - patch_t *ttlnum; // act number being displayed - patch_t *ptotal; // TOTAL - UINT8 gotlife; // Number of extra lives obtained - } coop;*/ - struct { UINT8 *color[MAXPLAYERS]; // Winner's color # @@ -388,7 +368,7 @@ void Y_IntermissionDrawer(void) if (cv_betainterscreen.value == 1 #ifdef HWRENDER - || (rendermode == render_opengl && cv_grscreentextures.value != 2) // use the neato kart bg for intermission on disabled screen textures + || (rendermode == render_opengl && cv_glscreentextures.value != 2) // use the neato kart bg for intermission on disabled screen textures #endif ) V_DrawPatchFill(bgtile); // use the neato kart bg for intermission on disabled screen textures @@ -463,14 +443,12 @@ void Y_IntermissionDrawer(void) for (i = 0; i < data.match.numplayers; i++) { - boolean dojitter = data.match.jitter[data.match.num[i]]; - data.match.jitter[data.match.num[i]] = 0; - if (data.match.num[i] != MAXPLAYERS && playeringame[data.match.num[i]] && !players[data.match.num[i]].spectator) { char strtime[MAXPLAYERNAME+1]; - if (dojitter) + // Apply the jitter offset (later reversed) + if (data.match.jitter[data.match.num[i]] > 0) y--; V_DrawCenteredString(x+6, y, 0, va("%d", data.match.pos[i])); @@ -559,7 +537,7 @@ void Y_IntermissionDrawer(void) } } - if (dojitter) + if (data.match.jitter[data.match.num[i]] > 0) y++; } else @@ -614,7 +592,7 @@ void Y_IntermissionDrawer(void) if (renderisnewtic) { LUA_HUD_ClearDrawList(luahuddrawlist_intermission); - LUAh_IntermissionHUD(luahuddrawlist_intermission); + LUA_HUDHOOK(intermission, luahuddrawlist_intermission); } LUA_HUD_DrawList(luahuddrawlist_intermission); } @@ -633,18 +611,20 @@ void Y_Ticker(void) { INT32 axis = JoyAxis(AXISLOOKBACK, 1); - if (demo.savemode == DSM_NOTSAVING && (InputDown(gc_lookback, 1) || (cv_usejoystick.value && axis > 0))) + if (demo.savemode == DSM_NOTSAVING && (InputDown(gc_lookback, 1) || (cv_usejoystick[0].value && axis > 0))) demo.savemode = DSM_TITLEENTRY; if (demo.savemode == DSM_WILLSAVE || demo.savemode == DSM_WILLAUTOSAVE) G_SaveDemo(); + else + G_ResetDemoRecording(); } // Check for pause or menu up in single player if (paused || P_AutoPause()) return; - LUAh_IntermissionThinker(); + LUA_HookVoid(HOOK(IntermissionThinker)); intertic++; @@ -666,8 +646,16 @@ void Y_Ticker(void) return; } - if (intertic < TICRATE || intertic & 1 || endtic != -1) + if (intertic < TICRATE || endtic != -1) + { return; + } + + if (data.match.rankingsmode && intertic & 1) + { + memset(data.match.jitter, 0, sizeof (data.match.jitter)); + return; + } if (intertype == int_race || intertype == int_match) { @@ -1227,7 +1215,7 @@ void Y_VoteDrawer(void) if (renderisnewtic) { LUA_HUD_ClearDrawList(luahuddrawlist_vote); - LUAh_VoteHUD(luahuddrawlist_vote); + LUA_HUDHOOK(vote, luahuddrawlist_vote); } LUA_HUD_DrawList(luahuddrawlist_vote); } @@ -1274,7 +1262,7 @@ void Y_VoteTicker(void) if (paused || P_AutoPause() || !voteclient.loaded) return; - LUAh_VoteThinker(); + LUA_HOOK(VoteThinker); votetic++;