diff --git a/src/.gitignore b/src/.gitignore index d1d328f14..156f6f65f 100644 --- a/src/.gitignore +++ b/src/.gitignore @@ -1,4 +1,3 @@ /cscope.out -/srb2wii *.json *.idx diff --git a/src/Makefile b/src/Makefile index 0abc7c318..b6077ba6c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -68,7 +68,6 @@ ALL_SYSTEMS=\ LINUX64\ MINGW64\ HAIKU\ - DUMMY\ MINGW\ UNIX\ LINUX\ @@ -158,17 +157,6 @@ endif include Makefile.cfg -ifdef DUMMY -NOPNG=1 -NOZLIB=1 -NONET=1 -NOHW=1 -NOIPX=1 -EXENAME?=srb2dummy -OBJS=$(OBJDIR)/i_video.o -LIBS=-lm -endif - ifdef HAIKU NOIPX=1 ifndef NONET @@ -610,10 +598,6 @@ ifdef SDL all: pre-build $(BIN)/$(EXENAME) endif -ifdef DUMMY -all: $(BIN)/$(EXENAME) -endif - cleandep: $(REMOVE) $(OBJDIR)/depend.dep $(REMOVE) comptime.h @@ -625,7 +609,7 @@ else -$(.)../comptime.sh . endif -clean: +clean: cleandep $(REMOVE) *~ *.flc $(REMOVE) $(OBJDIR)/*.o @@ -734,9 +718,7 @@ endif #dependecy made by gcc itself ! $(OBJS): -ifndef DUMMY -include $(OBJDIR)/depend.dep -endif $(OBJDIR)/depend.dep: @echo "Creating dependency file, depend.dep" diff --git a/src/Makefile.cfg b/src/Makefile.cfg index e4ba0c1ab..2e407ac3f 100644 --- a/src/Makefile.cfg +++ b/src/Makefile.cfg @@ -489,7 +489,6 @@ ifndef CYGWIN32 ifndef MINGW ifndef MINGW64 ifndef SDL -ifndef DUMMY $(error No interface or platform flag defined) endif endif @@ -497,7 +496,6 @@ endif endif endif endif -endif #determine the interface directory (where you put all i_*.c) i_net_o=$(OBJDIR)/i_net.o @@ -522,11 +520,6 @@ UPX_OPTS+=-q endif #Interface Setup -ifdef DUMMY - INTERFACE=dummy - OBJDIR:=$(OBJDIR)/dummy - BIN:=$(BIN)/dummy -else ifdef LINUX SDL=1 ifdef LINUX64 @@ -573,7 +566,6 @@ endif endif endif endif -endif ifdef ARCHNAME OBJDIR:=$(OBJDIR)/$(ARCHNAME) @@ -588,7 +580,6 @@ ifdef SDL OBJDIR:=$(OBJDIR)/SDL endif -ifndef DUMMY ifdef DEBUGMODE OBJDIR:=$(OBJDIR)/Debug BIN:=$(BIN)/Debug @@ -596,4 +587,3 @@ else OBJDIR:=$(OBJDIR)/Release BIN:=$(BIN)/Release endif -endif diff --git a/src/command.c b/src/command.c index eb38a0f6a..e7dd9cc01 100644 --- a/src/command.c +++ b/src/command.c @@ -1984,7 +1984,7 @@ static boolean CV_FilterJoyAxisVars(consvar_t *v, const char *valstr) return true; } -// Block the Xbox DInput default axes and reset to the current defaults +// Block the Xbox DInput default axes and reset to the current defaults static boolean CV_FilterJoyAxisVars2(consvar_t *v, const char *valstr) { if (!stricmp(v->name, "joyaxis_turn") && !stricmp(valstr, "X-Axis")) @@ -2041,15 +2041,6 @@ static boolean CV_FilterVarByVersion(consvar_t *v, const char *valstr) if (GETMAJOREXECVERSION(cv_execversion.value) < 2) // 2 = 1.0.2 { -#if 0 - // We don't have changed saved cvars yet - if (!stricmp(v->name, "alwaysmlook") - || !stricmp(v->name, "alwaysmlook2") - || !stricmp(v->name, "mousemove") - || !stricmp(v->name, "mousemove2")) - return false; -#endif - // axis defaults were changed to be friendly to 360 controllers // if ALL axis settings are defaults, then change them to new values if (!CV_FilterJoyAxisVars(v, valstr)) diff --git a/src/console.c b/src/console.c index 7f417625b..8c1824456 100644 --- a/src/console.c +++ b/src/console.c @@ -275,29 +275,28 @@ void CON_SetupBackColormap(void) switch (cons_backcolor.value) { - case 0: palindex = 15; break; // White - case 1: palindex = 31; break; // Gray - case 2: palindex = 47; break; // Sepia - case 3: palindex = 63; break; // Brown - case 4: palindex = 150; shift = 7; break; // Pink - case 5: palindex = 127; shift = 7; break; // Raspberry - case 6: palindex = 143; break; // Red - case 7: palindex = 86; shift = 7; break; // Creamsicle - case 8: palindex = 95; break; // Orange - case 9: palindex = 119; shift = 7; break; // Gold - case 10: palindex = 111; break; // Yellow - case 11: palindex = 191; shift = 7; break; // Emerald - case 12: palindex = 175; break; // Green - case 13: palindex = 219; break; // Cyan - case 14: palindex = 207; shift = 7; break; // Steel - case 15: palindex = 230; shift = 7; break; // Periwinkle - case 16: palindex = 239; break; // Blue - case 17: palindex = 199; shift = 7; break; // Purple - case 18: palindex = 255; shift = 7; break; // Lavender + case 0: palindex = 15; break; // White + case 1: palindex = 31; break; // Gray + case 2: palindex = 47; break; // Sepia + case 3: palindex = 63; break; // Brown + case 4: palindex = 150; shift = 7; break; // Pink + case 5: palindex = 127; shift = 7; break; // Raspberry + case 6: palindex = 143; break; // Red + case 7: palindex = 86; shift = 7; break; // Creamsicle + case 8: palindex = 95; break; // Orange + case 9: palindex = 119; shift = 7; break; // Gold + case 10: palindex = 111; break; // Yellow + case 11: palindex = 191; shift = 7; break; // Emerald + case 12: palindex = 175; break; // Green + case 13: palindex = 219; break; // Cyan + case 14: palindex = 207; shift = 7; break; // Steel + case 15: palindex = 230; shift = 7; break; // Periwinkle + case 16: palindex = 239; break; // Blue + case 17: palindex = 199; shift = 7; break; // Purple + case 18: palindex = 255; shift = 7; break; // Lavender // Default green default: palindex = 175; break; - -} + } // setup background colormap for (i = 0, j = 0; i < 768; i += 3, j++) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 6b496c0e7..9625934fc 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -238,6 +238,18 @@ static boolean UseLocalDelay(void) return (cv_mindelay.value || (server && !server_lagless)); } +#ifdef SATURNPAK +static inline boolean UseSaturnSynch(INT32 node) +{ + return (is_client_saturn[node] && cv_gamestateattempts.value); +} + +static inline boolean UseVanillaSynch(INT32 node) +{ + return (!UseSaturnSynch(node) && cv_resynchattempts.value); +} +#endif + static inline void *G_DcpyTiccmd(void* dest, const ticcmd_t* src, const size_t n) { const size_t d = n / sizeof(ticcmd_t); @@ -2278,7 +2290,7 @@ static void M_ConfirmConnect(event_t *ev) #endif } -static void AbortConnection(void) +void CL_AbortConnection(void) { #ifdef HAVE_CURL CURLAbortFile(); @@ -2291,7 +2303,6 @@ static void AbortConnection(void) cl_mode = CL_ABORTED; } - static boolean CL_FinishedFileList(void) { INT32 i; @@ -2304,7 +2315,7 @@ static boolean CL_FinishedFileList(void) } else if (i == 3) // too many files { - AbortConnection(); + CL_AbortConnection(); M_StartMessage(M_GetText( "You have too many WAD files loaded\n" "to add ones the server is using.\n" @@ -2315,7 +2326,7 @@ static boolean CL_FinishedFileList(void) } else if (i == 2) // cannot join for some reason { - AbortConnection(); + CL_AbortConnection(); M_StartMessage(M_GetText( "You have the wrong addons loaded.\n\n" "To play on this server, restart\n" @@ -2352,7 +2363,7 @@ static boolean CL_FinishedFileList(void) { if (!CL_CheckDownloadable()) // nope! { - AbortConnection(); + CL_AbortConnection(); M_StartMessage(M_GetText( "An error occured when trying to\n" "download missing addons.\n" @@ -2617,7 +2628,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { CONS_Printf(M_GetText("Legacy downloader request packet failed.\n")); CONS_Printf(M_GetText("Network game synchronization aborted.\n")); - AbortConnection(); + CL_AbortConnection(); M_StartMessage(M_GetText( "The direct download encountered an error.\n" "See the logfile for more info.\n" @@ -2644,7 +2655,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic { CONS_Printf("%d minute wait time exceeded.\n", cv_connectawaittime.value); CONS_Printf(M_GetText("Network game synchronization aborted.\n")); - AbortConnection(); + CL_AbortConnection(); M_StartMessage(va( "%d minute wait time exceeded.\n" "You may retry connection.\n" @@ -2715,7 +2726,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic if (!modeattacking && (key == KEY_ESCAPE || key == KEY_JOY1+1 || cl_mode == CL_ABORTED)) { CONS_Printf(M_GetText("Network game synchronization aborted.\n")); - AbortConnection(); + CL_AbortConnection(); return false; } @@ -3302,36 +3313,6 @@ void CL_RemovePlayer(INT32 playernum, INT32 reason) if (gametype == GT_CTF) P_PlayerFlagBurst(&players[playernum], false); // Don't take the flag with you! - // If in a special stage, redistribute the player's rings across - // the remaining players. - if (G_IsSpecialStage(gamemap)) - { - INT32 i, count, increment, rings; - - for (i = 0, count = 0; i < MAXPLAYERS; i++) - { - if (playeringame[i]) - count++; - } - - count--; - rings = players[playernum].health - 1; - increment = rings/count; - - for (i = 0; i < MAXPLAYERS; i++) - { - if (playeringame[i] && i != playernum) - { - if (rings < increment) - P_GivePlayerRings(&players[i], rings); - else - P_GivePlayerRings(&players[i], increment); - - rings -= increment; - } - } - } - LUA_HookPlayerQuit(&players[playernum], reason); // Lua hook for player quitting if (playernum == displayplayers[0] && !demo.playback) @@ -3973,7 +3954,7 @@ static void Got_KickCmd(UINT8 **p, INT32 playernum) #ifdef DUMPCONSISTENCY if (msg == KICK_MSG_CON_FAIL) SV_SavedGame(); #endif - AbortConnection(); + CL_AbortConnection(); if (msg == KICK_MSG_CON_FAIL) M_StartMessage(M_GetText("Server closed connection\n(Synch failure)\nPress ESC\n"), NULL, MM_NOTHING); @@ -5416,25 +5397,26 @@ static void HandlePacketFromPlayer(SINT8 node) if (gamestate == GS_LEVEL && (realstart > gametic - TICQUEUE+1 && realstart <= gametic) && consistancy[realstart%TICQUEUE] != SHORT(netbuffer->u.clientpak.consistancy) - && (!is_client_saturn[node] || (!resendingsavegame[node] && savegameresendcooldown[node] <= I_GetTime() && !SV_ResendingSavegameToAnyone()))) + && (!UseSaturnSynch(node) || (!resendingsavegame[node] && savegameresendcooldown[node] <= I_GetTime() && !SV_ResendingSavegameToAnyone()))) { + resendingsavegame[node] = false; // reset this before just in case + // Check if a client is saturn before sending ANYTHING! // this way we only send stuff to clients we know can use the gamestate resend // and dont have to wait for a response from clients that never would send a response back - if (is_client_saturn[node]) + if (UseSaturnSynch(node)) { // Tell the client we are about to resend them the gamestate netbuffer->packettype = PT_WILLRESENDGAMESTATE; HSendPacket(node, true, 0, 0); resendingsavegame[node] = true; } - else + else if (UseVanillaSynch(node)) { SV_RequireResynch(node); - resendingsavegame[node] = false; } - if ((!is_client_saturn[node] && (cv_resynchattempts.value && resynch_score[node] <= (unsigned)cv_resynchattempts.value*250)) || (is_client_saturn[node] && (gamestate_resend_counter[node] < cv_gamestateattempts.value))) + if ((UseVanillaSynch(node) && (resynch_score[node] <= (unsigned)cv_resynchattempts.value*250)) || (UseSaturnSynch(node) && (gamestate_resend_counter[node] < cv_gamestateattempts.value))) { if (is_client_saturn[node] && resendingsavegame[node]) { diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 65884362b..6202c8c52 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -635,6 +635,9 @@ void CL_RemovePlayer(INT32 playernum, INT32 reason); void CL_QueryServerList(msg_server_t *list); void CL_UpdateServerList(void); void CL_TimeoutServerList(void); + +void CL_AbortConnection(void); + // Is there a game running boolean Playing(void); diff --git a/src/d_main.c b/src/d_main.c index fd92739b9..728a1a760 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -472,6 +472,7 @@ static boolean D_Display(void) F_TitleScreenDrawer(); if (wipe) wipedefindex = wipe_titlescreen_toblack; + HU_DrawSongCredits(); break; case GS_WAITINGPLAYERS: diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 69df66500..5b8a8c18b 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -211,14 +211,6 @@ void SendWeaponPref4(void); static CV_PossibleValue_t usemouse_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Force"}, {0, NULL}}; -#ifdef LJOYSTICK -static CV_PossibleValue_t joyport_cons_t[] = {{1, "/dev/js0"}, {2, "/dev/js1"}, {3, "/dev/js2"}, - {4, "/dev/js3"}, {0, NULL}}; -#else -// accept whatever value - it is in fact the joystick device number -#define usejoystick_cons_t NULL -#endif - static CV_PossibleValue_t autobalance_cons_t[] = {{0, "MIN"}, {4, "MAX"}, {0, NULL}}; static CV_PossibleValue_t teamscramble_cons_t[] = {{0, "Off"}, {1, "Random"}, {2, "Points"}, {0, NULL}}; @@ -307,7 +299,7 @@ consvar_t cv_mouseturn = {"mouseturn", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, consvar_t cv_laglesscam = {"lagless_camera", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_verticallook[MAXSPLITSCREENPLAYERS] = { - {"verticallook", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"verticallook", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, {"verticallook2", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, {"verticallook3", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, {"verticallook4", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL} @@ -315,28 +307,26 @@ consvar_t cv_verticallook[MAXSPLITSCREENPLAYERS] = { #if defined(HAVE_SDL) || defined(_WINDOWS) //joystick 1 and 2 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} + {"use_joystick", "1", CV_SAVE|CV_CALL, NULL, I_InitJoystick1, 0, NULL, NULL, 0, 0, NULL}, + {"use_joystick2", "2", CV_SAVE|CV_CALL, NULL, I_InitJoystick2, 0, NULL, NULL, 0, 0, NULL}, + {"use_joystick3", "3", CV_SAVE|CV_CALL, NULL, I_InitJoystick3, 0, NULL, NULL, 0, 0, NULL}, + {"use_joystick4", "4", CV_SAVE|CV_CALL, NULL, I_InitJoystick4, 0, NULL, NULL, 0, 0, NULL} }; #endif -#if (defined (LJOYSTICK) || defined (HAVE_SDL)) -#ifdef LJOYSTICK -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 +#if defined (HAVE_SDL) consvar_t cv_joyscale[MAXSPLITSCREENPLAYERS] = { - {"joyscale", "1", CV_SAVE|CV_CALL, NULL, I_JoyScale, 0, NULL, NULL, 0, 0, NULL}, + {"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[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} +consvar_t cv_joyscale[MAXSPLITSCREENPLAYERS] = { //Alam: Dummy for save + {"joyscale", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyscale2", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyscale3", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyscale4", "1", CV_SAVE|CV_HIDEN, NULL, NULL, 0, NULL, NULL, 0, 0, NULL} }; #endif @@ -344,19 +334,6 @@ consvar_t cv_matchboxes = {"matchboxes", "Normal", CV_NETVAR|CV_CHEAT|CV_NOSHOWH consvar_t cv_specialrings = {"specialrings", "On", CV_NETVAR|CV_NOSHOWHELP, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_powerstones = {"powerstones", "On", CV_NETVAR|CV_NOSHOWHELP, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -/*consvar_t cv_recycler = {"tv_recycler", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_teleporters = {"tv_teleporter", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_superring = {"tv_superring", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_supersneakers = {"tv_supersneaker", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_invincibility = {"tv_invincibility", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_jumpshield = {"tv_jumpshield", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_watershield = {"tv_watershield", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ringshield = {"tv_ringshield", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_forceshield = {"tv_forceshield", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_bombshield = {"tv_bombshield", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_1up = {"tv_1up", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_eggmanbox = {"tv_eggman", "5", CV_NETVAR|CV_CHEAT, chances_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};*/ - // SRB2kart consvar_t cv_sneaker = {"sneaker", "On", CV_NETVAR|CV_CHEAT, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_rocketsneaker = {"rocketsneaker", "On", CV_NETVAR|CV_CHEAT, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -472,7 +449,6 @@ consvar_t cv_killingdead = {"killingdead", "Off", CV_NETVAR|CV_NOSHOWHELP, CV_On consvar_t cv_netstat = {"netstat", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // show bandwidth statistics static CV_PossibleValue_t nettimeout_cons_t[] = {{TICRATE/7, "MIN"}, {60*TICRATE, "MAX"}, {0, NULL}}; consvar_t cv_nettimeout = {"nettimeout", "210", CV_CALL|CV_SAVE, nettimeout_cons_t, NetTimeout_OnChange, 0, NULL, NULL, 0, 0, NULL}; -//static CV_PossibleValue_t jointimeout_cons_t[] = {{5*TICRATE, "MIN"}, {60*TICRATE, "MAX"}, {0, NULL}}; consvar_t cv_jointimeout = {"jointimeout", "210", CV_CALL|CV_SAVE, nettimeout_cons_t, JoinTimeout_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_maxping = {"maxdelay", "20", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -992,7 +968,18 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_showfocuslost); CV_RegisterVar(&cv_pauseifunfocused); + // filesrch.c + CV_RegisterVar(&cv_addons_option); + CV_RegisterVar(&cv_addons_folder); + CV_RegisterVar(&cv_addons_md5); + CV_RegisterVar(&cv_addons_showall); + CV_RegisterVar(&cv_addons_search_type); + CV_RegisterVar(&cv_addons_search_case); + // g_input.c + CV_RegisterVar(&cv_controlperkey); + CV_RegisterVar(&cv_turnsmooth); + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { CV_RegisterVar(&cv_turnaxis[i]); @@ -1010,45 +997,17 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_custom3axis[i]); CV_RegisterVar(&cv_xdeadzone[i]); CV_RegisterVar(&cv_ydeadzone[i]); - } - // filesrch.c - CV_RegisterVar(&cv_addons_option); - CV_RegisterVar(&cv_addons_folder); - CV_RegisterVar(&cv_addons_md5); - CV_RegisterVar(&cv_addons_showall); - CV_RegisterVar(&cv_addons_search_type); - CV_RegisterVar(&cv_addons_search_case); - - CV_RegisterVar(&cv_controlperkey); - CV_RegisterVar(&cv_turnsmooth); - - for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) - { + CV_RegisterVar(&cv_usejoystick[i]); + CV_RegisterVar(&cv_joyscale[i]); CV_RegisterVar(&cv_rumble[i]); CV_RegisterVar(&cv_gamepadled[i]); - CV_RegisterVar(&cv_ledpowerup[i]); } CV_RegisterVar(&cv_usemouse); CV_RegisterVar(&cv_invertmouse); CV_RegisterVar(&cv_mousesens); CV_RegisterVar(&cv_mouseysens); - //CV_RegisterVar(&cv_mousemove); - - for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) - { - CV_RegisterVar(&cv_usejoystick[i]); - } -#ifdef LJOYSTICK - CV_RegisterVar(&cv_joyport); - CV_RegisterVar(&cv_joyport2); -#endif - - for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) - { - CV_RegisterVar(&cv_joyscale[i]); - } // s_sound.c CV_RegisterVar(&cv_soundvolume); @@ -1097,6 +1056,7 @@ void D_RegisterClientCommands(void) } CV_RegisterVar(&cv_demodateformat); + CV_RegisterVar(&cv_showspecstuff); // ingame object placing COM_AddCommand("objectplace", Command_ObjectPlace_f); @@ -1131,8 +1091,6 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_discordasks); #endif - CV_RegisterVar(&cv_showspecstuff); - COM_AddCommand("listskins", Command_ListSkins); COM_AddCommand("skinsearch", Command_SkinSearch); } @@ -1441,6 +1399,7 @@ static void SetPlayerName(INT32 playernum, char *newname) else { CONS_Printf(M_GetText("Player %d sent a bad name change\n"), playernum+1); + if (server && netgame) { SendKick(playernum, KICK_MSG_CON_FAIL); @@ -1798,24 +1757,8 @@ static void SendNameAndColor3(void) if ((foundskin = R_SkinAvailable(cv_skin3.string)) != -1) { - //boolean notsame; - cv_skin3.value = foundskin; - - //notsame = (cv_skin3.value != players[thirdplaya].skin); - SetPlayerSkin(thirdplaya, cv_skin3.string); - - // SRB2Kart - /*if (notsame) - { - CV_StealthSetValue(&cv_playercolor3, skins[players[thirdplaya].skin].prefcolor); - - players[thirdplaya].skincolor = (cv_playercolor3.value&0x3F) % MAXSKINCOLORS; - - if (players[thirdplaya].mo) - players[thirdplaya].mo->color = players[thirdplaya].skincolor; - }*/ } else { @@ -2127,6 +2070,7 @@ void D_SendPlayerConfig(void) SendNameAndColor3(); if (splitscreen > 2) SendNameAndColor4(); + SendWeaponPref(); if (splitscreen) SendWeaponPref2(); @@ -2150,7 +2094,7 @@ static INT32 LookupPlayer(const char *s) if (*s == '0')/* clever way to bypass atoi */ return 0; - if (( playernum = atoi(s) )) + if ((playernum = atoi(s))) { playernum = max(min(playernum, MAXPLAYERS-1), 0);/* not out of range */ return playernum; @@ -2231,8 +2175,7 @@ static void Command_View_f(void) if (viewnum > 1 && !( multiplayer && demo.playback )) { - CONS_Alert(CONS_NOTICE, - "You must be viewing a multiplayer replay to use this.\n"); + CONS_Alert(CONS_NOTICE, "You must be viewing a multiplayer replay to use this.\n"); return; } @@ -2314,10 +2257,9 @@ static void Command_SetViews_f(void) UINT8 splits; UINT8 newsplits; - if (!( demo.playback && multiplayer )) + if (!(demo.playback && multiplayer)) { - CONS_Alert(CONS_NOTICE, - "You must be viewing a multiplayer replay to use this.\n"); + CONS_Alert(CONS_NOTICE, "You must be viewing a multiplayer replay to use this.\n"); return; } @@ -2536,18 +2478,8 @@ void D_MapChange(INT32 mapnum, INT32 newgametype, boolean pencoremode, boolean r // Kick bot from special stages if (botskin) { - if (G_IsSpecialStage(mapnum)) + if (!botingame) { - if (botingame) - { - //CL_RemoveSplitscreenPlayer(); - botingame = false; - playeringame[1] = false; - } - } - else if (!botingame) - { - //CL_AddSplitscreenPlayer(); botingame = true; displayplayers[1] = 1; playeringame[1] = true; @@ -3133,20 +3065,6 @@ static void Command_Respawn(void) return; } - /*if (!G_RaceGametype()) // srb2kart: not necessary, respawning makes you lose a bumper in battle, so it's not desirable to use as a way to escape a hit - { - CONS_Printf(M_GetText("You may only use this in co-op, race, and competition!\n")); - return; - }*/ - - // Retry is quicker. Probably should force people to use it. - // nope, this is srb2kart - a complete retry is overkill - /*if (!(netgame || multiplayer)) - { - CONS_Printf(M_GetText("You can't use this in Single Player! Use \"retry\" instead.\n")); - return; - }*/ - SendNetXCmd(XD_RESPAWN, &buf, 4); } diff --git a/src/d_netfil.c b/src/d_netfil.c index a71df9a71..0650f3c34 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -1306,6 +1306,21 @@ void CURLPrepareFile(const char* url, int dfilenum) strcatbf(curl_curfile->filename, downloaddir, "/"); curl_curfile->file = fopen(curl_curfile->filename, "wb"); + + if (!curl_curfile->file) + { + CONS_Alert(CONS_ERROR, "Couldnt open %s for writing!\nAborting file download.\nCheck if you have write access to your download folder!\n", curl_curfile->filename); + CL_AbortConnection(); + M_StartMessage(M_GetText( + "An error occured when trying to\n" + "download missing addons.\n" + "See the console or log file\n" + "for additional details.\n\n" + "Press ESC\n" + ), NULL, MM_NOTHING); + return; + } + curl_easy_setopt(http_handle, CURLOPT_WRITEDATA, curl_curfile->file); curl_easy_setopt(http_handle, CURLOPT_WRITEFUNCTION, curlwrite_data); curl_easy_setopt(http_handle, CURLOPT_NOPROGRESS, 0L); @@ -1366,6 +1381,7 @@ void CURLGetFile(void) CONS_Alert(CONS_WARNING, "curl_multi_wait() failed, code %d.\n", mc); continue; } + curl_curfile->currentsize = curl_dlnow; curl_curfile->totalsize = curl_dltotal; } diff --git a/src/dummy/i_main.c b/src/dummy/i_main.c deleted file mode 100644 index 0abf53b17..000000000 --- a/src/dummy/i_main.c +++ /dev/null @@ -1,21 +0,0 @@ -#include "../doomdef.h" -#include "../d_main.h" -#include "../m_argv.h" - -int main(int argc, char **argv) -{ - myargc = argc; - myargv = argv; /// \todo pull out path to exe from this string - - // startup SRB2 - CONS_Printf("Setting up SRB2...\n"); - D_SRB2Main(); - CONS_Printf("Entering main game loop...\n"); - // never return - D_SRB2Loop(); - - // return to OS -#ifndef __GNUC__ - return 0; -#endif -} diff --git a/src/dummy/i_net.c b/src/dummy/i_net.c deleted file mode 100644 index f6e642022..000000000 --- a/src/dummy/i_net.c +++ /dev/null @@ -1,6 +0,0 @@ -#include "../i_net.h" - -boolean I_InitNetwork(void) -{ - return false; -} diff --git a/src/dummy/i_sound.c b/src/dummy/i_sound.c deleted file mode 100644 index ff01bdff0..000000000 --- a/src/dummy/i_sound.c +++ /dev/null @@ -1,217 +0,0 @@ -#include "../i_sound.h" - -UINT8 sound_started = 0; - -void *I_GetSfx(sfxinfo_t *sfx) -{ - (void)sfx; - return NULL; -} - -void I_FreeSfx(sfxinfo_t *sfx) -{ - (void)sfx; -} - -void I_StartupSound(void){} - -void I_ShutdownSound(void){} - -void I_UpdateSound(void){}; - -// -// SFX I/O -// - -INT32 I_StartSound(sfxenum_t id, UINT8 vol, UINT8 sep, UINT8 pitch, UINT8 priority, INT32 channel) -{ - (void)id; - (void)vol; - (void)sep; - (void)pitch; - (void)priority; - (void)channel; - return -1; -} - -void I_StopSound(INT32 handle) -{ - (void)handle; -} - -boolean I_SoundIsPlaying(INT32 handle) -{ - (void)handle; - return false; -} - -void I_UpdateSoundParams(INT32 handle, UINT8 vol, UINT8 sep, UINT8 pitch) -{ - (void)handle; - (void)vol; - (void)sep; - (void)pitch; -} - -void I_SetSfxVolume(UINT8 volume) -{ - (void)volume; -} - -/// ------------------------ -// MUSIC SYSTEM -/// ------------------------ - -void I_InitMusic(void){} - -void I_ShutdownMusic(void){} - -/// ------------------------ -// MUSIC PROPERTIES -/// ------------------------ - -musictype_t I_SongType(void) -{ - return MU_NONE; -} - -boolean I_SongPlaying(void) -{ - return false; -} - -boolean I_SongPaused(void) -{ - return false; -} - -/// ------------------------ -// MUSIC EFFECTS -/// ------------------------ - -boolean I_SetSongSpeed(float speed) -{ - (void)speed; - return false; -} - -/// ------------------------ -// MUSIC SEEKING -/// ------------------------ - -UINT32 I_GetSongLength(void) -{ - return 0; -} - -boolean I_SetSongLoopPoint(UINT32 looppoint) -{ - (void)looppoint; - return false; -} - -UINT32 I_GetSongLoopPoint(void) -{ - return 0; -} - -boolean I_SetSongPosition(UINT32 position) -{ - (void)position; - return false; -} - -UINT32 I_GetSongPosition(void) -{ - return 0; -} - -/// ------------------------ -// MUSIC PLAYBACK -/// ------------------------ - -boolean I_LoadSong(char *data, size_t len) -{ - (void)data; - (void)len; - return -1; -} - -void I_UnloadSong(void) -{ - (void)handle; -} - -boolean I_PlaySong(boolean looping) -{ - (void)handle; - (void)looping; - return false; -} - -void I_StopSong(void) -{ - (void)handle; -} - -void I_PauseSong(void) -{ - (void)handle; -} - -void I_ResumeSong(void) -{ - (void)handle; -} - -void I_SetMusicVolume(UINT8 volume) -{ - (void)volume; -} - -boolean I_SetSongTrack(INT32 track) -{ - (void)track; - return false; -} - -/// ------------------------ -// MUSIC FADING -/// ------------------------ - -void I_SetInternalMusicVolume(UINT8 volume) -{ - (void)volume; -} - -void I_StopFadingSong(void) -{ -} - -boolean I_FadeSongFromVolume(UINT8 target_volume, UINT8 source_volume, UINT32 ms, void (*callback)(void)); -{ - (void)target_volume; - (void)source_volume; - (void)ms; - return false; -} - -boolean I_FadeSong(UINT8 target_volume, UINT32 ms, void (*callback)(void)); -{ - (void)target_volume; - (void)ms; - return false; -} - -boolean I_FadeOutStopSong(UINT32 ms) -{ - (void)ms; - return false; -} - -boolean I_FadeInPlaySong(UINT32 ms, boolean looping) -{ - (void)ms; - (void)looping; - return false; -} diff --git a/src/dummy/i_system.c b/src/dummy/i_system.c deleted file mode 100644 index 32af5f9c8..000000000 --- a/src/dummy/i_system.c +++ /dev/null @@ -1,174 +0,0 @@ -#include "../doomdef.h" -#include "../i_system.h" - -UINT8 graphics_started = 0; - -UINT8 keyboard_started = 0; - -size_t I_GetFreeMem(size_t *total) -{ - *total = 0; - return 0; -} - -void I_Sleep(UINT32 ms){} - -precise_t I_GetPreciseTime(void) { - return 0; -} - -UINT64 I_GetPrecisePrecision(void) { - return 1000000; -} - -void I_GetEvent(void){} - -void I_OsPolling(void){} - -ticcmd_t *I_BaseTiccmd(void) -{ - return NULL; -} - -ticcmd_t *I_BaseTiccmd2(void) -{ - return NULL; -} - -void I_Quit(void) -{ - exit(0); -} - -void I_Error(const char *error, ...) -{ - (void)error; - exit(-1); -} - -void I_Tactile(FFType Type, const JoyFF_t *Effect) -{ - (void)Type; - (void)Effect; -} - -void I_Tactile2(FFType Type, const JoyFF_t *Effect) -{ - (void)Type; - (void)Effect; -} - -void I_JoyScale(void){} - -void I_JoyScale2(void){} - -void I_InitJoystick(void){} - -void I_InitJoystick2(void){} - -INT32 I_NumJoys(void) -{ - return 0; -} - -const char *I_GetJoyName(INT32 joyindex) -{ - (void)joyindex; - return NULL; -} - -#ifndef NOMUMBLE -void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) -{ - (void)mobj; - (void)listener; -} -#endif - -void I_OutputMsg(const char *error, ...) -{ - (void)error; -} - -void I_StartupMouse(void){} - -void I_StartupKeyboard(void){} - -INT32 I_GetKey(void) -{ - return 0; -} - -void I_StartupTimer(void){} - -void I_AddExitFunc(void (*func)()) -{ - (void)func; -} - -void I_RemoveExitFunc(void (*func)()) -{ - (void)func; -} - -INT32 I_StartupSystem(void) -{ - return -1; -} - -void I_ShutdownSystem(void){} - -void I_GetDiskFreeSpace(INT64* freespace) -{ - *freespace = 0; -} - -char *I_GetUserName(void) -{ - return NULL; -} - -INT32 I_mkdir(const char *dirname, INT32 unixright) -{ - (void)dirname; - (void)unixright; - return -1; -} - -const char *I_LocateWad(void) -{ - return NULL; -} - -void I_GetJoystickEvents(void){} - -void I_GetJoystick2Events(void){} - -char *I_GetEnv(const char *name) -{ - (void)name; - return NULL; -} - -INT32 I_PutEnv(char *variable) -{ - (void)variable; - return -1; -} - -INT32 I_ClipboardCopy(const char *data, size_t size) -{ - (void)data; - (void)size; - return -1; -} - -char *I_ClipboardPaste(void) -{ - return NULL; -} - -void I_RegisterSysCommands(void) {} - -#include "../sdl/dosstr.c" - diff --git a/src/dummy/i_video.c b/src/dummy/i_video.c deleted file mode 100644 index 93ba6b751..000000000 --- a/src/dummy/i_video.c +++ /dev/null @@ -1,67 +0,0 @@ -#include "../doomdef.h" -#include "../command.h" -#include "../i_video.h" - -rendermode_t rendermode = render_none; - -boolean highcolor = false; - -boolean allow_fullscreen = false; - -consvar_t cv_vidwait = {"vid_wait", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; - -void I_StartupGraphics(void){} - -void I_ShutdownGraphics(void){} - -void I_SetPalette(RGBA_t *palette) -{ - (void)palette; -} - -INT32 VID_NumModes(void) -{ - return 0; -} - -INT32 VID_GetModeForSize(INT32 w, INT32 h) -{ - (void)w; - (void)h; - return 0; -} - -void VID_PrepareModeList(void){} - -INT32 VID_SetMode(INT32 modenum) -{ - (void)modenum; - return 0; -} - -const char *VID_GetModeName(INT32 modenum) -{ - (void)modenum; - return NULL; -} - -void I_UpdateNoBlit(void){} - -void I_FinishUpdate(void){} - -void I_UpdateNoVsync(void) {} - -void I_WaitVBL(INT32 count) -{ - (void)count; -} - -void I_ReadScreen(UINT8 *scr) -{ - (void)scr; -} - -void I_BeginRead(void){} - -void I_EndRead(void){} - diff --git a/src/g_game.c b/src/g_game.c index 44b9cf370..200ce7834 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -396,7 +396,6 @@ consvar_t cv_growmusic = {"growmusic", "On", CV_SAVE, powermusic_cons_t, NULL, consvar_t cv_supermusic = {"supermusic", "On", CV_SAVE, powermusic_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_invertmouse = {"invertmouse", "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}; static CV_PossibleValue_t joyaxis_cons_t[] = {{0, "None"}, {1, "Left X"}, {2, "Left Y"}, {-1, "Left X-"}, {-2, "Left Y-"}, @@ -417,105 +416,105 @@ static CV_PossibleValue_t joyaxis_cons_t[] = {{0, "None"}, static CV_PossibleValue_t deadzone_cons_t[] = {{FRACUNIT/16, "MIN"}, {FRACUNIT, "MAX"}, {0, NULL}}; consvar_t cv_turnaxis[MAXSPLITSCREENPLAYERS] = { - {"joyaxis_turn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"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_moveaxis[MAXSPLITSCREENPLAYERS] = { - {"joyaxis_move", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"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_camstrafeaxis[MAXSPLITSCREENPLAYERS] = { - {"joyaxis_camstrafe", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis_camstrafe", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"joyaxis2_camstrafe", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"joyaxis3_camstrafe", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"joyaxis4_camstrafe", "None", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} }; consvar_t cv_camturnaxis[MAXSPLITSCREENPLAYERS] = { - {"joyaxis_camturn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"joyaxis_camturn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"joyaxis2_camturn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"joyaxis3_camturn", "Left X", CV_SAVE, joyaxis_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, {"joyaxis4_camturn", "Left X", 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}, + {"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}, + {"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}, + {"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}, + {"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}, + {"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}, + {"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}, + {"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}, + {"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}, + {"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}, + {"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}, + {"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} @@ -1291,7 +1290,7 @@ static void G_DoLoadLevel(boolean resetplayer) for (i = 0; i < JOYAXISSET; i++) { - joyxmove[i] = joyymove[i] = 0; + joyxmove[i] = joyymove[i] = 0; joy2xmove[i] = joy2ymove[i] = 0; joy3xmove[i] = joy3ymove[i] = 0; joy4xmove[i] = joy4ymove[i] = 0; @@ -1583,10 +1582,7 @@ boolean G_CouldView(INT32 playernum) return false; // SRB2Kart: Only go through players who are actually playing - if (player->exiting) - return false; - - if (player->pflags & PF_TIMEOVER) + if (player->exiting || (player->pflags & PF_TIMEOVER)) return false; // I don't know if we want this actually, but I'll humor the suggestion anyway @@ -1848,11 +1844,11 @@ void G_Ticker(boolean run) { switch (gameaction) { - case ga_completed: G_DoCompleted(); break; + case ga_completed: G_DoCompleted(); break; case ga_startcont: G_DoStartContinue(); break; - case ga_continued: G_DoContinued(); break; - case ga_worlddone: G_DoWorldDone(); break; - case ga_startvote: G_DoStartVote(); break; + case ga_continued: G_DoContinued(); break; + case ga_worlddone: G_DoWorldDone(); break; + case ga_startvote: G_DoStartVote(); break; case ga_nothing: break; default: I_Error("gameaction = %d\n", gameaction); } @@ -1954,6 +1950,7 @@ void G_Ticker(boolean run) case GS_TITLESCREEN: F_TitleScreenTicker(run); + HU_TickSongCredits(); break; case GS_WAITINGPLAYERS: if (netgame) @@ -2571,10 +2568,10 @@ mapthing_t *G_FindRaceStart(INT32 playernum) { if (!playeringame[j] || players[j].spectator) continue; - if (j == playernum) - continue; - if (j == i) + + if ((j == playernum) || (j == i)) continue; + if (players[j].score == players[i].score) num++; } @@ -2672,6 +2669,7 @@ void G_DoReborn(INT32 playernum) } B_RespawnBot(playernum); + if (oldmo) G_ChangePlayerReferences(oldmo, players[playernum].mo); } @@ -2694,6 +2692,7 @@ void G_DoReborn(INT32 playernum) } G_SpawnPlayer(playernum, starpost); + if (oldmo) G_ChangePlayerReferences(oldmo, players[playernum].mo); @@ -2762,62 +2761,6 @@ INT32 G_GetGametypeByName(const char *gametypestr) return -1; // unknown gametype } -// -// G_IsSpecialStage -// -// Returns TRUE if -// the given map is a special stage. -// -boolean G_IsSpecialStage(INT32 mapnum) -{ - (void)mapnum; - return false; -} - -// -// G_GametypeUsesLives -// -// Returns true if the current gametype uses -// the lives system. False otherwise. -// -boolean G_GametypeUsesLives(void) -{ - // SRB2kart NEEDS no lives - return false; -} - -// -// G_GametypeHasTeams -// -// Returns true if the current gametype uses -// Red/Blue teams. False otherwise. -// -boolean G_GametypeHasTeams(void) -{ - return (gametype == GT_TEAMMATCH || gametype == GT_CTF); -} - -// -// G_GametypeHasSpectators -// -// Returns true if the current gametype supports -// spectators. False otherwise. -// -boolean G_GametypeHasSpectators(void) -{ - return (netgame || (multiplayer && demo.playback)); //true -} - -// -// G_BattleGametype -// -// Returns true in Battle gamemodes, previously was G_RingSlingerGametype. -// -boolean G_BattleGametype(void) -{ - return (gametype == GT_MATCH); -} - // // G_SometimesGetDifferentGametype // @@ -2849,6 +2792,7 @@ UINT8 G_SometimesGetDifferentGametype(UINT8 prefgametype) default: break; } + if (encoreactual != (boolean)cv_kartencore.value) encoremodifier = 0x80; } @@ -2882,6 +2826,7 @@ UINT8 G_SometimesGetDifferentGametype(UINT8 prefgametype) return (GT_RACE|0x80); return (GT_RACE); } + // This might appear wrong HERE, but the game will display the Encore possibility on the second voting choice instead. return (GT_MATCH|encoremodifier); } @@ -2904,27 +2849,6 @@ UINT8 G_GetGametypeColor(INT16 gt) return 247; // FALLBACK } -// -// G_RaceGametype -// -// Returns true in Race gamemodes, previously was G_PlatformGametype. -// -boolean G_RaceGametype(void) -{ - return (gametype == GT_RACE); -} - -// -// G_TagGametype -// -// For Jazz's Tag/HnS modes that have a lot of special cases... -// SRB2Kart: do we actually want to add Kart tag later? :V -// -boolean G_TagGametype(void) -{ - return (gametype == GT_TAG || gametype == GT_HIDEANDSEEK); -} - /** Get the typeoflevel flag needed to indicate support of a gametype. * In single-player, this always returns TOL_SP. * \param gametype The gametype for which support is desired. @@ -2988,7 +2912,8 @@ INT16 G_RandMap(INT16 tolflags, INT16 pprevmap, boolean ignorebuffer, UINT8 maph if (extbuffer != NULL) { bufx = 0; - while (extbuffer[bufx]) { + while (extbuffer[bufx]) + { extbufsize++; bufx++; } } @@ -3117,7 +3042,6 @@ void G_AddMapToBuffer(INT16 map) static void G_DoCompleted(void) { INT32 i, j = 0; - boolean gottoken = false; tokenlist = 0; // Reset the list @@ -3166,15 +3090,13 @@ static void G_DoCompleted(void) nextmap = (INT16)(mapheaderinfo[gamemap-1]->nextlevel-1); // Remember last map for when you come out of the special stage. - if (!G_IsSpecialStage(gamemap)) - lastmap = nextmap; + lastmap = nextmap; // If nextmap is actually going to get used, make sure it points to // a map of the proper gametype -- skip levels that don't support // the current gametype. (Helps avoid playing boss levels in Race, // for instance). - if (!token && !G_IsSpecialStage(gamemap) && !modeattacking - && (nextmap >= 0 && nextmap < NUMMAPS)) + if (!token && !modeattacking && (nextmap >= 0 && nextmap < NUMMAPS)) { register INT16 cm = nextmap; INT16 tolflag = G_TOLFlag(gametype); @@ -3228,12 +3150,11 @@ static void G_DoCompleted(void) if (gametype == GT_COOP && token) { token--; - gottoken = true; if (!(emeralds & EMERALD1)) nextmap = (INT16)(sstage_start - 1); // Special Stage 1 else if (!(emeralds & EMERALD2)) - nextmap = (INT16)(sstage_start); // Special Stage 2 + nextmap = (INT16)(sstage_start); // Special Stage 2 else if (!(emeralds & EMERALD3)) nextmap = (INT16)(sstage_start + 1); // Special Stage 3 else if (!(emeralds & EMERALD4)) @@ -3244,13 +3165,8 @@ static void G_DoCompleted(void) nextmap = (INT16)(sstage_start + 4); // Special Stage 6 else if (!(emeralds & EMERALD7)) nextmap = (INT16)(sstage_start + 5); // Special Stage 7 - else - gottoken = false; } - if (G_IsSpecialStage(gamemap) && !gottoken) - nextmap = lastmap; // Exiting from a special stage? Go back to the game. Tails 08-11-2001 - automapactive = false; if (gametype != GT_COOP) @@ -3281,7 +3197,6 @@ demointermission: void G_AfterIntermission(void) { HU_ClearCEcho(); - //G_NextLevel(); if (demo.playback) { @@ -3838,9 +3753,6 @@ void G_LoadGame(UINT32 slot, INT16 mapoverride) if (demo.playback) // reset game engine G_StopDemo(); -// paused = false; -// automapactive = false; - // dearchive all the modifications if (!P_LoadGame(&save, mapoverride)) { @@ -4950,6 +4862,13 @@ void G_WriteAllGhostTics(void) if (multiplayer && ((counter % cv_netdemosyncquality.value) != 0)) // Only write 1 in this many ghost datas per tic to cut down on multiplayer replay size. continue; + if (((ghostext[i].flags && (ghostext[i].flags & EZT_HIT)) || ghostext[i].hits) + && !ghostext[i].hitlist) // hitlist might be freed during resynch, beware PU_LEVEL! + { + ghostext[i].hits = 0; + continue; + } + CHECKSPACE(1); WRITEUINT8(demobuf.p, i); @@ -5016,9 +4935,9 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) ziptic |= GZT_XYZ; CHECKSPACE(sizeof(fixed_t)*3); - WRITEFIXED(demobuf.p,oldghost[playernum].x); - WRITEFIXED(demobuf.p,oldghost[playernum].y); - WRITEFIXED(demobuf.p,oldghost[playernum].z); + WRITEFIXED(demobuf.p, oldghost[playernum].x); + WRITEFIXED(demobuf.p, oldghost[playernum].y); + WRITEFIXED(demobuf.p, oldghost[playernum].z); } else { @@ -5036,8 +4955,8 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) CHECKSPACE(4); - WRITEINT16(demobuf.p,momx); - WRITEINT16(demobuf.p,momy); + WRITEINT16(demobuf.p, momx); + WRITEINT16(demobuf.p, momy); } momx = (INT16)((ghost->z-oldghost[playernum].z + (1<<4))>>8); @@ -5049,7 +4968,7 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) CHECKSPACE(2); - WRITEINT16(demobuf.p,momx); + WRITEINT16(demobuf.p, momx); } // This SHOULD set oldghost.x/y/z to match ghost->x/y/z @@ -5072,7 +4991,7 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) CHECKSPACE(1); - WRITEUINT8(demobuf.p,oldghost[playernum].angle); + WRITEUINT8(demobuf.p, oldghost[playernum].angle); } // Store the sprite frame. @@ -5084,7 +5003,7 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) CHECKSPACE(1); - WRITEUINT8(demobuf.p,oldghost[playernum].frame); + WRITEUINT8(demobuf.p, oldghost[playernum].frame); } // Check for sprite set changes @@ -5120,26 +5039,26 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) if (ghostext[playernum].flags) { ziptic |= GZT_EXTRA; - WRITEUINT8(demobuf.p,ghostext[playernum].flags); + WRITEUINT8(demobuf.p, ghostext[playernum].flags); if (ghostext[playernum].flags & EZT_COLOR) { CHECKSPACE(1); - WRITEUINT8(demobuf.p,ghostext[playernum].color); + WRITEUINT8(demobuf.p, ghostext[playernum].color); ghostext[playernum].lastcolor = ghostext[playernum].color; } if (ghostext[playernum].flags & EZT_SCALE) { CHECKSPACE(sizeof(fixed_t)); - WRITEFIXED(demobuf.p,ghostext[playernum].scale); + WRITEFIXED(demobuf.p, ghostext[playernum].scale); ghostext[playernum].lastscale = ghostext[playernum].scale; } if (ghostext[playernum].flags & EZT_HIT) { CHECKSPACE(2); - WRITEUINT16(demobuf.p,ghostext[playernum].hits); + WRITEUINT16(demobuf.p, ghostext[playernum].hits); for (i = 0; i < ghostext[playernum].hits; i++) { @@ -5147,13 +5066,13 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) CHECKSPACE(4+4+2+sizeof(fixed_t)*3+sizeof(angle_t)); - WRITEUINT32(demobuf.p,UINT32_MAX); // reserved for some method of determining exactly which mobj this is. (mobjnum doesn't work here.) - WRITEUINT32(demobuf.p,mo->type); - WRITEUINT16(demobuf.p,(UINT16)mo->health); - WRITEFIXED(demobuf.p,mo->x); - WRITEFIXED(demobuf.p,mo->y); - WRITEFIXED(demobuf.p,mo->z); - WRITEANGLE(demobuf.p,mo->angle); + WRITEUINT32(demobuf.p, UINT32_MAX); // reserved for some method of determining exactly which mobj this is. (mobjnum doesn't work here.) + WRITEUINT32(demobuf.p, mo->type); + WRITEUINT16(demobuf.p, (UINT16)mo->health); + WRITEFIXED(demobuf.p, mo->x); + WRITEFIXED(demobuf.p, mo->y); + WRITEFIXED(demobuf.p, mo->z); + WRITEANGLE(demobuf.p, mo->angle); P_SetTarget(ghostext[playernum].hitlist+i, NULL); } @@ -5163,7 +5082,7 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) if (ghostext[playernum].flags & EZT_SPRITE) { CHECKSPACE(1); - WRITEUINT8(demobuf.p,sprite); + WRITEUINT8(demobuf.p, sprite); } if (ghostext[playernum].flags & EZT_KART) diff --git a/src/g_game.h b/src/g_game.h index bde892309..5714097b2 100644 --- a/src/g_game.h +++ b/src/g_game.h @@ -388,16 +388,24 @@ boolean G_CheckDemoStatus(void); void G_SaveDemo(void); boolean G_DemoTitleResponder(event_t *ev); +#define G_GametypeHasTeams() (G_IsGameType(GT_TEAMMATCH) || G_IsGameType(GT_CTF)) +#define G_BattleGametype() (G_IsGameType(GT_MATCH)) +#define G_RaceGametype() (G_IsGameType(GT_RACE)) +#define G_TagGametype() (G_IsGameType(GT_TAG) || G_IsGameType(GT_HIDEANDSEEK)) + +FUNCINLINE static ATTRINLINE boolean G_IsGameType(int type) +{ + return (gametype == type); +} + +FUNCINLINE static ATTRINLINE boolean G_GametypeHasSpectators(void) +{ + return (netgame || (multiplayer && demo.playback)); +} + INT32 G_GetGametypeByName(const char *gametypestr); -boolean G_IsSpecialStage(INT32 mapnum); -boolean G_GametypeUsesLives(void); -boolean G_GametypeHasTeams(void); -boolean G_GametypeHasSpectators(void); -boolean G_BattleGametype(void); UINT8 G_SometimesGetDifferentGametype(UINT8 prefgametype); UINT8 G_GetGametypeColor(INT16 gt); -boolean G_RaceGametype(void); -boolean G_TagGametype(void); void G_ExitLevel(void); void G_NextLevel(void); void G_Continue(void); @@ -427,7 +435,6 @@ void G_SetRetryFlag(void); void G_ClearRetryFlag(void); boolean G_GetRetryFlag(void); - void G_LoadGameData(void); void G_LoadGameSettings(void); diff --git a/src/g_input.c b/src/g_input.c index 963663504..43b7f48ca 100644 --- a/src/g_input.c +++ b/src/g_input.c @@ -58,44 +58,35 @@ consvar_t cv_rumble[MAXSPLITSCREENPLAYERS] = { {"rumble4", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, rumble_off_handle4, 0, NULL, NULL, 0, 0, NULL} }; +static CV_PossibleValue_t gamepadled_cons_t[] = {{0, "Off"}, {1, "Skincolor"}, {2, "Mobjcolor"}, {0, NULL}}; consvar_t cv_gamepadled[MAXSPLITSCREENPLAYERS] = { - {"gamepadled", "On", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle, 0, NULL, NULL, 0, 0, NULL}, - {"gamepadled2", "On", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle2, 0, NULL, NULL, 0, 0, NULL}, - {"gamepadled3", "On", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle3, 0, NULL, NULL, 0, 0, NULL}, - {"gamepadled4", "On", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle4, 0, NULL, NULL, 0, 0, NULL} -}; - -consvar_t cv_ledpowerup[MAXSPLITSCREENPLAYERS] = { - {"ledpowerup", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle, 0, NULL, NULL, 0, 0, NULL}, - {"ledpowerup2", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle2, 0, NULL, NULL, 0, 0, NULL}, - {"ledpowerup3", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle3, 0, NULL, NULL, 0, 0, NULL}, - {"ledpowerup4", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, led_off_handle4, 0, NULL, NULL, 0, 0, NULL} + {"gamepadled", "Skincolor", CV_SAVE|CV_CALL|CV_NOINIT, gamepadled_cons_t, led_off_handle, 0, NULL, NULL, 0, 0, NULL}, + {"gamepadled2", "Skincolor", CV_SAVE|CV_CALL|CV_NOINIT, gamepadled_cons_t, led_off_handle2, 0, NULL, NULL, 0, 0, NULL}, + {"gamepadled3", "Skincolor", CV_SAVE|CV_CALL|CV_NOINIT, gamepadled_cons_t, led_off_handle3, 0, NULL, NULL, 0, 0, NULL}, + {"gamepadled4", "Skincolor", CV_SAVE|CV_CALL|CV_NOINIT, gamepadled_cons_t, led_off_handle4, 0, NULL, NULL, 0, 0, NULL} }; static void rumble_off_handle(void) { - if (cv_rumble[0].value == 0) + if (!cv_rumble[0].value) G_ResetPlayerDeviceRumble(0); } - static void rumble_off_handle2(void) { - if (cv_rumble[1].value == 0) + if (!cv_rumble[1].value) G_ResetPlayerDeviceRumble(1); } - static void rumble_off_handle3(void) { - if (cv_rumble[2].value == 0) + if (!cv_rumble[2].value) G_ResetPlayerDeviceRumble(2); } - static void rumble_off_handle4(void) { - if (cv_rumble[3].value == 0) + if (!cv_rumble[3].value) G_ResetPlayerDeviceRumble(3); } @@ -104,19 +95,16 @@ static void led_off_handle(void) G_ResetPlayerGamepadIndicatorColor(0); } - static void led_off_handle2(void) { G_ResetPlayerGamepadIndicatorColor(1); } - static void led_off_handle3(void) { G_ResetPlayerGamepadIndicatorColor(2); } - static void led_off_handle4(void) { G_ResetPlayerGamepadIndicatorColor(3); @@ -900,13 +888,16 @@ UINT16 G_GetSkinColor(INT32 playernum) { player_t *player = &players[displayplayers[playernum]]; - // make rgb rainbow vomit when invul or flash blue when grow - if (cv_ledpowerup[playernum].value && player->mo && (player->kartstuff[k_invincibilitytimer] || player->kartstuff[k_growshrinktimer] || player->powers[pw_invulnerability])) - return player->mo->color; + if (player) + { + // make rgb rainbow vomit when invul or flash blue when grow + if ((cv_gamepadled[playernum].value == 2) && player->mo && player->mo->color) + return player->mo->color; - // take actual player skincolour when ingame - if (player->skincolor) - return player->skincolor; + // take actual player skincolour when ingame + if (player->skincolor) + return player->skincolor; + } } // otherwise just fallback to whatever the cvar is diff --git a/src/g_input.h b/src/g_input.h index 478dae8f1..d801d1020 100644 --- a/src/g_input.h +++ b/src/g_input.h @@ -109,7 +109,6 @@ extern consvar_t cv_mousesens, cv_mouseysens; extern consvar_t cv_controlperkey, cv_turnsmooth; extern consvar_t cv_rumble[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_gamepadled[MAXSPLITSCREENPLAYERS]; -extern consvar_t cv_ledpowerup[MAXSPLITSCREENPLAYERS]; extern INT32 mousex, mousey; extern INT32 mlooky; //mousey with mlookSensitivity diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c index 3c7a49af9..3655beb8a 100644 --- a/src/hardware/hw_batching.c +++ b/src/hardware/hw_batching.c @@ -88,7 +88,10 @@ void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPt 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 + } + if (polygonArraySize == polygonArrayAllocSize) { PolygonArrayEntry* new_array; @@ -228,7 +231,9 @@ void HWR_RenderBatches(void) int i; if (!currently_batching) + { I_Error("HWR_RenderBatches called without starting batching"); + } nextSurfaceInfo.LightInfo.fade_end = 0; nextSurfaceInfo.LightInfo.fade_start = 0; @@ -236,6 +241,7 @@ void HWR_RenderBatches(void) nextSurfaceInfo.LightInfo.directional = false; currently_batching = false;// no longer collecting batches + if (!polygonArraySize) { ps_hw_numpolys.value.i = ps_hw_numcalls.value.i = ps_hw_numshaders.value.i @@ -243,6 +249,7 @@ void HWR_RenderBatches(void) = ps_hw_numcolors.value.i = 0; return;// nothing to draw } + // init stats vars ps_hw_numpolys.value.i = polygonArraySize; ps_hw_numcalls.value.i = ps_hw_numverts.value.i = 0; @@ -291,7 +298,7 @@ void HWR_RenderBatches(void) else GL_SetTexture(currentTexture); - while (1)// note: remember handling notexture polyflag as having texture number 0 (also in comparePolygons) + while (1) // note: remember handling notexture polyflag as having texture number 0 (also in comparePolygons) { int firstIndex; int lastIndex; @@ -361,23 +368,28 @@ void HWR_RenderBatches(void) nextTexture = nextEntry->texture; nextPolyFlags = nextEntry->polyFlags; nextSurfaceInfo = nextEntry->surf; + if (nextPolyFlags & PF_NoTexture) nextTexture = 0; + if (currentShader != nextShader && cv_glshaders.value && gl_shadersavailable) { changeState = true; changeShader = true; } + if (currentTexture != nextTexture) { changeState = true; changeTexture = true; } + if (currentPolyFlags != nextPolyFlags) { changeState = true; changePolyFlags = true; } + if (cv_glshaders.value && gl_shadersavailable) { if (currentSurfaceInfo.PolyColor.rgba != nextSurfaceInfo.PolyColor.rgba || @@ -413,10 +425,12 @@ void HWR_RenderBatches(void) finalVertexWritePos = 0; finalIndexWritePos = 0; } - else continue; + else + continue; // if we're here then either its time to stop or time to change state - if (stopFlag) break; + if (stopFlag) + break; // change state according to change bools and next vars, update current vars and reset bools if (changeState) @@ -429,6 +443,7 @@ void HWR_RenderBatches(void) ps_hw_numshaders.value.i++; } + if (changeTexture) { // texture should be already ready for use from calls to GL_SetTexture during batch collection @@ -438,6 +453,7 @@ void HWR_RenderBatches(void) ps_hw_numtextures.value.i++; } + if (changePolyFlags) { currentPolyFlags = nextPolyFlags; @@ -445,6 +461,7 @@ void HWR_RenderBatches(void) ps_hw_numpolyflags.value.i++; } + if (changeSurfaceInfo) { currentSurfaceInfo = nextSurfaceInfo; diff --git a/src/hardware/hw_defs.h b/src/hardware/hw_defs.h index 822389758..08cce42c9 100644 --- a/src/hardware/hw_defs.h +++ b/src/hardware/hw_defs.h @@ -131,17 +131,23 @@ typedef struct FLOAT scalex, scaley, scalez; FLOAT fovangle; UINT8 splitscreen; - boolean flip; // screenflip boolean roll; FLOAT rollangle; FLOAT centerx, centery; FLOAT rollx, rollz; - boolean mirror; // SRB2Kart: Encore Mode - boolean mirrorflip; // Encore Mode with Flipcam + UINT8 fliptype; boolean shearing; // 14042019 float viewaiming; // 17052019 } FTransform; +enum +{ + TRANSFORM_NONE = 0, + TRANSFORM_FLIP = 1 << 0, // screenflip + TRANSFORM_MIRROR = 1 << 1, // SRB2Kart: Encore Mode + TRANSFORM_MIRRORFLIP = TRANSFORM_FLIP|TRANSFORM_MIRROR // SRB2Kart: Encore Mode with Flipcam +}; + // Transformed vector, as passed to HWR API typedef struct { diff --git a/src/hardware/hw_main.c b/src/hardware/hw_main.c index ea5b9f522..94767ff5d 100644 --- a/src/hardware/hw_main.c +++ b/src/hardware/hw_main.c @@ -481,11 +481,11 @@ static UINT8 HWR_FogBlockAlpha(INT32 light, extracolormap_t *colormap) // Let's return surfcolor.s.alpha; } -static FUINT HWR_CalcWallLight(FUINT lightnum, seg_t *seg) +static FUINT HWR_CalcWallLight(FUINT lightnum, seg_t *seg, extracolormap_t *colormap) { INT16 finallight = lightnum; - if (cv_glfakecontrast.value == 0) + if (cv_glfakecontrast.value == 0 || (HWR_ShouldUsePaletteRendering() && colormap)) return (FUINT)finallight; if (seg != NULL && P_ApplyLightOffsetFine(lightnum, seg->frontsector)) @@ -698,8 +698,7 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool for (i = 0, v3d = planeVerts; i < (INT32)nrPlaneVerts; i++,v3d++,pv++) SETUP3DVERT(v3d, pv->x, pv->y); - if (slope) - lightlevel = HWR_CalcSlopeLight(lightlevel, slope, gl_frontsector, (FOFsector != NULL)); + lightlevel = HWR_CalcSlopeLight(lightlevel, slope, gl_frontsector, (FOFsector != NULL)); HWR_Lighting(&Surf, lightlevel, planecolormap, P_SectorUsesDirectionalLighting(gl_frontsector)); @@ -1008,7 +1007,7 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, fixed_t v2y = FloatToFixed(wallVerts[1].z); const UINT8 alpha = Surf->PolyColor.s.alpha; - FUINT lightnum = HWR_CalcWallLight(sector->lightlevel, gl_curline); + FUINT lightnum = HWR_CalcWallLight(sector->lightlevel, gl_curline, NULL); extracolormap_t *colormap = NULL; realtop = top = wallVerts[3].y; @@ -1051,14 +1050,14 @@ 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, gl_curline); } else { lightnum = *list[i].lightlevel; colormap = list[i].extra_colormap; - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); } + + lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); } boolean solid = false; @@ -1388,7 +1387,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom FUINT lightnum = gl_frontsector->lightlevel; extracolormap_t *colormap = gl_frontsector->extra_colormap; - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); + lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); FSurfaceInfo Surf; @@ -2015,7 +2014,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(lightnum, colormap); - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); + lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); if (gl_frontsector->numlights) HWR_SplitWall(gl_frontsector, wallVerts, 0, false, &Surf, roverflags, rover, blendmode); @@ -2132,7 +2131,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom Surf.PolyColor.s.alpha = HWR_FogBlockAlpha(lightnum, colormap); - lightnum = (HWR_ShouldUsePaletteRendering() && colormap) ? lightnum : HWR_CalcWallLight(lightnum, gl_curline); + lightnum = HWR_CalcWallLight(lightnum, gl_curline, colormap); if (gl_backsector->numlights) HWR_SplitWall(gl_backsector, wallVerts, 0, false, &Surf, roverflags, rover, blendmode); @@ -2166,6 +2165,11 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom //Hurdler: end of 3d-floors test } +static inline boolean HWR_UsePortals(void) +{ + return cv_glportals.value && gl_maphasportals; +} + // From PrBoom: // // e6y: Check whether the player can look beyond this line, returns true if we can't @@ -2226,7 +2230,8 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector) } // using this check with portals causes weird culling issues on ante-station - if (LIKELY(!portalclipline) && (afrontsector == viewsector || abacksector == viewsector)) + if (LIKELY(!portalclipline) && + (afrontsector == viewsector || abacksector == viewsector)) { fixed_t viewf1, viewf2, viewc1, viewc2; if (afrontsector == viewsector) @@ -2292,7 +2297,8 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector) // Window. // We know it's a window when the above isn't true and the back and front sectors don't match - if (backc1 != frontc1 || backc2 != frontc2 || backf1 != frontf1 || backf2 != frontf2) + if (backc1 != frontc1 || backc2 != frontc2 + || backf1 != frontf1 || backf2 != frontf2) { checkforemptylines = false; return false; @@ -2359,7 +2365,7 @@ static void HWR_AddLine(seg_t *line) gl_backsector = line->backsector; - if (!cv_glportals.value || LIKELY(!gl_maphasportals)) + if (LIKELY(!HWR_UsePortals())) { doaddline: if (!line->backsector) @@ -4365,44 +4371,45 @@ static void HWR_RenderDrawNodes(void) switch (drawnode->type) { case DRAWNODE_PLANE: - { - planeinfo_t *plane = &drawnode->u.plane; + { + planeinfo_t *plane = &drawnode->u.plane; - // We aren't traversing the BSP tree, so make gl_frontsector null to avoid crashes. - gl_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)); + if (!(plane->blend & PF_NoTexture)) + HWR_GetFlat(plane->lumpnum, R_NoEncore(plane->FOFSector, plane->isceiling)); - HWR_RenderPlane(NULL, plane->xsub, plane->isceiling, plane->fixedheight, plane->blend, plane->lightlevel, - plane->lumpnum, plane->FOFSector, plane->alpha, plane->planecolormap); + HWR_RenderPlane(NULL, plane->xsub, plane->isceiling, plane->fixedheight, plane->blend, plane->lightlevel, + plane->lumpnum, plane->FOFSector, plane->alpha, plane->planecolormap); + } break; - } case DRAWNODE_POLYOBJECT_PLANE: - { - polyplaneinfo_t *polyplane = &drawnode->u.polyplane; + { + polyplaneinfo_t *polyplane = &drawnode->u.polyplane; - // We aren't traversing the BSP tree, so make gl_frontsector null to avoid crashes. - gl_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)); + if (!(polyplane->blend & PF_NoTexture)) + HWR_GetFlat(polyplane->lumpnum, R_NoEncore(polyplane->FOFSector, polyplane->isceiling)); - HWR_RenderPolyObjectPlane(polyplane->polysector, polyplane->isceiling, polyplane->fixedheight, polyplane->blend, polyplane->lightlevel, - polyplane->lumpnum, polyplane->FOFSector, polyplane->alpha, polyplane->planecolormap); + HWR_RenderPolyObjectPlane(polyplane->polysector, polyplane->isceiling, polyplane->fixedheight, polyplane->blend, polyplane->lightlevel, + polyplane->lumpnum, polyplane->FOFSector, polyplane->alpha, polyplane->planecolormap); + + } break; - } case DRAWNODE_WALL: - { - wallinfo_t *wall = &drawnode->u.wall; + { + wallinfo_t *wall = &drawnode->u.wall; - if (!(wall->blend & PF_NoTexture)) - HWR_GetTexture(wall->texnum, wall->noencore); + if (!(wall->blend & PF_NoTexture)) + HWR_GetTexture(wall->texnum, wall->noencore); - HWR_RenderWall(wall->wallVerts, &wall->Surf, wall->blend, wall->fogwall, - wall->lightlevel, wall->wallcolormap); + HWR_RenderWall(wall->wallVerts, &wall->Surf, wall->blend, wall->fogwall, + wall->lightlevel, wall->wallcolormap); + } break; - } default: break; } @@ -4666,7 +4673,7 @@ static void HWR_ProjectSprite(mobj_t *thing) const boolean vflip = (thing->eflags & MFE_VERTICALFLIP); const boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored); - this_scale = FixedToFloat(interp.scale); + this_scale = FixedToFloat(interp.scale); spritexscale = FixedToFloat(interp.spritexscale); spriteyscale = FixedToFloat(interp.spriteyscale); @@ -5336,9 +5343,6 @@ static void HWR_SetTransformAiming(FTransform *trans) void HWR_SetTransform(float fpov) { - UINT8 viewnum = R_GetViewNumber(); - camera_t *thiscam = &camera[viewnum]; - gl_viewx = FixedToFloat(viewx); gl_viewy = FixedToFloat(viewy); gl_viewz = FixedToFloat(viewz); @@ -5366,17 +5370,17 @@ void HWR_SetTransform(float fpov) HWR_RollTransform(&atransform, viewroll); atransform.splitscreen = splitscreen; - atransform.flip = false; - if ((thiscam->postimg & POSTIMG_FLIP) && !(thiscam->postimg & POSTIMG_MIRROR)) - atransform.flip = true; + const UINT8 postimg = camera[R_GetViewNumber()].postimg; - atransform.mirror = false; - if ((thiscam->postimg & POSTIMG_MIRROR) && !(thiscam->postimg & POSTIMG_FLIP)) - atransform.mirror = true; - - atransform.mirrorflip = false; - if ((thiscam->postimg & POSTIMG_FLIP) && (thiscam->postimg & POSTIMG_MIRROR)) - atransform.mirrorflip = true; + if (postimg & POSTIMG_FLIP) + { + if (postimg & POSTIMG_MIRROR) + atransform.fliptype = TRANSFORM_MIRRORFLIP; + else + atransform.fliptype = TRANSFORM_FLIP; + } + else if (postimg & POSTIMG_MIRROR) + atransform.fliptype = TRANSFORM_MIRROR; // Set transform. GL_SetTransform(&atransform); @@ -5408,7 +5412,7 @@ void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *pl gl_portallist_t portallist; const boolean skybox = (skyboxmo[0] && cv_skybox.value); - const boolean useportals = cv_glportals.value && gl_maphasportals && allow_portals; + const boolean useportals = HWR_UsePortals() && allow_portals; bspfunc bspFunc = (useportals && portalclipline) ? HWR_RenderPortalBSPNode : HWR_RenderBSPNode; portallist.base = portallist.cap = NULL; @@ -5644,6 +5648,7 @@ void HWR_RenderPlayerView(void) { if (cv_ripplewater.value) GL_SetShaderInfo(HWD_SHADERINFO_LEVELTIME, (INT32)leveltime); // The water surface shader needs the leveltime. + const angle_t light_angle = maplighting.angle - viewangle + ANGLE_90; // I fucking hate OGL's coordinate system GL_SetShaderInfo(HWD_SHADERINFO_LIGHT_X, FINECOSINE(light_angle >> ANGLETOFINESHIFT)); GL_SetShaderInfo(HWD_SHADERINFO_LIGHT_Y, 0); @@ -6015,7 +6020,7 @@ static void HWR_DoPostProcessor(player_t *player) if (thiscam->postimg & POSTIMG_WATER) { WAVELENGTH = 5; - AMPLITUDE = 20; + AMPLITUDE = 40; FREQUENCY = 8; } else diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index 0de904716..2696cf89d 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -1431,6 +1431,8 @@ void HWR_DrawMD2(gl_vissprite_t *spr) ? (spr->mobj->rollangle) + (sliptideroll * spr->mobj->player->kartstuff[k_aizdriftstrat]) : (spr->mobj->rollangle); + rollang *= flipfactor; + fixed_t anglef = AngleFixed(rollang); p.rollangle = 0.0f; @@ -1468,8 +1470,7 @@ void HWR_DrawMD2(gl_vissprite_t *spr) p.anglex += flipfactor*FIXED_TO_FLOAT(AngleFixed(interp.roll)); p.anglez -= flipfactor*FIXED_TO_FLOAT(AngleFixed(interp.pitch)); - p.flip = atransform.flip; - p.mirror = atransform.mirror; // from Kart + p.fliptype = atransform.fliptype; GL_SetShader(SHADER_MODEL); // model shader { diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 0533d3676..12ec0cd97 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -102,6 +102,8 @@ RGBA_t myPaletteData[256]; // the palette for converting textures to RGBA static GLint gltexformat = GL_RGB5_A1; GLint screen_width = 0; // used by Draw2DLine() GLint screen_height = 0; +GLint screen_texsizew = 512; // Power-of-two screen texture render resolution +GLint screen_texsizeh = 512; // Power-of-two screen texture render resolution GLbyte screen_depth = 0; GLint maximumAnisotropy = 0; static GLboolean MipMap = GL_FALSE; @@ -129,6 +131,8 @@ GLuint FramebufferObject, FramebufferTexture, RenderbufferObject; boolean supportFBO = false; static boolean fboinit = false; + +static void GL_Framebuffer_DeleteAttachments(void); #endif // Sryder: NextTexAvail is broken for these because palette changes or changes to the texture filter or antialiasing @@ -948,7 +952,7 @@ void GL_UnSetShader(void) static void GL_SetNoTexture(void) { // Disable texture. - if (tex_downloaded != NOTEXTURE_NUM && !currently_batching) + if (tex_downloaded != NOTEXTURE_NUM) { if (NOTEXTURE_NUM == 0) pglGenTextures(1, &NOTEXTURE_NUM); @@ -991,8 +995,43 @@ static void GL_Perspective(GLfloat fovy, GLfloat aspect) // -----------------+ void GL_SetModelView(GLint w, GLint h) { + GLint maxtexsize = 0; //GL_DBG_Printf("SetModelView(): %dx%d\n", (int)w, (int)h); + // 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) + { + GL_FlushScreenTextures(); + +#ifdef USE_FBO_OGL + GL_Framebuffer_DeleteAttachments(); +#endif + } + + screen_width = (GLint)w; + screen_height = (GLint)h; + + screen_texsizew = screen_texsizeh = 512; + + // look for power of two that is large enough for the screen + while (screen_texsizew < w) + screen_texsizew <<= 1; + + while (screen_texsizeh < h) + screen_texsizeh <<= 1; + + pglGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxtexsize); // Get the maximum supported texture size + if ((screen_texsizew > maxtexsize || screen_texsizeh > maxtexsize) && maxtexsize > 0) + { + // The desired screen texture resolution is too big for the player's GPU! + CONS_Alert(CONS_WARNING, "Tried to make a screen texture for a %dx%d game resolution, but your GPU only supports up to %dx%d! Please switch to the software renderer or lower your game resolution.\n", w, h, maxtexsize, maxtexsize); + + // For now, let's just pray that clamping it to the maximum supported size "works" + // There'll be a stretchy "border" artefact, but it's better than failing to make the screen textures + screen_texsizew = min(screen_texsizew, maxtexsize); + screen_texsizeh = min(screen_texsizeh, maxtexsize); + } + pglViewport(0, 0, w, h); pglMatrixMode(GL_PROJECTION); @@ -1038,6 +1077,8 @@ void GL_SetStates(void) pglPolygonOffset(-1.0f, -1.0f); + pglDisable(GL_FOG); + // bp : when no t&l :) pglLoadIdentity(); pglScalef(1.0f, 1.0f, -1.0f); @@ -1122,7 +1163,7 @@ static void GL_Framebuffer_GenerateAttachments(void) fboinit = true; } -void GL_Framebuffer_DeleteAttachments(void) +static void GL_Framebuffer_DeleteAttachments(void) { if (!supportFBO || fboinit == false) return; @@ -2689,8 +2730,7 @@ void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics // pos->mirror is if the screen is flipped horizontally // XOR all the flips together to figure out what culling to use! { - boolean reversecull = (flipped ^ hflipped ^ pos->flip ^ pos->mirror); - if (reversecull) + if ((flipped ^ hflipped ^ !!(pos->fliptype & TRANSFORM_FLIP) ^ !!(pos->fliptype & TRANSFORM_MIRROR))) pglCullFace(GL_FRONT); else pglCullFace(GL_BACK); @@ -2836,14 +2876,21 @@ void GL_SetTransform(FTransform *stransform) used_fov = stransform->fovangle; shearing = stransform->shearing; - if (stransform->mirror) - pglScalef(-stransform->scalex, stransform->scaley, -stransform->scalez); - else if (stransform->mirrorflip) - pglScalef(-stransform->scalex, -stransform->scaley, -stransform->scalez); - else if (stransform->flip) - pglScalef(stransform->scalex, -stransform->scaley, -stransform->scalez); - else - pglScalef(stransform->scalex, stransform->scaley, -stransform->scalez); + switch (stransform->fliptype) + { + case TRANSFORM_MIRROR: + pglScalef(-stransform->scalex, stransform->scaley, -stransform->scalez); + break; + case TRANSFORM_MIRRORFLIP: + pglScalef(-stransform->scalex, -stransform->scaley, -stransform->scalez); + break; + case TRANSFORM_FLIP: + pglScalef(stransform->scalex, -stransform->scaley, -stransform->scalez); + break; + default: // TRANSFORM_NONE + pglScalef(stransform->scalex, stransform->scaley, -stransform->scalez); + break; + } if (stransform->roll) pglRotatef(stransform->rollangle, 0.0f, 0.0f, 1.0f); @@ -2869,7 +2916,7 @@ void GL_SetTransform(FTransform *stransform) if (shearing) { float dy = stransform->viewaiming * 2; - if (stransform->flip || stransform->mirrorflip) + if (stransform->fliptype == TRANSFORM_FLIP || stransform->fliptype == TRANSFORM_MIRRORFLIP) dy *= -1.0f; pglTranslatef(0.0f, -dy/BASEVIDHEIGHT, 0.0f); } @@ -2918,7 +2965,6 @@ void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2]) INT32 x, y; float float_x, float_y, float_nextx, float_nexty; float xfix, yfix; - INT32 texsizew = 512, texsizey = 512; const float blackBack[16] = { @@ -2931,16 +2977,9 @@ void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2]) if (gl_enable_screen_textures != 2) return; - // look for power of two that is large enough for the screen - while (texsizew < screen_width) - texsizew <<= 1; - - while (texsizey < screen_height) - texsizey <<= 1; - // X/Y stretch fix for all resolutions(!) - xfix = (float)(texsizew)/((float)((screen_width)/(float)(SCREENVERTS-1))); - yfix = (float)(texsizey)/((float)((screen_height)/(float)(SCREENVERTS-1))); + xfix = (float)(screen_texsizew)/((float)((screen_width)/(float)(SCREENVERTS-1))); + yfix = (float)(screen_texsizeh)/((float)((screen_height)/(float)(SCREENVERTS-1))); pglDisable(GL_DEPTH_TEST); pglDisable(GL_BLEND); @@ -3014,7 +3053,6 @@ void GL_FlushScreenTextures(void) void GL_DrawScreenTexture(int tex, FSurfaceInfo *surf, FBITFIELD polyflags) { float xfix, yfix; - INT32 texsizew = 512, texsizey = 512; const float screenVerts[12] = { @@ -3029,15 +3067,8 @@ void GL_DrawScreenTexture(int tex, FSurfaceInfo *surf, FBITFIELD polyflags) if (gl_enable_screen_textures != 2) return; - // look for power of two that is large enough for the screen - while (texsizew < screen_width) - texsizew <<= 1; - - while (texsizey < screen_height) - texsizey <<= 1; - - xfix = 1/((float)(texsizew)/((float)((screen_width)))); - yfix = 1/((float)(texsizey)/((float)((screen_height)))); + xfix = 1/((float)(screen_texsizew)/((float)((screen_width)))); + yfix = 1/((float)(screen_texsizeh)/((float)((screen_height)))); // const float screenVerts[12] @@ -3070,7 +3101,6 @@ void GL_DrawScreenTexture(int tex, FSurfaceInfo *surf, FBITFIELD polyflags) // Do screen fades! void GL_DoScreenWipe(int wipeStart, int wipeEnd) { - INT32 texsizew = 512, texsizey = 512; float xfix, yfix; INT32 fademaskdownloaded = tex_downloaded; // the fade mask that has been set @@ -3096,15 +3126,8 @@ void GL_DoScreenWipe(int wipeStart, int wipeEnd) if (!gl_enable_screen_textures) return; - // look for power of two that is large enough for the screen - while (texsizew < screen_width) - texsizew <<= 1; - - while (texsizey < screen_height) - texsizey <<= 1; - - xfix = 1/((float)(texsizew)/((float)((screen_width)))); - yfix = 1/((float)(texsizey)/((float)((screen_height)))); + xfix = 1/((float)(screen_texsizew)/((float)((screen_width)))); + yfix = 1/((float)(screen_texsizeh)/((float)((screen_height)))); // const float screenVerts[12] @@ -3162,7 +3185,6 @@ void GL_DoScreenWipe(int wipeStart, int wipeEnd) void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 downdistort, UINT8 barsize) { - INT32 texsizew = 512, texsizey = 512; int tex = HWD_SCREENTEXTURE_VHS; float xfix, yfix; float fix[8]; @@ -3180,15 +3202,8 @@ void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 if (gl_enable_screen_textures != 2) return; - // look for power of two that is large enough for the screen - while (texsizew < screen_width) - texsizew <<= 1; - - while (texsizey < screen_height) - texsizey <<= 1; - - xfix = 1/((float)(texsizew)/((float)((screen_width)))); - yfix = 1/((float)(texsizey)/((float)((screen_height)))); + xfix = 1/((float)(screen_texsizew)/((float)((screen_width)))); + yfix = 1/((float)(screen_texsizeh)/((float)((screen_height)))); // Slight fuzziness GL_MakeScreenTexture(tex); @@ -3272,19 +3287,11 @@ void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8 // Create a texture from the screen. void GL_MakeScreenTexture(int tex) { - INT32 texsizew = 512, texsizey = 512; boolean firstTime = (screenTextures[tex] == 0); if (!gl_enable_screen_textures) return; - // look for power of two that is large enough for the screen - while (texsizew < screen_width) - texsizew <<= 1; - - while (texsizey < screen_height) - texsizey <<= 1; - // Create screen texture if (firstTime) pglGenTextures(1, &screenTextures[tex]); @@ -3296,10 +3303,10 @@ void GL_MakeScreenTexture(int tex) pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); Clamp2D(GL_TEXTURE_WRAP_S); Clamp2D(GL_TEXTURE_WRAP_T); - pglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, texsizew, texsizey, 0); + pglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, screen_texsizew, screen_texsizeh, 0); } else - pglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, texsizew, texsizey); + pglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, screen_texsizew, screen_texsizeh); tex_downloaded = screenTextures[tex]; } @@ -3310,7 +3317,6 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh float origaspect, newaspect; float xoff = 1, yoff = 1; // xoffset and yoffset for the polygon to have black bars around the screen FRGBAFloat clearColour; - INT32 texsizew = 512, texsizey = 512; float off[12]; float fix[8]; @@ -3318,15 +3324,8 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh if (gl_enable_screen_textures != 2) return; - // look for power of two that is large enough for the screen - while (texsizew < screen_width) - texsizew <<= 1; - - while (texsizey < screen_height) - texsizey <<= 1; - - xfix = 1/((float)(texsizew)/((float)((screen_width)))); - yfix = 1/((float)(texsizey)/((float)((screen_height)))); + xfix = 1/((float)(screen_texsizew)/((float)((screen_width)))); + yfix = 1/((float)(screen_texsizeh)/((float)((screen_height)))); origaspect = (float)screen_width / screen_height; newaspect = (float)width / height; diff --git a/src/hardware/r_opengl/r_opengl.h b/src/hardware/r_opengl/r_opengl.h index 2f2b9ba98..b70febad4 100644 --- a/src/hardware/r_opengl/r_opengl.h +++ b/src/hardware/r_opengl/r_opengl.h @@ -103,8 +103,6 @@ extern PFNglGetString pglGetString; #endif #ifdef USE_FBO_OGL -void GL_Framebuffer_DeleteAttachments(void); - void GL_Framebuffer_Unbind(void); void GL_Framebuffer_Enable(void); void GL_Framebuffer_Disable(void); diff --git a/src/hu_stuff.c b/src/hu_stuff.c index 339722661..2821c4021 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -2203,6 +2203,10 @@ void HU_Drawer(void) if (cechotimer) HU_DrawCEcho(); + // draw song credits + if (cv_songcredits.value) + HU_DrawSongCredits(); + if (!( Playing() || demo.playback ) || gamestate == GS_INTERMISSION || gamestate == GS_CUTSCENE || gamestate == GS_CREDITS || gamestate == GS_EVALUATION @@ -2236,10 +2240,6 @@ void HU_Drawer(void) if (gamestate != GS_LEVEL) return; - // draw song credits - if (cv_songcredits.value) - HU_DrawSongCredits(); - // draw desynch text if (hu_resynching #ifdef SATURNPAK diff --git a/src/i_system.h b/src/i_system.h index 90887444f..e7fb26a41 100644 --- a/src/i_system.h +++ b/src/i_system.h @@ -112,77 +112,6 @@ ticcmd_t *I_BaseTiccmd4(void); */ void I_Quit(void) FUNCNORETURN; -typedef enum -{ - EvilForce = -1, - //Constant - ConstantForce = 0, - //Ramp - RampForce, - //Periodics - SquareForce, - SineForce, - TriangleForce, - SawtoothUpForce, - SawtoothDownForce, - //MAX - NumberofForces, -} FFType; - -typedef struct JoyFF_s -{ - INT32 ForceX; ///< The X of the Force's Vel - INT32 ForceY; ///< The Y of the Force's Vel - //All - UINT32 Duration; ///< The total duration of the effect, in microseconds - INT32 Gain; //< /The gain to be applied to the effect, in the range from 0 through 10,000. - //All, CONSTANTFORCE -10,000 to 10,000 - INT32 Magnitude; ///< Magnitude of the effect, in the range from 0 through 10,000. - //RAMPFORCE - INT32 Start; ///< Magnitude at the start of the effect, in the range from -10,000 through 10,000. - INT32 End; ///< Magnitude at the end of the effect, in the range from -10,000 through 10,000. - //PERIODIC - INT32 Offset; ///< Offset of the effect. - UINT32 Phase; ///< Position in the cycle of the periodic effect at which playback begins, in the range from 0 through 35,999 - UINT32 Period; ///< Period of the effect, in microseconds. -} JoyFF_t; - -/** \brief Forcefeedback for the first joystick - - \param Type what kind of Effect - \param Effect Effect Info - - \return void -*/ - -void I_Tactile(FFType Type, const JoyFF_t *Effect); - -/** \brief Forcefeedback for the second joystick - - \param Type what kind of Effect - \param Effect Effect Info - - \return void -*/ -void I_Tactile2(FFType Type, const JoyFF_t *Effect); - -/** \brief Forcefeedback for the third joystick - -\param Type what kind of Effect -\param Effect Effect Info - -\return void -*/ -void I_Tactile3(FFType Type, const JoyFF_t *Effect); - -/** \brief Forcefeedback for the fourth joystick - -\param Type what kind of Effect -\param Effect Effect Info - -\return void -*/ -void I_Tactile4(FFType Type, const JoyFF_t *Effect); /** \brief to set up the first joystick scale */ diff --git a/src/k_kart.c b/src/k_kart.c index 466c5cc9f..c63433fb4 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -10884,6 +10884,9 @@ static void K_drawKartMinimap(void) angle_t ang = R_InterpolateAngle(mobj->old_angle, mobj->angle); + if (encoremode) + ang = ANGLE_180 - ang; + if (mobj->colorized) colormap = R_GetTranslationColormap(TC_RAINBOW, mobj->color, GTC_CACHE); else diff --git a/src/lua_baselib.c b/src/lua_baselib.c index 10da0d1a3..0ccc7d8ed 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -1396,11 +1396,9 @@ static int lib_pSetMobjStateNF(lua_State *L) static int lib_pDoSuperTransformation(lua_State *L) { player_t *player = *((player_t **)luaL_checkudata(L, 1, META_PLAYER)); - boolean giverings = lua_optboolean(L, 2); NOHUD if (!player) return LUA_ErrInvalid(L, "player_t"); - P_DoSuperTransformation(player, giverings); return 0; } @@ -2452,16 +2450,15 @@ static int lib_gExitLevel(lua_State *L) static int lib_gIsSpecialStage(lua_State *L) { - INT32 mapnum = luaL_optinteger(L, 1, gamemap); //HUDSAFE - lua_pushboolean(L, G_IsSpecialStage(mapnum)); + lua_pushboolean(L, false); return 1; } static int lib_gGametypeUsesLives(lua_State *L) { //HUDSAFE - lua_pushboolean(L, G_GametypeUsesLives()); + lua_pushboolean(L, false); return 1; } diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index 7ddf1a1d7..e1e246d28 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -629,7 +629,7 @@ static int cvar_get(lua_State *L) break; default: if (devparm) - return luaL_error(L, LUA_QL("consvar_t") " has no field named " LUA_QS, field); + return luaL_error(L, LUA_QL("consvar_t") " has no field named " LUA_QS, lua_tostring(L, 2)); else return 0; } diff --git a/src/lua_infolib.c b/src/lua_infolib.c index a82fc947d..3ff2d97ae 100644 --- a/src/lua_infolib.c +++ b/src/lua_infolib.c @@ -385,7 +385,7 @@ static int state_get(lua_State *L) default: { if (devparm) - return luaL_error(L, LUA_QL("state_t") " has no field named " LUA_QS, field); + return luaL_error(L, LUA_QL("state_t") " has no field named " LUA_QS, lua_tostring(L, 2)); return 0; } } @@ -462,7 +462,7 @@ static int state_set(lua_State *L) break; default: - return luaL_error(L, LUA_QL("state_t") " has no field named " LUA_QS, field); + return luaL_error(L, LUA_QL("state_t") " has no field named " LUA_QS, lua_tostring(L, 2)); } return 0; diff --git a/src/lua_mobjlib.c b/src/lua_mobjlib.c index 44c43297f..504a1e130 100644 --- a/src/lua_mobjlib.c +++ b/src/lua_mobjlib.c @@ -877,7 +877,7 @@ static int mapthing_get(lua_State *L) break; default: if (devparm) - return luaL_error(L, LUA_QL("mapthing_t") " has no field named " LUA_QS, field); + return luaL_error(L, LUA_QL("mapthing_t") " has no field named " LUA_QS, lua_tostring(L, 2)); else return 0; } @@ -931,7 +931,7 @@ static int mapthing_set(lua_State *L) mt->mobj = *((mobj_t **)luaL_checkudata(L, 3, META_MOBJ)); break; default: - return luaL_error(L, LUA_QL("mapthing_t") " has no field named " LUA_QS, field); + return luaL_error(L, LUA_QL("mapthing_t") " has no field named " LUA_QS, lua_tostring(L, 2)); } return 0; diff --git a/src/lua_playerlib.c b/src/lua_playerlib.c index 0b3f9cc1d..9562c5679 100644 --- a/src/lua_playerlib.c +++ b/src/lua_playerlib.c @@ -707,8 +707,8 @@ static int kartstuff_len(lua_State *L) return 1; } -#define NOFIELD luaL_error(L, LUA_QL("ticcmd_t") " has no field named " LUA_QS, field) -#define NOSET luaL_error(L, LUA_QL("ticcmd_t") " field " LUA_QS " should not be set directly.", field) +#define NOFIELD luaL_error(L, LUA_QL("ticcmd_t") " has no field named " LUA_QS, lua_tostring(L, 2)) +#define NOSET luaL_error(L, LUA_QL("ticcmd_t") " field " LUA_QS " should not be set directly.", lua_tostring(L, 2)) enum ticcmd_e { diff --git a/src/m_cheat.c b/src/m_cheat.c index 1cdb57419..d786775c6 100644 --- a/src/m_cheat.c +++ b/src/m_cheat.c @@ -57,29 +57,11 @@ typedef struct // CHEAT Structures // ========================================================================== -// Cheat responders -/*static UINT8 cheatf_ultimate(void) -{ - if (menuactive && (currentMenu != &MainDef && currentMenu != &SP_LoadDef)) - return 0; // Only on the main menu, or the save select! - - S_StartSound(0, sfx_itemup); - ultimate_selectable = (!ultimate_selectable); - - // If on the save select, move to what is now Ultimate Mode! - if (currentMenu == &SP_LoadDef) - M_ForceSaveSlotSelected(NOSAVESLOT); - return 1; -}*/ - static UINT8 cheatf_warp(void) { UINT8 i; boolean success = false; - /*if (modifiedgame) - return 0;*/ - if (menuactive && currentMenu != &MainDef) return 0; // Only on the main menu! @@ -134,18 +116,6 @@ static UINT8 cheatf_devmode(void) } #endif -/*static cheatseq_t cheat_ultimate = { - 0, cheatf_ultimate, - { SCRAMBLE('u'), SCRAMBLE('l'), SCRAMBLE('t'), SCRAMBLE('i'), SCRAMBLE('m'), SCRAMBLE('a'), SCRAMBLE('t'), SCRAMBLE('e'), 0xff } -};*/ - -/*static cheatseq_t cheat_ultimate_joy = { - 0, cheatf_ultimate, - { SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_UPARROW), SCRAMBLE(KEY_DOWNARROW), SCRAMBLE(KEY_DOWNARROW), - SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_RIGHTARROW), SCRAMBLE(KEY_LEFTARROW), SCRAMBLE(KEY_RIGHTARROW), - SCRAMBLE(KEY_ENTER), 0xff } -};*/ - static cheatseq_t cheat_warp = { 0, cheatf_warp, //{ SCRAMBLE('r'), SCRAMBLE('e'), SCRAMBLE('d'), SCRAMBLE('x'), SCRAMBLE('v'), SCRAMBLE('i'), 0xff } @@ -376,70 +346,6 @@ void Command_Hurtme_f(void) P_DamageMobj(players[consoleplayer].mo, NULL, NULL, atoi(COM_Argv(1))); } -// Moves the NiGHTS player to another axis within the current mare -/*void Command_JumpToAxis_f(void) -{ - REQUIRE_DEVMODE; - REQUIRE_INLEVEL; - REQUIRE_SINGLEPLAYER; - - if (COM_Argc() != 2) - { - CONS_Printf(M_GetText("jumptoaxis : Jump to axis within current mare.\n")); - return; - } - - P_TransferToAxis(&players[consoleplayer], atoi(COM_Argv(1))); -} - -void Command_Charability_f(void) -{ - REQUIRE_DEVMODE; - REQUIRE_INLEVEL; - REQUIRE_SINGLEPLAYER; - - if (COM_Argc() < 3) - { - CONS_Printf(M_GetText("charability <1/2> : change character abilities\n")); - return; - } - - if (atoi(COM_Argv(1)) == 1) - players[consoleplayer].charability = (UINT8)atoi(COM_Argv(2)); - else if (atoi(COM_Argv(1)) == 2) - players[consoleplayer].charability2 = (UINT8)atoi(COM_Argv(2)); - else - CONS_Printf(M_GetText("charability <1/2> : change character abilities\n")); -} - -void Command_Charspeed_f(void) -{ - REQUIRE_DEVMODE; - REQUIRE_INLEVEL; - REQUIRE_SINGLEPLAYER; - - if (COM_Argc() < 3) - { - CONS_Printf(M_GetText("charspeed : set character speed\n")); - return; - } - - if (!strcasecmp(COM_Argv(1), "normalspeed")) - players[consoleplayer].normalspeed = atoi(COM_Argv(2))< : set character speed\n")); -}*/ - void Command_RTeleport_f(void) { fixed_t intx, inty, intz; @@ -682,28 +588,6 @@ void Command_Savecheckpoint_f(void) CONS_Printf(M_GetText("Temporary checkpoint created at %d, %d, %d\n"), players[consoleplayer].starpostx, players[consoleplayer].starposty, players[consoleplayer].starpostz); } -// Like M_GetAllEmeralds() but for console devmode junkies. -/*void Command_Getallemeralds_f(void) -{ - REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; - REQUIRE_PANDORA; - - emeralds = ((EMERALD7)*2)-1; - - CONS_Printf(M_GetText("You now have all 7 emeralds.\n")); -} - -void Command_Resetemeralds_f(void) -{ - REQUIRE_SINGLEPLAYER; - REQUIRE_PANDORA; - - emeralds = 0; - - CONS_Printf(M_GetText("Emeralds reset to zero.\n")); -}*/ - void Command_Devmode_f(void) { #ifndef _DEBUG @@ -730,63 +614,6 @@ void Command_Devmode_f(void) G_SetGameModified(multiplayer, true); } -/*void Command_Setrings_f(void) -{ - REQUIRE_INLEVEL; - REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; - REQUIRE_PANDORA; - - if (COM_Argc() > 1) - { - // P_GivePlayerRings does value clamping - players[consoleplayer].health = players[consoleplayer].mo->health = 1; - P_GivePlayerRings(&players[consoleplayer], atoi(COM_Argv(1))); - if (!G_IsSpecialStage(gamemap) || !useNightsSS) - players[consoleplayer].totalring -= atoi(COM_Argv(1)); //undo totalring addition done in P_GivePlayerRings - - G_SetGameModified(multiplayer); - } -} - -void Command_Setlives_f(void) -{ - REQUIRE_INLEVEL; - REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; - REQUIRE_PANDORA; - - if (COM_Argc() > 1) - { - // P_GivePlayerLives does value clamping - players[consoleplayer].lives = 0; - P_GivePlayerLives(&players[consoleplayer], atoi(COM_Argv(1))); - - G_SetGameModified(multiplayer); - } -} - -void Command_Setcontinues_f(void) -{ - REQUIRE_INLEVEL; - REQUIRE_SINGLEPLAYER; - REQUIRE_NOULTIMATE; - REQUIRE_PANDORA; - - if (COM_Argc() > 1) - { - INT32 numcontinues = atoi(COM_Argv(1)); - if (numcontinues > 99) - numcontinues = 99; - else if (numcontinues < 0) - numcontinues = 0; - - players[consoleplayer].continues = numcontinues; - - G_SetGameModified(multiplayer); - } -}*/ - // // OBJECTPLACE (and related variables) // @@ -1006,17 +833,6 @@ void OP_NightsObjectplace(player_t *player) P_SpawnHoopsAndRings(mt); } - // This places a bumper! - /*if (cmd->buttons & BT_SPECTATE) - { - player->pflags |= PF_ATTACKDOWN; - if (!OP_HeightOkay(player, false)) - return; - - mt = OP_CreateNewMapThing(player, (UINT16)mobjinfo[MT_NIGHTSBUMPER].doomednum, false); - P_SpawnMapThing(mt); - }*/ - // This places a ring! if (cmd->buttons & BT_BACKWARD) { @@ -1163,12 +979,7 @@ void OP_ObjectplaceMovement(player_t *player) return; } - /*if (cmd->buttons & BT_FORWARD) - { - OP_CycleThings(-1); - player->pflags |= PF_ATTACKDOWN; - } - else*/ if (cmd->buttons & BT_DRIFT) + if (cmd->buttons & BT_DRIFT) { OP_CycleThings(1); player->pflags |= PF_ATTACKDOWN; diff --git a/src/m_menu.c b/src/m_menu.c index c1abd2903..2fb38a4d5 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -1263,153 +1263,74 @@ static menuitem_t OP_AllControlsMenu[] = {IT_CONTROL, NULL, "Custom Action 3", M_ChangeControl, gc_custom3 }, }; +#define OP_JOYMENU(pnum) \ + {IT_HEADER, NULL, "Gameplay Controls", NULL, 7}, \ + {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[pnum] , 15}, \ + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[pnum] , 20}, \ + {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[pnum] , 25}, \ + {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[pnum] , 30}, \ + {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[pnum] , 35}, \ + {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[pnum] , 40}, \ + {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[pnum] , 45}, \ + {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[pnum] , 50}, \ + {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[pnum] , 55}, \ + {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[pnum] , 60}, \ + {IT_HEADER, NULL, "Camera Controls", NULL, 67}, \ + {IT_STRING | IT_CVAR, NULL, "Look Up/Down" , &cv_lookaxis[pnum] , 75}, \ + {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_camturnaxis[pnum] , 80}, \ + {IT_STRING | IT_CVAR, NULL, "Strafe Left/Right" , &cv_camstrafeaxis[pnum] , 85}, \ + {IT_HEADER, NULL, "Deadzones", NULL, 92}, \ + {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[pnum] , 100}, \ + {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[pnum] , 105}, \ + {IT_HEADER, NULL, "Miscellaneous", NULL, 112}, \ + {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[pnum] , 120}, \ + {IT_STRING | IT_CVAR, NULL, "Set LED to Player color", &cv_gamepadled[pnum] , 125}, + static menuitem_t OP_Joystick1Menu[] = { - {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup1PJoystickMenu , 0}, - - {IT_HEADER, NULL, "Gameplay Controls", NULL, 7}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[0] , 15}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[0] , 20}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[0] , 25}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[0] , 30}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[0] , 35}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[0] , 40}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[0] , 45}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[0] , 50}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[0] , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[0] , 60}, - - {IT_HEADER, NULL, "Camera Controls", NULL, 67}, - {IT_STRING | IT_CVAR, NULL, "Look Up/Down" , &cv_lookaxis[0] , 75}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_camturnaxis[0] , 80}, - {IT_STRING | IT_CVAR, NULL, "Strafe Left/Right" , &cv_camstrafeaxis[0] , 85}, - - {IT_HEADER, NULL, "Deadzones", NULL, 92}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[0] , 100}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[0] , 105}, - - {IT_HEADER, NULL, "Miscellaneous", NULL, 112}, - {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[0] , 120}, - {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[0] , 125}, - {IT_STRING | IT_CVAR, NULL, "Flash LED on powerups" , &cv_ledpowerup[0] , 130}, + {IT_STRING | IT_CALL, NULL, "Select Gamepad...", M_Setup1PJoystickMenu, 0}, + OP_JOYMENU(0) }; static menuitem_t OP_Joystick2Menu[] = { - {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup2PJoystickMenu , 10}, - - {IT_HEADER, NULL, "Gameplay Controls", NULL, 7}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[1] , 15}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[1] , 20}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[1] , 25}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[1] , 30}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[1] , 35}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[1] , 40}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[1] , 45}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[1] , 50}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[1] , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[1] , 60}, - - {IT_HEADER, NULL, "Camera Controls", NULL, 67}, - {IT_STRING | IT_CVAR, NULL, "Look Up/Down" , &cv_lookaxis[1] , 75}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_camturnaxis[1] , 80}, - {IT_STRING | IT_CVAR, NULL, "Strafe Left/Right" , &cv_camstrafeaxis[1] , 85}, - - {IT_HEADER, NULL, "Deadzones", NULL, 92}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[1] , 100}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[1] , 105}, - - {IT_HEADER, NULL, "Miscellaneous", NULL, 112}, - {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[1] , 120}, - {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[1] , 125}, - {IT_STRING | IT_CVAR, NULL, "Flash LED on powerups" , &cv_ledpowerup[1] , 130}, + {IT_STRING | IT_CALL, NULL, "Select Gamepad...", M_Setup2PJoystickMenu, 0}, + OP_JOYMENU(1) }; static menuitem_t OP_Joystick3Menu[] = { - {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup3PJoystickMenu , 10}, - - {IT_HEADER, NULL, "Gameplay Controls", NULL, 7}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[2] , 15}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[2] , 20}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[2] , 25}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[2] , 30}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[2] , 35}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[2] , 40}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[2] , 45}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[2] , 50}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[2] , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[2] , 60}, - - {IT_HEADER, NULL, "Camera Controls", NULL, 67}, - {IT_STRING | IT_CVAR, NULL, "Look Up/Down" , &cv_lookaxis[2] , 75}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_camturnaxis[2] , 80}, - {IT_STRING | IT_CVAR, NULL, "Strafe Left/Right" , &cv_camstrafeaxis[2] , 85}, - - {IT_HEADER, NULL, "Deadzones", NULL, 92}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[2] , 100}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[2] , 105}, - - {IT_HEADER, NULL, "Miscellaneous", NULL, 112}, - {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[2] , 120}, - {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[2] , 125}, - {IT_STRING | IT_CVAR, NULL, "Flash LED on powerups" , &cv_ledpowerup[2] , 130}, + {IT_STRING | IT_CALL, NULL, "Select Gamepad...", M_Setup3PJoystickMenu, 0}, + OP_JOYMENU(2) }; static menuitem_t OP_Joystick4Menu[] = { - {IT_STRING | IT_CALL, NULL, "Select Gamepad..." , M_Setup4PJoystickMenu , 10}, - - {IT_HEADER, NULL, "Gameplay Controls", NULL, 7}, - {IT_STRING | IT_CVAR, NULL, "Aim Forward/Back" , &cv_aimaxis[3] , 15}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_turnaxis[3] , 20}, - {IT_STRING | IT_CVAR, NULL, "Accelerate" , &cv_moveaxis[3] , 25}, - {IT_STRING | IT_CVAR, NULL, "Brake" , &cv_brakeaxis[3] , 30}, - {IT_STRING | IT_CVAR, NULL, "Drift" , &cv_driftaxis[3] , 35}, - {IT_STRING | IT_CVAR, NULL, "Use Item" , &cv_fireaxis[3] , 40}, - {IT_STRING | IT_CVAR, NULL, "Look Backward" , &cv_lookbackaxis[3] , 45}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 1" , &cv_custom1axis[3] , 50}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 2" , &cv_custom2axis[3] , 55}, - {IT_STRING | IT_CVAR, NULL, "Custom Button 3" , &cv_custom3axis[3] , 60}, - - {IT_HEADER, NULL, "Camera Controls", NULL, 67}, - {IT_STRING | IT_CVAR, NULL, "Look Up/Down" , &cv_lookaxis[3] , 75}, - {IT_STRING | IT_CVAR, NULL, "Turn Left/Right" , &cv_camturnaxis[3] , 80}, - {IT_STRING | IT_CVAR, NULL, "Strafe Left/Right" , &cv_camstrafeaxis[3] , 85}, - - {IT_HEADER, NULL, "Deadzones", NULL, 92}, - {IT_STRING | IT_CVAR, NULL, "X deadzone" , &cv_xdeadzone[3] , 100}, - {IT_STRING | IT_CVAR, NULL, "Y deadzone" , &cv_ydeadzone[3] , 105}, - - {IT_HEADER, NULL, "Miscellaneous", NULL, 112}, - {IT_STRING | IT_CVAR, NULL, "Controller Rumble" , &cv_rumble[3] , 120}, - {IT_STRING | IT_CVAR, NULL, "Set LED to skin color" , &cv_gamepadled[3] , 125}, - {IT_STRING | IT_CVAR, NULL, "Flash LED on powerups" , &cv_ledpowerup[3] , 130}, + {IT_STRING | IT_CALL, NULL, "Select Gamepad...", M_Setup4PJoystickMenu, 0}, + OP_JOYMENU(3) }; static menuitem_t OP_JoystickSetMenu[] = { - {IT_CALL | IT_NOTHING, "None", NULL, M_AssignJoystick, LINEHEIGHT+5}, - {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*2)+5}, - {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*3)+5}, - {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*4)+5}, - {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*5)+5}, - {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*6)+5}, - {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*7)+5}, - {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*8)+5}, + {IT_CALL | IT_NOTHING, "None", NULL, M_AssignJoystick, LINEHEIGHT+5}, + {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*2)+5}, + {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*3)+5}, + {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*4)+5}, + {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*5)+5}, + {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*6)+5}, + {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*7)+5}, + {IT_CALL | IT_NOTHING, "", NULL, M_AssignJoystick, (LINEHEIGHT*8)+5}, }; //WTF static menuitem_t OP_MouseOptionsMenu[] = { - {IT_STRING | IT_CVAR, NULL, "Use Mouse", &cv_usemouse, 10}, + {IT_STRING | IT_CVAR, NULL, "Use Mouse", &cv_usemouse, 10}, - {IT_STRING | IT_CVAR, NULL, "Mouse Turning", &cv_mouseturn, 20}, - {IT_STRING | IT_CVAR, NULL, "Invert Mouse", &cv_invertmouse, 30}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Mouse X Speed", &cv_mousesens, 40}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Mouse Y Speed", &cv_mouseysens, 50}, + {IT_STRING | IT_CVAR, NULL, "Mouse Turning", &cv_mouseturn, 20}, + {IT_STRING | IT_CVAR, NULL, "Invert Mouse", &cv_invertmouse, 30}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Mouse X Speed", &cv_mousesens, 40}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Mouse Y Speed", &cv_mouseysens, 50}, }; static const char* OP_MouseTooltips[] = @@ -1555,15 +1476,17 @@ static menuitem_t OP_ExpOptionsMenu[] = {IT_STRING | IT_CVAR, NULL, "FPS counter sampling", &cv_accuratefps, 50}, + {IT_STRING | IT_CVAR, NULL, "Votescreen Scaling", &cv_votebgscaling, 60}, + #ifdef HWRENDER - {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 60}, + {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 70}, #ifdef USE_FBO_OGL - {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_glframebuffer, 65}, - {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 75}, - {IT_DISABLED, NULL, "", NULL, 85}, // dummy text + {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_glframebuffer, 75}, + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 85}, + {IT_DISABLED, NULL, "", NULL, 95}, // dummy text #else - {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 70}, - {IT_DISABLED, NULL, "", NULL, 80}, // dummy text + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 80}, + {IT_DISABLED, NULL, "", NULL, 90}, // dummy text #endif #endif }; @@ -1578,6 +1501,7 @@ static const char* OP_ExpTooltips[] = //"Should the directional lightning be randomized each map?\nTakes effect on next map load.", "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?? + "Different methods of scaling the votescreen backgrounds.", #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 @@ -1791,9 +1715,11 @@ static menuitem_t OP_FocusOptionsMenu[] = {IT_STRING|IT_CVAR, NULL, "Pause Game While Unfocused", &cv_pauseifunfocused, 60}, - {IT_STRING|IT_CVAR, NULL, "Show \"FOCUS LOST\"", &cv_showfocuslost, 80}, + {IT_STRING|IT_CVAR, NULL, "Background FPS Cap", &cv_fpscapbg, 80}, - {IT_STRING|IT_CVAR, NULL, "Always Grab Mouse While Focused", &cv_alwaysgrabmouse, 100}, + {IT_STRING|IT_CVAR, NULL, "Show \"FOCUS LOST\"", &cv_showfocuslost, 100}, + + {IT_STRING|IT_CVAR, NULL, "Always Grab Mouse While Focused", &cv_alwaysgrabmouse, 120}, }; static const char* OP_FocusOptionsTooltips[] = @@ -1802,6 +1728,7 @@ static const char* OP_FocusOptionsTooltips[] = "Should music play while the game is unfocused?", "Should soundeffects play while the game is unfocused?", "Should the game pause while the game is unfocused?", + "Set manual framerate cap while the game is unfocused.", "Should the FOCUS LOST window appear\n while the game is unfocused?", "Should the mouse cursor be grabbed and hidden\n while the game is in focus?", }; @@ -1950,76 +1877,38 @@ static const char* OP_CamOptionsTooltips[] = NULL, }; +#define OP_CAMMENU(pnum) \ +{IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[pnum], 30}, \ +{IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[pnum], 50}, \ +{IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[pnum], 60}, \ +{IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[pnum], 70}, \ +{IT_STRING | IT_CVAR, NULL, "Camera Lookback Momentum", &cv_lookbackmom[pnum], 90}, \ +{IT_STRING | IT_CVAR, NULL, "Camera Vertical Look", &cv_verticallook[pnum], 100}, \ +{IT_STRING | IT_CVAR, NULL, "Freecam Speed", &cv_freecam_speed[pnum], 120}, \ +{IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[pnum], 135}, \ + static menuitem_t OP_Player1CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 1 Camera Options", NULL, 0}, - - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[0], 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[0], 50}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[0], 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[0], 70}, - - {IT_STRING | IT_CVAR, NULL, "Camera Lookback Momentum", &cv_lookbackmom[0], 90}, - - {IT_STRING | IT_CVAR, NULL, "Camera Vertical Look", &cv_verticallook[0], 100}, - - {IT_STRING | IT_CVAR, NULL, "Freecam Speed", &cv_freecam_speed[0], 120}, - - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[0], 135}, + OP_CAMMENU(0) }; static menuitem_t OP_Player2CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 2 Camera Options", NULL, 0}, - - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[1], 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[1], 50}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[1], 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[1], 70}, - - {IT_STRING | IT_CVAR, NULL, "Camera Lookback Momentum", &cv_lookbackmom[1], 90}, - - {IT_STRING | IT_CVAR, NULL, "Camera Vertical Look", &cv_verticallook[1], 100}, - - {IT_STRING | IT_CVAR, NULL, "Freecam Speed", &cv_freecam_speed[1], 120}, - - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[1], 135}, + OP_CAMMENU(1) }; static menuitem_t OP_Player3CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 3 Camera Options", NULL, 0}, - - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[2], 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[2], 50}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[2], 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[2], 70}, - - {IT_STRING | IT_CVAR, NULL, "Camera Lookback Momentum", &cv_lookbackmom[2], 90}, - - {IT_STRING | IT_CVAR, NULL, "Camera Vertical Look", &cv_verticallook[2], 100}, - - {IT_STRING | IT_CVAR, NULL, "Freecam Speed", &cv_freecam_speed[2], 120}, - - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[2], 135}, + OP_CAMMENU(2) }; static menuitem_t OP_Player4CamOptionsMenu[] = { {IT_HEADER, NULL, "Player 4 Camera Options", NULL, 0}, - - {IT_STRING | IT_CVAR, NULL, "Flipcam", &cv_flipcam[3], 30}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Distance", &cv_cam_dist[3], 50}, - {IT_STRING | IT_CVAR | IT_CV_BIGFLOAT, NULL, "Camera Height", &cv_cam_height[3], 60}, - {IT_STRING | IT_CVAR, NULL, "Camera Speed", &cv_cam_speed[3], 70}, - - {IT_STRING | IT_CVAR, NULL, "Camera Lookback Momentum", &cv_lookbackmom[3], 90}, - - {IT_STRING | IT_CVAR, NULL, "Camera Vertical Look", &cv_verticallook[3], 100}, - - {IT_STRING | IT_CVAR, NULL, "Freecam Speed", &cv_freecam_speed[3], 120}, - - {IT_STRING | IT_CVAR, NULL, "Third Person Camera", &cv_chasecam[3], 135}, + OP_CAMMENU(3) }; static const char* OP_PlayerCamOptionsTooltips[] = @@ -3178,10 +3067,10 @@ menu_t OP_ControlsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_ControlsMenu, &OP_MainDe //WTF menu_t OP_MouseOptionsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_MouseOptionsMenu, &OP_ControlsDef, 60, 30); menu_t OP_AllControlsDef = CONTROLMENUSTYLE(OP_AllControlsMenu, &OP_ControlsDef); -menu_t OP_Joystick1Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick1Menu, &OP_AllControlsDef, 60, 36); -menu_t OP_Joystick2Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick2Menu, &OP_AllControlsDef, 60, 36); -menu_t OP_Joystick3Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick3Menu, &OP_AllControlsDef, 60, 36); -menu_t OP_Joystick4Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick4Menu, &OP_AllControlsDef, 60, 36); +menu_t OP_Joystick1Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick1Menu, &OP_AllControlsDef, 30, 36); +menu_t OP_Joystick2Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick2Menu, &OP_AllControlsDef, 30, 36); +menu_t OP_Joystick3Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick3Menu, &OP_AllControlsDef, 30, 36); +menu_t OP_Joystick4Def = DEFAULTSCROLLSTYLE("M_CONTRO", OP_Joystick4Menu, &OP_AllControlsDef, 30, 36); menu_t OP_JoystickSetDef = { "M_CONTRO", @@ -3271,7 +3160,7 @@ menu_t OP_ChatOptionsDef = DEFAULTMENUSTYLE("M_HUD", OP_ChatOptionsMenu, &OP_HUD menu_t OP_SoundAdvancedDef = DEFAULTSCROLLSTYLE("M_SOUND", OP_SoundAdvancedMenu, &OP_SoundOptionsDef, 30, 30); -menu_t OP_FocusOptionsDef = DEFAULTMENUSTYLE(NULL, OP_FocusOptionsMenu, &OP_MainDef, 25, 30); +menu_t OP_FocusOptionsDef = DEFAULTMENUSTYLE(NULL, OP_FocusOptionsMenu, &OP_MainDef, 17, 30); menu_t OP_GameOptionsDef = DEFAULTMENUSTYLE("M_GAME", OP_GameOptionsMenu, &OP_MainDef, 30, 20); menu_t OP_ServerOptionsDef = DEFAULTMENUSTYLE("M_SERVER", OP_ServerOptionsMenu, &OP_MainDef, 24, 20); @@ -6356,25 +6245,41 @@ static boolean M_AddonsRefresh(void) { S_StartSound(NULL, sfx_s26d); if (refreshdirmenu & REFRESHDIR_MAX) - message = va("%c%s\x80\nMaximum number of addons reached.\nA file could not be loaded.\nIf you wish to play with this addon, restart the game to clear existing ones.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname); + { + if (refreshdirname) + message = va("%c%s\x80\nMaximum number of addons reached.\nA file could not be loaded.\nIf you wish to play with this addon, restart the game to clear existing ones.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname); + else + message = va("%c\x80 Maximum number of addons reached.\nA file could not be loaded.\nIf you wish to play with this addon, restart the game to clear existing ones.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT))); + } else - message = va("%c%s\x80\nA file was not loaded.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname); + { + if (refreshdirname) + message = va("%c%s\x80\nA file was not loaded.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname); + else + message = va("%c\x80 A file was not loaded.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT))); + } } else if (refreshdirmenu & (REFRESHDIR_WARNING | REFRESHDIR_ERROR)) { S_StartSound(NULL, sfx_s224); - message = va("%c%s\x80\nA file was loaded with %s.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname, ((refreshdirmenu & REFRESHDIR_ERROR) ? "errors" : "warnings")); + if (refreshdirname) + message = va("%c%s\x80\nA file was loaded with %s.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname, ((refreshdirmenu & REFRESHDIR_ERROR) ? "errors" : "warnings")); + else + message = va("%c\x80 A file was loaded with %s.\nCheck the console log for more information.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), ((refreshdirmenu & REFRESHDIR_ERROR) ? "errors" : "warnings")); } else if (majormods && !prevmajormods) { S_StartSound(NULL, sfx_s221); - message = va("%c%s\x80\nYou've loaded a gameplay-modifying addon.\n\nRecord Attack data will be saved to a seperate save file.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname); + if (refreshdirname) + message = va("%c%s\x80\nYou've loaded a gameplay-modifying addon.\n\nRecord Attack data will be saved to a seperate save file.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), refreshdirname); + else + message = va("%c\x80 You've loaded a gameplay-modifying addon.\n\nRecord Attack data will be saved to a seperate save file.\n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT))); prevmajormods = majormods; } if (message) { - M_StartMessage(message,M_AddonsClearName,MM_EVENTHANDLER); + M_StartMessage(message, M_AddonsClearName, MM_EVENTHANDLER); return true; } @@ -11442,7 +11347,7 @@ static void M_HandleSetupMultiPlayer(INT32 choice) boolean exitmenu = false; // exit to previous menu and send name change const boolean gridselect = (cv_skinselectmenu.value == SKINMENUTYPE_GRID || cv_skinselectmenu.value == SKINMENUTYPE_EXTENDED); // menus with "grids" - if ((choice == gamecontrol[0][gc_fire][0] || choice == gamecontrol[0][gc_fire][1]) && (itemOn == 2 || (gridselect && itemOn == 1))) + if ((choice == gamecontrol[0][gc_fire][0] || choice == gamecontrol[0][gc_fire][1]) && (itemOn == 2 || (gridselect && itemOn == 1 && choice != KEY_ENTER))) choice = KEY_BACKSPACE; // Hack to allow resetting prefcolor on controllers #define BREAKWHENLOCKED {\ diff --git a/src/m_misc.c b/src/m_misc.c index 6b9699243..c44086f4c 100644 --- a/src/m_misc.c +++ b/src/m_misc.c @@ -549,6 +549,28 @@ void M_FirstLoadConfig(void) CV_ToggleExecVersion(false); } +static boolean M_BackupConfig(const char *filename) +{ + char backupfile[MAX_WADPATH+4]; + + snprintf(backupfile, sizeof backupfile, "%s.bak", filename); + backupfile[sizeof backupfile - 1] = '\0'; + + FILE *config = fopen(filename, "r"); + + if (config != NULL) + { + fclose(config); + if (FIL_CopyFile(filename, backupfile) == false) + { + CONS_Alert(CONS_WARNING,"Failed to create a backup of the configuration file. Will not attempt to write to file\n"); + return false; + } + } + + return true; +} + /** Saves the game configuration. * * \sa Command_SaveConfig_f @@ -557,28 +579,11 @@ void M_SaveConfig(const char *filename) { FILE *f; char *filepath; - char backupfile[MAX_WADPATH+4]; // make sure not to write back the config until it's been correctly loaded if (!loaded_config) return; - // Create backup of the config file - snprintf(backupfile, sizeof backupfile, "%s.bak", configfile); - backupfile[sizeof backupfile - 1] = '\0'; - - FILE *config = fopen(configfile, "r"); - - if (config != NULL) - { - fclose(config); - if (FIL_CopyFile(configfile, backupfile) == false) - { - CONS_Alert(CONS_WARNING,"Failed to create a backup of the configuration file. Will not attempt to write to file\n"); - return; - } - } - // can change the file name if (filename) { @@ -595,6 +600,10 @@ void M_SaveConfig(const char *filename) else filepath = Z_StrDup(filename); + // If failed to backup, do not proceed + if (!M_BackupConfig(filepath)) + return; + f = fopen(filepath, "w"); // change it only if valid if (f) @@ -613,6 +622,10 @@ void M_SaveConfig(const char *filename) return; } + // If failed to backup, do not proceed + if (!M_BackupConfig(configfile)) + return; + f = fopen(configfile, "w"); if (!f) { diff --git a/src/p_floor.c b/src/p_floor.c index 2aa9cf0f7..5c5aac4b0 100644 --- a/src/p_floor.c +++ b/src/p_floor.c @@ -452,25 +452,16 @@ void T_MoveElevator(elevator_t *elevator) const fixed_t dh = abs(elevator->sector->floorheight - elevator->floordestheight); // Slow down when reaching destination Tails 12-06-2000 - if (wh < dh) - elevator->speed = FixedDiv(wh,25*FRACUNIT) + FRACUNIT/4; - else - elevator->speed = FixedDiv(dh,25*FRACUNIT) + FRACUNIT/4; + elevator->speed = FixedDiv(((wh < dh) ? wh : dh), 25*FRACUNIT) + FRACUNIT/4; if (elevator->origspeed) { - elevator->speed = FixedMul(elevator->speed,origspeed); - if (elevator->speed > elevator->origspeed) - elevator->speed = (elevator->origspeed); - if (elevator->speed < 1) - elevator->speed = 1; + elevator->speed = FixedMul(elevator->speed, origspeed); + elevator->speed = CLAMP(elevator->speed, 1, elevator->origspeed); } else { - if (elevator->speed > 3*FRACUNIT) - elevator->speed = 3*FRACUNIT; - if (elevator->speed < 1) - elevator->speed = 1; + elevator->speed = CLAMP(elevator->speed, 1, 3*FRACUNIT); } } @@ -513,26 +504,18 @@ void T_MoveElevator(elevator_t *elevator) const fixed_t origspeed = FixedDiv(elevator->origspeed,(ELEVATORSPEED/2)); const fixed_t wc = abs(elevator->sector->ceilingheight - elevator->ceilingwasheight); const fixed_t dc = abs(elevator->sector->ceilingheight - elevator->ceilingdestheight); + // Slow down when reaching destination Tails 12-06-2000 - if (wc < dc) - elevator->speed = FixedDiv(wc,25*FRACUNIT) + FRACUNIT/4; - else - elevator->speed = FixedDiv(dc,25*FRACUNIT) + FRACUNIT/4; + elevator->speed = FixedDiv(((wc < dc) ? wc : dc), 25*FRACUNIT) + FRACUNIT/4; if (elevator->origspeed) { - elevator->speed = FixedMul(elevator->speed,origspeed); - if (elevator->speed > elevator->origspeed) - elevator->speed = (elevator->origspeed); - if (elevator->speed < 1) - elevator->speed = 1; + elevator->speed = FixedMul(elevator->speed, origspeed); + elevator->speed = CLAMP(elevator->speed, 1, elevator->origspeed); } else { - if (elevator->speed > 3*FRACUNIT) - elevator->speed = 3*FRACUNIT; - if (elevator->speed < 1) - elevator->speed = 1; + elevator->speed = CLAMP(elevator->speed, 1, 3*FRACUNIT); } } @@ -571,11 +554,7 @@ void T_MoveElevator(elevator_t *elevator) else res = res1; } -/* - // make floor move sound - if (!(leveltime&7)) - S_StartSound(&elevator->sector->soundorg, sfx_stnmov); -*/ + if (res == pastdest || res == crushed) // if destination height acheived { if (elevator->type == elevateContinuous) @@ -608,7 +587,6 @@ void T_MoveElevator(elevator_t *elevator) elevator->ceilingdestheight = elevator->floordestheight + elevator->sector->ceilingheight - elevator->sector->floorheight; } -// T_MoveElevator(elevator); } else { @@ -638,7 +616,6 @@ void T_MoveElevator(elevator_t *elevator) elevator->ceilingdestheight = elevator->floordestheight + elevator->sector->ceilingheight - elevator->sector->floorheight; } -// T_MoveElevator(elevator); } elevator->delaytimer = elevator->delay; } @@ -651,9 +628,8 @@ void T_MoveElevator(elevator_t *elevator) P_RemoveThinker(&elevator->thinker); // remove elevator from actives dontupdate = true; } - // make floor stop sound - // S_StartSound(&elevator->sector->soundorg, sfx_pstop); } + if (!dontupdate) { elevator->sector->floorspeed = elevator->speed*elevator->direction; @@ -2154,10 +2130,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) if (!playeringame[j]) continue; - if (!players[j].mo) - continue; - - if (players[j].mo->health <= 0) + if (!players[j].mo || (players[j].mo->health <= 0)) continue; if ((netgame || multiplayer) && players[j].spectator) @@ -2168,6 +2141,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) else if (sec->flags & SF_TRIGGERSPECIAL_TOUCH) { boolean insector = false; + for (node = players[j].mo->touching_sectorlist; node; node = node->m_sectorlist_next) { if (node->m_sector == targetsec) @@ -2176,6 +2150,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) break; } } + if (!insector) continue; } @@ -2220,10 +2195,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) if (!playeringame[i]) continue; - if (!players[i].mo) - continue; - - if (players[i].mo->health <= 0) + if (!players[i].mo || (players[i].mo->health <= 0)) continue; if ((netgame || multiplayer) && players[i].spectator) @@ -2234,6 +2206,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) else if (sec->flags & SF_TRIGGERSPECIAL_TOUCH) { boolean insector = false; + for (node = players[i].mo->touching_sectorlist; node; node = node->m_sectorlist_next) { if (node->m_sector == sec) @@ -2242,6 +2215,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) break; } } + if (!insector) continue; } @@ -2302,10 +2276,7 @@ void T_EachTimeThinker(levelspecthink_t *eachtime) if (!playeringame[i]) continue; - if (!players[i].mo) - continue; - - if (players[i].mo->health <= 0) + if (!players[i].mo || (players[i].mo->health <= 0)) continue; if ((netgame || multiplayer) && players[i].spectator) @@ -2359,11 +2330,7 @@ void T_RaiseSector(levelspecthink_t *raise) { thing = node->m_thing; - if (!thing->player) - continue; - - // Ignore spectators. - if (thing->player && thing->player->spectator) + if (!thing->player || thing->player->spectator) // Ignore spectators. continue; // Option to require spindashing. @@ -2956,6 +2923,7 @@ void EV_CrumbleChain(sector_t *sec, ffloor_t *rover) if (R_PointInSubsector(a, b)->sector == sec) { mobj_t *spawned = NULL; + for (c = topz; c > *rover->bottomheight; c -= spacing) { spawned = P_SpawnMobj(a, b, c, type); @@ -3120,7 +3088,6 @@ INT32 EV_StartCrumble(sector_t *sec, ffloor_t *rover, boolean floating, for (i = -1; (i = P_FindSectorFromTag(elevator->sourceline->tag, i)) >= 0 ;) { foundsec = §ors[i]; - P_SpawnMobj(foundsec->soundorg.x, foundsec->soundorg.y, elevator->direction == 1 ? elevator->sector->floorheight : elevator->sector->ceilingheight, MT_CRUMBLEOBJ); } diff --git a/src/p_inter.c b/src/p_inter.c index 0cbe6577f..059bbe15c 100644 --- a/src/p_inter.c +++ b/src/p_inter.c @@ -37,62 +37,6 @@ #define CTFTEAMCODE(pl) pl->ctfteam ? (pl->ctfteam == 1 ? "\x85" : "\x84") : "" #define CTFTEAMENDCODE(pl) pl->ctfteam ? "\x80" : "" -void P_ForceFeed(const player_t *player, INT32 attack, INT32 fade, tic_t duration, INT32 period) -{ - BasicFF_t Basicfeed; - if (!player) - return; - Basicfeed.Duration = (UINT32)(duration * (100L/TICRATE)); - Basicfeed.ForceX = Basicfeed.ForceY = 1; - Basicfeed.Gain = 25000; - Basicfeed.Magnitude = period*10; - Basicfeed.player = player; - /// \todo test FFB - P_RampConstant(&Basicfeed, attack, fade); -} - -void P_ForceConstant(const BasicFF_t *FFInfo) -{ - JoyFF_t ConstantQuake; - if (!FFInfo || !FFInfo->player) - return; - ConstantQuake.ForceX = FFInfo->ForceX; - ConstantQuake.ForceY = FFInfo->ForceY; - ConstantQuake.Duration = FFInfo->Duration; - ConstantQuake.Gain = FFInfo->Gain; - ConstantQuake.Magnitude = FFInfo->Magnitude; - if (FFInfo->player == &players[consoleplayer]) - I_Tactile(ConstantForce, &ConstantQuake); - else if (splitscreen && FFInfo->player == &players[displayplayers[1]]) - I_Tactile2(ConstantForce, &ConstantQuake); - else if (splitscreen > 1 && FFInfo->player == &players[displayplayers[2]]) - I_Tactile3(ConstantForce, &ConstantQuake); - else if (splitscreen > 2 && FFInfo->player == &players[displayplayers[3]]) - I_Tactile4(ConstantForce, &ConstantQuake); -} -void P_RampConstant(const BasicFF_t *FFInfo, INT32 Start, INT32 End) -{ - JoyFF_t RampQuake; - if (!FFInfo || !FFInfo->player) - return; - RampQuake.ForceX = FFInfo->ForceX; - RampQuake.ForceY = FFInfo->ForceY; - RampQuake.Duration = FFInfo->Duration; - RampQuake.Gain = FFInfo->Gain; - RampQuake.Magnitude = FFInfo->Magnitude; - RampQuake.Start = Start; - RampQuake.End = End; - if (FFInfo->player == &players[consoleplayer]) - I_Tactile(ConstantForce, &RampQuake); - else if (splitscreen && FFInfo->player == &players[displayplayers[1]]) - I_Tactile2(ConstantForce, &RampQuake); - else if (splitscreen > 1 && FFInfo->player == &players[displayplayers[2]]) - I_Tactile3(ConstantForce, &RampQuake); - else if (splitscreen > 2 && FFInfo->player == &players[displayplayers[3]]) - I_Tactile4(ConstantForce, &RampQuake); -} - - // // GET STUFF // @@ -107,9 +51,6 @@ boolean P_CanPickupItem(player_t *player, UINT8 weapon) if (player->exiting || mapreset) return false; - /*if (G_BattleGametype() && player->kartstuff[k_bumper] <= 0) // No bumpers in Match - return false;*/ - if (weapon) { // Item slot already taken up @@ -165,26 +106,14 @@ void P_DoNightsScore(player_t *player) return; // Don't do any fancy shit for failures. dummymo = P_SpawnMobj(player->mo->x, player->mo->y, player->mo->z+player->mo->height/2, MT_NIGHTSCORE); + if (player->bot) player = &players[consoleplayer]; - if (G_IsSpecialStage(gamemap)) // Global link count? Maybe not a good idea... - { - INT32 i; - for (i = 0; i < MAXPLAYERS; i++) - if (playeringame[i]) - { - if (++players[i].linkcount > players[i].maxlink) - players[i].maxlink = players[i].linkcount; - players[i].linktimer = 2*TICRATE; - } - } - else // Individual link counts - { - if (++player->linkcount > player->maxlink) - player->maxlink = player->linkcount; - player->linktimer = 2*TICRATE; - } + // Individual link counts + if (++player->linkcount > player->maxlink) + player->maxlink = player->linkcount; + player->linktimer = 2*TICRATE; if (player->linkcount < 10) { @@ -214,12 +143,10 @@ void P_DoNightsScore(player_t *player) } // Hoops are the only things that should add to your drill meter - //player->drillmeter += TICRATE; dummymo->momz = FRACUNIT; dummymo->fuse = 3*TICRATE; // What?! NO, don't use the camera! Scale up instead! - //P_InstaThrust(dummymo, R_PointToAngle2(dummymo->x, dummymo->y, camera[0].x, camera[0].y), 3*FRACUNIT); dummymo->scalespeed = FRACUNIT/25; dummymo->destscale = 2*FRACUNIT; } @@ -374,7 +301,6 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) else { K_DropItems(player); //K_StripItems(player); - //K_StripOther(player); player->kartstuff[k_itemroulette] = 1; player->kartstuff[k_roulettetype] = 2; } @@ -521,8 +447,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) special->target->player->kartstuff[k_comebacktimer] = comebacktime; - K_DropItems(player); //K_StripItems(player); - //K_StripOther(player); + K_DropItems(player); player->kartstuff[k_itemroulette] = 1; player->kartstuff[k_roulettetype] = 2; @@ -554,7 +479,6 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) if (player->kartstuff[k_invincibilitytimer] > 0 || player->kartstuff[k_growshrinktimer] > 0 || player->kartstuff[k_hyudorotimer] > 0) { - //player->powers[pw_flashing] = 0; K_DropHnextList(player); K_StripItems(player); } @@ -842,8 +766,6 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) return; if (special->fuse == 1) return; -// if (special->momz > 0) -// return; { UINT8 flagteam = (special->type == MT_REDFLAG) ? 1 : 2; const char *flagtext; @@ -964,14 +886,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) } return; case MT_NIGHTSWING: - if (G_IsSpecialStage(gamemap) && useNightsSS) - { // Pseudo-ring. - S_StartSound(toucher, special->info->painsound); - player->totalring++; - } - else - S_StartSound(toucher, special->info->activesound); - + S_StartSound(toucher, special->info->activesound); P_DoNightsScore(player); break; case MT_HOOPCOLLIDE: @@ -1002,13 +917,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) // Hoops are the only things that should add to the drill meter // Also, one tic's worth of drill is too much. - if (G_IsSpecialStage(gamemap)) - { - for (i = 0; i < MAXPLAYERS; i++) - if (playeringame[i] && players[i].pflags & PF_NIGHTSMODE) - players[i].drillmeter += TICRATE/2; - } - else if (player->bot) + if (player->bot) players[consoleplayer].drillmeter += TICRATE/2; else player->drillmeter += TICRATE/2; @@ -1293,31 +1202,7 @@ void P_TouchSpecialThing(mobj_t *special, mobj_t *toucher, boolean heightcheck) P_SetMobjState(special, special->info->deathstate); return; case MT_SPECIALSPIKEBALL: - if (!(!useNightsSS && G_IsSpecialStage(gamemap))) // Only for old special stages - { - P_DamageMobj(toucher, special, special, 1); - return; - } - - if (player->powers[pw_invulnerability] || player->powers[pw_flashing] - || (player->powers[pw_super] && !(ALL7EMERALDS(player->powers[pw_emeralds])))) - return; - if (player->powers[pw_shield] || player->bot) //If One-Hit Shield - { - P_RemoveShield(player); - S_StartSound(toucher, sfx_shldls); // Ba-Dum! Shield loss. - } - else - { - P_PlayRinglossSound(toucher, NULL); - if (toucher->health > 10) - toucher->health -= 10; - else - toucher->health = 1; - player->health = toucher->health; - } - - P_DoPlayerPain(player, special, NULL); + P_DamageMobj(toucher, special, special, 1); return; case MT_EGGMOBILE2_POGO: // sanity checks @@ -1614,9 +1499,6 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) mobj_t *mo; int ms; - if (!useNightsSS && G_IsSpecialStage(gamemap) && target->player && sstimer > 6) - sstimer = 6; // Just let P_Ticker take care of the rest. - if (target->flags & (MF_ENEMY|MF_BOSS)) target->momx = target->momy = target->momz = 0; @@ -1720,20 +1602,6 @@ void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source) target->flags |= MF_NOBLOCKMAP|MF_NOCLIPHEIGHT; P_SetThingPosition(target); - if (!target->player->bot && !G_IsSpecialStage(gamemap) - && G_GametypeUsesLives()) - { - target->player->lives -= 1; // Lose a life Tails 03-11-2000 - - if (target->player->lives <= 0) // Tails 03-14-2000 - { - if (P_IsLocalPlayer(target->player)/* && target->player == &players[consoleplayer] */) - { - S_StopMusic(); // Stop the Music! Tails 03-14-2000 - S_ChangeMusicInternal("gmover", false); // Yousa dead now, Okieday? Tails 03-14-2000 - } - } - } target->player->playerstate = PST_DEAD; if (cv_birdmusic.value && cv_fading.value && P_IsLocalPlayer(target->player)) @@ -2252,7 +2120,7 @@ static inline boolean P_PlayerHitsPlayer(mobj_t *target, mobj_t *inflictor, mobj return true; } -static void P_KillPlayer(player_t *player, mobj_t *source, INT32 damage) +static void P_KillPlayer(player_t *player, mobj_t *source) { player->pflags &= ~(PF_CARRIED|PF_SLIDING|PF_ITEMHANG|PF_MACESPIN|PF_ROPEHANG|PF_NIGHTSMODE); @@ -2271,8 +2139,6 @@ static void P_KillPlayer(player_t *player, mobj_t *source, INT32 damage) // Get rid of emeralds player->powers[pw_emeralds] = 0; - P_ForceFeed(player, 40, 10, TICRATE, 40 + min(damage, 100)*2); - P_ResetPlayer(player); P_SetPlayerMobjState(player->mo, player->mo->info->deathstate); @@ -2337,14 +2203,12 @@ void P_RemoveShield(player_t *player) player->powers[pw_shield] = player->powers[pw_shield] & SH_STACK; } -static void P_RingDamage(player_t *player, mobj_t *inflictor, mobj_t *source, INT32 damage) +static void P_RingDamage(player_t *player, mobj_t *inflictor, mobj_t *source) { if (!(inflictor && ((inflictor->flags & MF_MISSILE) || inflictor->player) && player->powers[pw_super] && ALL7EMERALDS(player->powers[pw_emeralds]))) { P_DoPlayerPain(player, source, inflictor); - P_ForceFeed(player, 40, 10, TICRATE, 40 + min(damage, 100)*2); - if (source && (source->type == MT_SPIKE || (source->type == MT_NULL && source->threshold == 43))) // spikes S_StartSound(player->mo, sfx_spkdth); } @@ -2378,10 +2242,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da return false; // well no clue but this may happen ig - if (!target) - return false; - - if (target->health <= 0) + if (!target || (target->health <= 0)) return false; // Spectator handling @@ -2403,6 +2264,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da if (P_MobjWasRemoved(target)) return (shouldForce == 1); // mobj was removed + if (shouldForce == 1) force = true; else if (shouldForce == 2) @@ -2543,7 +2405,8 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da // Instant-Death if (damage == DMG_INSTAKILL) - P_KillPlayer(player, source, damage); + P_KillPlayer(player, source); + else if (player->kartstuff[k_invincibilitytimer] > 0 || player->kartstuff[k_growshrinktimer] > 0 || player->powers[pw_flashing]) { if (!force) // shoulddamage bypasses all of that. @@ -2561,8 +2424,9 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da player->kartstuff[k_sneakertimer] = 0; K_SpinPlayer(player, source, 1, inflictor, false); damage = player->mo->health - 1; - P_RingDamage(player, inflictor, source, damage); + P_RingDamage(player, inflictor, source); P_PlayerRingBurst(player, 5); + if (P_IsLocalPlayer(player)) { P_StartQuake(5, 32<health < 0) player->health = 0; - - P_ForceFeed(player, 40, 10, TICRATE, 40 + min(damage, 100)*2); } // Killing dead. Just for kicks. @@ -2640,19 +2503,11 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da } else { - switch (target->type) - { - case MT_EGGMOBILE2: // egg slimer - if (target->health < target->info->damage) // in pinch phase - { - P_SetMobjState(target, target->info->meleestate); // go to pinch pain state - break; - } - /* FALLTHRU */ - default: + // egg slimer + if (target->type == MT_EGGMOBILE2 && (target->health < target->info->damage)) // in pinch phase + P_SetMobjState(target, target->info->meleestate); // go to pinch pain state + else P_SetMobjState(target, target->info->painstate); - break; - } } if (!P_MobjWasRemoved(target)) @@ -2664,6 +2519,7 @@ boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 da // if not intent on another player, // chase after this one P_SetTarget(&target->target, source); + if (target->state == &states[target->info->spawnstate] && target->info->seestate != S_NULL) { if (player) diff --git a/src/p_local.h b/src/p_local.h index 76506ac87..38dcc006b 100644 --- a/src/p_local.h +++ b/src/p_local.h @@ -433,25 +433,11 @@ extern struct minimapinfo // // P_INTER // -typedef struct BasicFF_s -{ - INT32 ForceX; ///< The X of the Force's Vel - INT32 ForceY; ///< The Y of the Force's Vel - const player_t *player; ///< Player of Rumble - //All - UINT32 Duration; ///< The total duration of the effect, in microseconds - INT32 Gain; ///< /The gain to be applied to the effect, in the range from 0 through 10,000. - //All, CONSTANTFORCE �10,000 to 10,000 - INT32 Magnitude; ///< Magnitude of the effect, in the range from 0 through 10,000. -} BasicFF_t; // replace damage magic numbers with smth readable #define DMG_INSTAKILL 10000 #define DMG_SPECTATOR 42000 -void P_ForceFeed(const player_t *player, INT32 attack, INT32 fade, tic_t duration, INT32 period); -void P_ForceConstant(const BasicFF_t *FFInfo); -void P_RampConstant(const BasicFF_t *FFInfo, INT32 Start, INT32 End); void P_RemoveShield(player_t *player); boolean P_DamageMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source, INT32 damage); void P_KillMobj(mobj_t *target, mobj_t *inflictor, mobj_t *source); @@ -488,7 +474,6 @@ boolean P_Teleport(mobj_t *thing, fixed_t x, fixed_t y, fixed_t z, angle_t angle boolean P_SetMobjStateNF(mobj_t *mobj, statenum_t state); boolean P_CheckMissileSpawn(mobj_t *th); void P_Thrust(mobj_t *mo, angle_t angle, fixed_t move); -void P_DoSuperTransformation(player_t *player, boolean giverings); void P_ExplodeMissile(mobj_t *mo); void P_CheckGravity(mobj_t *mo, boolean affect); diff --git a/src/p_map.c b/src/p_map.c index aacbb2e6e..17263bfe9 100644 --- a/src/p_map.c +++ b/src/p_map.c @@ -333,11 +333,11 @@ static boolean PIT_CheckThing(mobj_t *thing) return true; #ifdef SEENAMES - // Do name checks all the way up here - // So that NOTHING ELSE can see MT_NAMECHECK because it is client-side. + // Do name checks all the way up here + // So that NOTHING ELSE can see MT_NAMECHECK because it is client-side. if (tmthing->type == MT_NAMECHECK) { - // Ignore things that aren't players, ignore spectators, ignore yourself. + // Ignore things that aren't players, ignore spectators, ignore yourself. // (also don't bother to check that tmthing->target->player is non-NULL because we're not actually using it here.) if (!thing->player || thing->player->spectator || (tmthing->target && thing->player == tmthing->target->player)) return true; @@ -505,17 +505,15 @@ static boolean PIT_CheckThing(mobj_t *thing) // check for skulls slamming into things if (tmthing->flags2 & MF2_SKULLFLY) { - { - // see if it went over / under - if (tmthing->z > thing->z + thing->height) - return true; // overhead - if (tmthing->z + tmthing->height < thing->z) - return true; // underneath + // see if it went over / under + if (tmthing->z > thing->z + thing->height) + return true; // overhead + if (tmthing->z + tmthing->height < thing->z) + return true; // underneath - tmthing->flags2 &= ~MF2_SKULLFLY; - tmthing->momx = tmthing->momy = tmthing->momz = 0; - return false; // stop moving - } + tmthing->flags2 &= ~MF2_SKULLFLY; + tmthing->momx = tmthing->momy = tmthing->momz = 0; + return false; // stop moving } // SRB2kart 011617 - Colission[sic] code for kart items //{ @@ -543,10 +541,6 @@ static boolean PIT_CheckThing(mobj_t *thing) if (thing->health) P_KillMobj(thing, tmthing, tmthing); - /*if (tmthing->player && (tmthing->player->kartstuff[k_invincibilitytimer] > 0 - || tmthing->player->kartstuff[k_growshrinktimer] > 0)) - return true;*/ - K_KartBouncing(tmthing, thing, false, true); return false; } @@ -729,7 +723,7 @@ static boolean PIT_CheckThing(mobj_t *thing) if (tmthing->z + tmthing->height < thing->z) return true; // underneath - if (!(thing->type == MT_PLAYER)) + if (thing->type != MT_PLAYER) return true; if (thing->player && thing->player->powers[pw_flashing]) @@ -1749,7 +1743,7 @@ boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) if (!(rover->flags & FF_EXISTS)) continue; - topheight = P_GetFOFTopZ(thing, newsubsec->sector, rover, x, y, NULL); + topheight = P_GetFOFTopZ(thing, newsubsec->sector, rover, x, y, NULL); bottomheight = P_GetFOFBottomZ(thing, newsubsec->sector, rover, x, y, NULL); if ((rover->flags & (FF_SWIMMABLE|FF_GOOWATER)) == (FF_SWIMMABLE|FF_GOOWATER) && !(thing->flags & MF_NOGRAVITY)) @@ -1771,14 +1765,16 @@ boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) // Land on the top or the bottom, depending on gravity flip. if (!(thing->eflags & MFE_VERTICALFLIP) && thing->z >= topheight - sinklevel && thing->momz <= 0) { - if (tmfloorz < topheight - sinklevel) { + if (tmfloorz < topheight - sinklevel) + { tmfloorz = topheight - sinklevel; tmfloorslope = *rover->t_slope; } } else if (thing->eflags & MFE_VERTICALFLIP && thingtop <= bottomheight + sinklevel && thing->momz >= 0) { - if (tmceilingz > bottomheight + sinklevel) { + if (tmceilingz > bottomheight + sinklevel) + { tmceilingz = bottomheight + sinklevel; tmceilingslope = *rover->b_slope; } @@ -1800,7 +1796,8 @@ boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) { if (thing->z < topheight && bottomheight < thingtop) { - if (tmfloorz < thing->z) { + if (tmfloorz < thing->z) + { tmfloorz = thing->z; tmfloorslope = NULL; } @@ -1820,6 +1817,7 @@ boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) tmfloorz = tmdropoffz = topheight; tmfloorslope = *rover->t_slope; } + if (bottomheight < tmceilingz && abs(delta1) >= abs(delta2) && !(rover->flags & FF_PLATFORM) && !(thing->type == MT_SKIM && (rover->flags & FF_SWIMMABLE))) @@ -2175,7 +2173,6 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) subsector_t *s; boolean retval = true; - boolean itsatwodlevel = false; UINT8 i; floatok = false; @@ -2188,22 +2185,7 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) else s = thiscam->subsector; - if (twodlevel) - itsatwodlevel = true; - else - { - for (i = 0; i <= splitscreen; i++) - { - if (thiscam == &camera[i] && players[displayplayers[i]].mo - && (players[displayplayers[i]].mo->flags2 & MF2_TWOD)) - { - itsatwodlevel = true; - break; - } - } - } - - if (!itsatwodlevel && players[displayplayers[0]].mo) + if (players[displayplayers[0]].mo) { fixed_t tryx = thiscam->x; fixed_t tryy = thiscam->y; @@ -2270,7 +2252,7 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) } else { - tmfloorz = P_CameraGetFloorZ(thiscam, thiscam->subsector->sector, x, y, NULL); + tmfloorz = P_CameraGetFloorZ(thiscam, thiscam->subsector->sector, x, y, NULL); tmceilingz = P_CameraGetCeilingZ(thiscam, thiscam->subsector->sector, x, y, NULL); } diff --git a/src/p_mobj.c b/src/p_mobj.c index bb894538e..0157963f9 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -1124,9 +1124,6 @@ void P_CheckGravity(mobj_t *mo, boolean affect) } } -#define STOPSPEED (FRACUNIT) -//#define FRICTION (ORIG_FRICTION) // 0.90625 - // // P_SceneryXYFriction // @@ -1135,8 +1132,8 @@ static void P_SceneryXYFriction(mobj_t *mo, fixed_t oldx, fixed_t oldy) I_Assert(mo != NULL); I_Assert(!P_MobjWasRemoved(mo)); - if (abs(mo->momx) < FixedMul(STOPSPEED/32, mo->scale) - && abs(mo->momy) < FixedMul(STOPSPEED/32, mo->scale)) + if (abs(mo->momx) < FixedMul(FRACUNIT/32, mo->scale) + && abs(mo->momy) < FixedMul(FRACUNIT/32, mo->scale)) { mo->momx = 0; mo->momy = 0; @@ -1145,13 +1142,13 @@ static void P_SceneryXYFriction(mobj_t *mo, fixed_t oldx, fixed_t oldy) { if ((oldx == mo->x) && (oldy == mo->y)) // didn't go anywhere { - mo->momx = FixedMul(mo->momx,ORIG_FRICTION); - mo->momy = FixedMul(mo->momy,ORIG_FRICTION); + mo->momx = FixedMul(mo->momx, ORIG_FRICTION); + mo->momy = FixedMul(mo->momy, ORIG_FRICTION); } else { - mo->momx = FixedMul(mo->momx,mo->friction); - mo->momy = FixedMul(mo->momy,mo->friction); + mo->momx = FixedMul(mo->momx, mo->friction); + mo->momy = FixedMul(mo->momy, mo->friction); } if (mo->type == MT_CANNONBALLDECOR) @@ -1183,12 +1180,12 @@ static void P_XYFriction(mobj_t *mo, fixed_t oldx, fixed_t oldy) // spinning friction if (player->pflags & PF_SPINNING && (player->rmomx || player->rmomy) && !(player->pflags & PF_STARTDASH)) { - const fixed_t ns = FixedDiv(549*ORIG_FRICTION,500*FRACUNIT); //const fixed_t ns = FixedDiv(549*FRICTION,500*FRACUNIT); + const fixed_t ns = FixedDiv(549*ORIG_FRICTION, 500*FRACUNIT); //const fixed_t ns = FixedDiv(549*FRICTION,500*FRACUNIT); mo->momx = FixedMul(mo->momx, ns); mo->momy = FixedMul(mo->momy, ns); } - else if (abs(player->rmomx) < FixedMul(STOPSPEED, mo->scale) - && abs(player->rmomy) < FixedMul(STOPSPEED, mo->scale) + else if (abs(player->rmomx) < FixedMul(FRACUNIT, mo->scale) + && abs(player->rmomy) < FixedMul(FRACUNIT, mo->scale) && (!(player->cmd.forwardmove && !(twodlevel || mo->flags2 & MF2_TWOD)) && !player->cmd.sidemove && !(player->pflags & PF_SPINNING)) && !(player->mo->standingslope && (!(player->mo->standingslope->flags & SL_NOPHYSICS)) && (abs(player->mo->standingslope->zdelta) >= FRACUNIT/2)) ) @@ -2242,9 +2239,9 @@ static boolean P_ZMovement(mobj_t *mo) if (mo->type == MT_BIGTUMBLEWEED || mo->type == MT_LITTLETUMBLEWEED) { - if (abs(mom.x) < FixedMul(STOPSPEED, mo->scale) - && abs(mom.y) < FixedMul(STOPSPEED, mo->scale) - && abs(mom.z) < FixedMul(STOPSPEED*3, mo->scale)) + if (abs(mom.x) < FixedMul(FRACUNIT, mo->scale) + && abs(mom.y) < FixedMul(FRACUNIT, mo->scale) + && abs(mom.z) < FixedMul(FRACUNIT*3, mo->scale)) { if (mo->flags2 & MF2_AMBUSH) { @@ -2285,9 +2282,9 @@ static boolean P_ZMovement(mobj_t *mo) mom.z /= 2; // Rocks not so bouncy if (!mo->fuse - && abs(mom.x) < FixedMul(STOPSPEED*2, mo->scale) - && abs(mom.y) < FixedMul(STOPSPEED*2, mo->scale) - && abs(mom.z) < FixedMul(STOPSPEED*2*3, mo->scale)) + && abs(mom.x) < FixedMul(FRACUNIT*2, mo->scale) + && abs(mom.y) < FixedMul(FRACUNIT*2, mo->scale) + && abs(mom.z) < FixedMul(FRACUNIT*2*3, mo->scale)) { //P_RemoveMobj(mo); //return false; @@ -2297,7 +2294,7 @@ static boolean P_ZMovement(mobj_t *mo) else if (mo->type == MT_CANNONBALLDECOR) { mom.z /= 2; - if (abs(mom.z) < FixedMul(STOPSPEED*3, mo->scale)) + if (abs(mom.z) < FixedMul(FRACUNIT*3, mo->scale)) mom.z = 0; } } @@ -3278,30 +3275,12 @@ void P_CalcChasePostImg(player_t *player, camera_t *thiscam) // Process the mobj-ish required functions of the camera boolean P_CameraThinker(player_t *player, camera_t *thiscam, boolean resetcalled) { - boolean itsatwodlevel = false; - 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 - { - for (i = 0; i <= splitscreen; i++) - { - if (thiscam == &camera[i] && players[displayplayers[i]].mo - && (players[displayplayers[i]].mo->flags2 & MF2_TWOD)) - { - itsatwodlevel = true; - break; - } - } - } - if (thiscam->momx || thiscam->momy) { if (!P_TryCameraMove(thiscam->x + thiscam->momx, thiscam->y + thiscam->momy, thiscam)) // Never fails for 2D mode. @@ -3328,9 +3307,6 @@ 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->floorz = tmfloorz; thiscam->ceilingz = tmceilingz; @@ -3384,9 +3360,8 @@ boolean P_CameraThinker(player_t *player, camera_t *thiscam, boolean resetcalled #endif } - if (itsatwodlevel - || (thiscam->ceilingz - thiscam->z < thiscam->height - && thiscam->ceilingz >= thiscam->z)) + if (thiscam->ceilingz - thiscam->z < thiscam->height + && thiscam->ceilingz >= thiscam->z) { thiscam->ceilingz = thiscam->z + thiscam->height; thiscam->floorz = thiscam->z; @@ -7406,24 +7381,7 @@ void P_MobjThinker(mobj_t *mobj) P_SetTarget(&mobj->target, goalpost); } - if (G_IsSpecialStage(gamemap)) - { // Never show the NiGHTS drone in special stages. Check ANYONE for bonustime. - INT32 i; - boolean bonustime = false; - for (i = 0; i < MAXPLAYERS; i++) - if (playeringame[i] && players[i].bonustime) - { - bonustime = true; - break; - } - if (!bonustime) - { - mobj->flags &= ~MF_NOGRAVITY; - P_SetMobjState(mobj, S_NIGHTSDRONE1); - mobj->flags2 |= MF2_DONTDRAW; - } - } - else if (mobj->tracer && mobj->tracer->player) + if (mobj->tracer && mobj->tracer->player) { if (!(mobj->tracer->player->pflags & PF_NIGHTSMODE)) { @@ -7440,35 +7398,7 @@ void P_MobjThinker(mobj_t *mobj) } else { - if (G_IsSpecialStage(gamemap)) - { // Never show the NiGHTS drone in special stages. Check ANYONE for bonustime. - INT32 i; - - boolean bonustime = false; - for (i = 0; i < MAXPLAYERS; i++) - if (playeringame[i] && players[i].bonustime) - { - bonustime = true; - break; - } - - if (bonustime) - { - P_SetMobjState(mobj, S_NIGHTSDRONE_SPARKLING1); - mobj->flags |= MF_NOGRAVITY; - } - else - { - if (mobj->target) - { - CONS_Debug(DBG_NIGHTSBASIC, "Removing goal post\n"); - P_RemoveMobj(mobj->target); - P_SetTarget(&mobj->target, NULL); - } - mobj->flags2 |= MF2_DONTDRAW; - } - } - else if (mobj->tracer && mobj->tracer->player) + if (mobj->tracer && mobj->tracer->player) { if (mobj->target) { @@ -10479,10 +10409,6 @@ void P_RespawnSpecials(void) if (!cv_itemrespawn.value) return; - // Don't respawn in special stages! - if (G_IsSpecialStage(gamemap)) - return; - // nothing left to respawn? if (iquehead == iquetail) return; @@ -11192,7 +11118,7 @@ void P_SpawnMapThing(mapthing_t *mthing) if (i == MT_PITYTV || i == MT_GREENTV || i == MT_YELLOWTV || i == MT_BLUETV || i == MT_BLACKTV || i == MT_WHITETV) return; // No shields in Ultimate mode - if (i == MT_SUPERRINGBOX && !G_IsSpecialStage(gamemap)) + if (i == MT_SUPERRINGBOX) return; // No rings in Ultimate mode (except special stages) } @@ -11691,14 +11617,6 @@ ML_NOCLIMB : Direction not controllable mobj->health |= 1; // If ambush is set, push using XYZ if (mthing->options & MTF_OBJECTSPECIAL) mobj->health |= 2; // If object special is set, fade using XY - - if (G_IsSpecialStage(gamemap)) - { - if (i == MT_PUSH) - P_SetMobjState(mobj, S_GRAVWELLGREEN); - if (i == MT_PULL) - P_SetMobjState(mobj, S_GRAVWELLRED); - } } // ignore MTF_ flags and return early diff --git a/src/p_slopes.c b/src/p_slopes.c index 83438c4d4..d4c033eeb 100644 --- a/src/p_slopes.c +++ b/src/p_slopes.c @@ -72,8 +72,8 @@ static void P_UpdateSlopeLightOffset(pslope_t *slope) * // We reverse it in R_FindPlane now. * nX = -nX; * nY = -nY; - } - */ + * } + */ light = FixedMul(nX, FINECOSINE(maplighting.angle >> ANGLETOFINESHIFT)) + FixedMul(nY, FINESINE(maplighting.angle >> ANGLETOFINESHIFT)); @@ -233,9 +233,11 @@ void P_RunDynamicSlopes(void) I_Error("P_RunDynamicSlopes: slope has invalid type!"); } - if (slope->zdelta != FixedDiv(zdelta, slope->extent)) + const fixed_t zeedelta = FixedDiv(zdelta, slope->extent); + + if (slope->zdelta != zeedelta) { - slope->zdelta = FixedDiv(zdelta, slope->extent); + slope->zdelta = zeedelta; slope->zangle = R_PointToAngle2(0, 0, slope->extent, -zdelta); slope->real_zangle = slope->zangle; P_CalculateSlopeNormal(slope); @@ -295,18 +297,18 @@ static fixed_t P_GetExtent(sector_t *sector, line_t *line) fixed_t dist; // Don't compare to the slope line. - if(li == line) + if (li == line) continue; P_ClosestPointOnLine(li->v1->x, li->v1->y, line, &tempv); dist = R_PointToDist2(tempv.x, tempv.y, li->v1->x, li->v1->y); - if(dist > fardist) + if (dist > fardist) fardist = dist; // Okay, maybe do it for v2 as well? P_ClosestPointOnLine(li->v2->x, li->v2->y, line, &tempv); dist = R_PointToDist2(tempv.x, tempv.y, li->v2->x, li->v2->y); - if(dist > fardist) + if (dist > fardist) fardist = dist; } @@ -357,11 +359,9 @@ void P_SpawnSlope_Line(int linenum) return; } - { - fixed_t len = R_PointToDist2(0, 0, line->dx, line->dy); - nx = FixedDiv(line->dy, len); - ny = -FixedDiv(line->dx, len); - } + fixed_t len = R_PointToDist2(0, 0, line->dx, line->dy); + nx = FixedDiv(line->dy, len); + ny = -FixedDiv(line->dx, len); origin.x = line->v1->x + (line->v2->x - line->v1->x)/2; origin.y = line->v1->y + (line->v2->y - line->v1->y)/2; @@ -377,7 +377,7 @@ void P_SpawnSlope_Line(int linenum) extent = P_GetExtent(line->frontsector, line); - if(extent < 0) + if (extent < 0) { CONS_Printf("P_SpawnSlope_Line failed to get frontsector extent on line number %i\n", linenum); return; @@ -694,9 +694,9 @@ void P_CopySectorSlope(line_t *line) { sector_t *srcsec = sectors + i; - if((special - 719) & 1 && !fsec->f_slope && srcsec->f_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) + if ((special - 719) & 2 && !fsec->c_slope && srcsec->c_slope) fsec->c_slope = srcsec->c_slope; //P_CopySlope(srcsec->c_slope); } @@ -782,25 +782,24 @@ void P_ResetDynamicSlopes(void) if (!(lines[i].flags & ML_NOTAILS)) flags |= SL_NODYNAMIC; - if (which == 704) + switch (which) { - slopetoset = &lines[i].frontsector->f_slope; - which = 0; - } - else if (which == 705) - { - slopetoset = &lines[i].frontsector->c_slope; - which = 0; - } - else if (which == 714) - { - slopetoset = &lines[i].backsector->f_slope; - which = 1; - } - else // 715 - { - slopetoset = &lines[i].backsector->c_slope; - which = 1; + case 704: + slopetoset = &lines[i].frontsector->f_slope; + which = 0; + break; + case 705: + slopetoset = &lines[i].frontsector->c_slope; + which = 0; + break; + case 714: + slopetoset = &lines[i].backsector->f_slope; + which = 1; + break; + default: // 715 + slopetoset = &lines[i].backsector->c_slope; + which = 1; + break; } if (lines[i].flags & ML_NOKNUX) @@ -944,10 +943,12 @@ void P_ButteredSlope(mobj_t *mo) if (mo->player) { - if (abs(mo->standingslope->zdelta) < FRACUNIT/4 && !(mo->player->pflags & PF_SPINNING)) + const int zeedelta = abs(mo->standingslope->zdelta); + + if (zeedelta < FRACUNIT/4 && !(mo->player->pflags & PF_SPINNING)) return; // Don't slide on non-steep slopes unless spinning - if (abs(mo->standingslope->zdelta) < FRACUNIT/2 && !(mo->player->rmomx || mo->player->rmomy)) + if (zeedelta < FRACUNIT/2 && !(mo->player->rmomx || mo->player->rmomy)) return; // Allow the player to stand still on slopes below a certain steepness } diff --git a/src/p_spec.c b/src/p_spec.c index 40e47bf83..70fb19c20 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -3538,6 +3538,7 @@ DoneSection2: for (UINT8 j = 0; j <= splitscreen; ++j) { INT32 id = (j == 0 ? consoleplayer : displayplayers[j]); + if (player == &players[id]) { localangle[j] = player->mo->angle; @@ -3574,7 +3575,6 @@ DoneSection2: sfxenum_t pick = P_RandomKey(2); // Gotta roll the RNG every time this is called for sync reasons if (cv_kartvoices.value) S_StartSound(player->mo, sfx_kbost1+pick); - //K_TauntVoiceTimers(player); } } break; @@ -3610,8 +3610,6 @@ DoneSection2: case 2: // Special stage GOAL sector / Exit Sector / CTF Flag Return if (player->bot) break; - if (!useNightsSS && G_IsSpecialStage(gamemap) && sstimer > 6) - sstimer = 6; // Just let P_Ticker take care of the rest. // Exit (for FOF exits; others are handled in P_PlayerThink in p_user.c) { @@ -3802,12 +3800,6 @@ DoneSection2: if (!(player->mo->state >= &states[S_KART_RUN1] && player->mo->state <= &states[S_KART_RUN2])) P_SetPlayerMobjState(player->mo, S_KART_RUN1); - - //if (!(player->mo->state >= &states[S_PLAY_ATK1] && player->mo->state <= &states[S_PLAY_ATK4])) // SRB2kart - //{ - // P_SetPlayerMobjState(player->mo, S_PLAY_ATK1); - // S_StartSound(player->mo, sfx_spin); - //} } break; @@ -3963,12 +3955,6 @@ DoneSection2: S_StartSound(NULL, sfx_s221); } - //player->starpostangle = player->starposttime = player->starpostnum = 0; - //player->starpostx = player->starposty = player->starpostz = 0; - - // Play the starpost sound for 'consistency' - // S_StartSound(player->mo, sfx_strpst); - thwompsactive = true; // Lap 2 effects player->grieftime = 0; } @@ -4532,14 +4518,6 @@ static void P_RunSpecialSectorCheck(player_t *player, sector_t *sector) switch(GETSECSPECIAL(sector->special, 4)) { case 2: // Level Exit / GOAL Sector / Flag Return - if (!useNightsSS && G_IsSpecialStage(gamemap)) - { - // Special stage GOAL sector - // requires touching floor. - break; - } - /* FALLTHRU */ - case 1: // Starpost activator case 5: // Fan sector case 6: // Super Sonic Transform @@ -4809,11 +4787,11 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f i = 0; th = thinkercap.next; - for(;;) + for (;;) { - if(secthinkers) + if (secthinkers) { - if(i < secthinkers[sec2num].count) + if (i < secthinkers[sec2num].count) th = secthinkers[sec2num].thinkers[i]; else break; } @@ -4845,8 +4823,10 @@ static ffloor_t *P_AddFakeFloor(sector_t *sec, sector_t *sec2, line_t *master, f Add_Pusher(p->type, p->x_mag<y_mag<source, (INT32)(sec-sectors), p->affectee, p->exclusive, p->slider); } - if(secthinkers) i++; - else th = th->next; + if (secthinkers) + i++; + else + th = th->next; } if (flags & FF_TRANSLUCENT) @@ -6371,6 +6351,7 @@ static void P_AddFakeFloorsByLine(size_t line, ffloortype_e ffloorflags, thinker static void P_DoScrollMove(mobj_t *thing, fixed_t dx, fixed_t dy, INT32 exclusive) { fixed_t fuckaj = 0; // Nov 05 14:12:08 <+MonsterIestyn> I've heard of explicitly defined variables but this is ridiculous + if (thing->player) { if (!(dx | dy)) @@ -6392,7 +6373,8 @@ static void P_DoScrollMove(mobj_t *thing, fixed_t dx, fixed_t dy, INT32 exclusiv else if (thing->friction != ORIG_FRICTION) fuckaj = thing->friction; - if (fuckaj) { + if (fuckaj) + { // refactor thrust for new friction dx = FixedDiv(dx, CARRYFACTOR); dy = FixedDiv(dy, CARRYFACTOR); @@ -6451,9 +6433,6 @@ void T_Scroll(scroll_t *s) s->vdy = dy += s->vdy; } -// if (!(dx | dy)) // no-op if both (x,y) offsets 0 -// return; - switch (s->type) { side_t *side; @@ -6729,27 +6708,21 @@ static void P_SpawnScrollers(void) // this linedef controls the direction and speed of the scrolling. The // most complicated linedef since donuts, but powerful :) - if (special == 515 || special == 512 || special == 522 || special == 532 || special == 504) // displacement scrollers + switch (special) { - special -= 2; - control = (INT32)(sides[*l->sidenum].sector - sectors); - } - else if (special == 514 || special == 511 || special == 521 || special == 531 || special == 503) // accelerative scrollers - { - special--; - accel = 1; - control = (INT32)(sides[*l->sidenum].sector - sectors); - } - else if (special == 535 || special == 525) // displacement scrollers - { - special -= 2; - control = (INT32)(sides[*l->sidenum].sector - sectors); - } - else if (special == 534 || special == 524) // accelerative scrollers - { - accel = 1; - special--; - control = (INT32)(sides[*l->sidenum].sector - sectors); + case 515: case 512: case 522: case 532: case 504: + case 535: case 525: // displacement scrollers + + special -= 2; + control = (INT32)(sides[*l->sidenum].sector - sectors); + break; + + case 514: case 511: case 521: case 531: case 503: + case 534: case 524: // accelerative scrollers + special--; + accel = 1; + control = (INT32)(sides[*l->sidenum].sector - sectors); + break; } switch (special) diff --git a/src/p_tick.c b/src/p_tick.c index 212c2f1e6..3c4583322 100644 --- a/src/p_tick.c +++ b/src/p_tick.c @@ -845,7 +845,7 @@ void P_Ticker(boolean run) // 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(); + G_SaveDemo(); } } else if (demo.playback) // Use Ghost data for consistency checks. diff --git a/src/p_user.c b/src/p_user.c index 5d69dc381..8151c28aa 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -135,9 +135,6 @@ boolean P_AutoPause(void) // void P_CalcHeight(player_t *player) { - //INT32 angle; - //fixed_t bob; - //fixed_t pviewheight; mobj_t *mo = player->mo; // Regular movement bobbing. @@ -256,7 +253,6 @@ void P_GiveEmerald(boolean spawnObj) void P_ResetScore(player_t *player) { // Formally a host for Chaos mode behavior - player->scoreadd = 0; } @@ -440,9 +436,7 @@ void P_GivePlayerRings(player_t *player, INT32 num_rings) player->mo->health += num_rings; player->health += num_rings; - - if (!G_IsSpecialStage(gamemap) || !useNightsSS) - player->totalring += num_rings; + player->totalring += num_rings; //{ SRB2kart - rings don't really do anything, but we don't want the player spilling them later. { @@ -450,24 +444,6 @@ void P_GivePlayerRings(player_t *player, INT32 num_rings) player->health = 1; } //} - - // Now extra life bonuses are handled here instead of in P_MovePlayer, since why not? - if (!ultimatemode && !modeattacking && !G_IsSpecialStage(gamemap) && G_GametypeUsesLives()) - { - INT32 gainlives = 0; - - while (player->xtralife < maxXtraLife && player->health > 100 * (player->xtralife+1)) - { - ++gainlives; - ++player->xtralife; - } - - if (gainlives) - { - P_GivePlayerLives(player, gainlives); - P_PlayLivesJingle(player); - } - } } // @@ -486,22 +462,10 @@ void P_GivePlayerLives(player_t *player, INT32 numlives) player->lives = 1; } -// -// P_DoSuperTransformation -// -// Transform into Super Sonic! -void P_DoSuperTransformation(player_t *player, boolean giverings) -{ - (void)player; - (void)giverings; - - return; // SRB2kart - this is not a thing we need -} - // Adds to the player's score void P_AddPlayerScore(player_t *player, UINT32 amount) { - if (!(G_BattleGametype())) + if (!G_BattleGametype()) return; if (player->bot) @@ -606,15 +570,21 @@ static boolean isPlayerLosing(player_t *player) UINT8 pos = 1; UINT8 maxpos = 1; - for (int i = 0; i < MAXPLAYERS; ++i) { + for (int i = 0; i < MAXPLAYERS; ++i) + { if (!playeringame[i] || players[i].spectator) continue; - if (players[i].marescore > player->marescore) ++pos; + + if (players[i].marescore > player->marescore) + ++pos; + maxpos = max(getPlayerPos(&players[i]), maxpos); } - if (maxpos == 1) return false; + if (maxpos == 1) + return false; - if (maxpos % 2) ++maxpos; + if (maxpos % 2) + ++maxpos; return pos > (maxpos / 2); } @@ -823,20 +793,6 @@ boolean P_IsObjectOnGround(mobj_t *mo) { if (P_IsObjectInGoop(mo)) { -/* - // It's a crazy hack that checking if you're on the ground - // would actually CHANGE your position and momentum, - if (mo->z < mo->floorz) - { - mo->z = mo->floorz; - mo->momz = 0; - } - else if (mo->z + mo->height > mo->ceilingz) - { - mo->z = mo->ceilingz - mo->height; - mo->momz = 0; - } -*/ // but I don't want you to ever 'stand' while submerged in goo. // You're in constant vertical momentum, even if you get stuck on something. // No exceptions. @@ -1182,26 +1138,28 @@ mobj_t *P_SpawnGhostMobj(mobj_t *mobj) else ghost->angle = mobj->angle; - ghost->pitch = mobj->pitch; - ghost->roll = mobj->roll; - ghost->sprite = mobj->sprite; ghost->frame = mobj->frame; ghost->tics = -1; ghost->frame &= ~FF_TRANSMASK; ghost->frame |= tr_trans50<slopepitch = mobj->slopepitch; - ghost->sloperoll = mobj->sloperoll; ghost->fuse = ghost->info->damage; ghost->skin = mobj->skin; ghost->localskin = mobj->localskin; ghost->skinlocal = mobj->skinlocal; + ghost->spritexscale = mobj->spritexscale; ghost->spriteyscale = mobj->spriteyscale; ghost->spritexoffset = mobj->spritexoffset; ghost->spriteyoffset = mobj->spriteyoffset; + + ghost->pitch = mobj->pitch; + ghost->roll = mobj->roll; + ghost->sloperoll = mobj->sloperoll; ghost->rollangle = mobj->rollangle; + ghost->sloperoll = mobj->sloperoll; + ghost->slopepitch = mobj->slopepitch; if (mobj->flags2 & MF2_OBJECTFLIP) ghost->flags |= MF2_OBJECTFLIP; @@ -1282,9 +1240,6 @@ void P_DoPlayerExit(player_t *player) if (player == &players[consoleplayer]) demo.savebutton = leveltime; - - /*if (playeringame[player-players] && netgame && !circuitmap) - CONS_Printf(M_GetText("%s has completed the level.\n"), player_names[player-players]);*/ } #define SPACESPECIAL 12 @@ -1701,7 +1656,6 @@ static void P_CheckInvincibilityTimer(player_t *player) } } - // // P_DoBubbleBreath // @@ -1871,11 +1825,8 @@ static void P_3dMovement(player_t *player) { ticcmd_t *cmd; angle_t movepushangle, movepushsideangle; // Analog - //INT32 topspeed, acceleration, thrustfactor; fixed_t movepushforward = 0, movepushside = 0; angle_t dangle; // replaces old quadrants bits - //boolean dangleflip = false; // SRB2kart - toaster - //fixed_t normalspd = FixedMul(player->normalspeed, player->mo->scale); boolean analogmove = false; fixed_t oldMagnitude, newMagnitude; vector3_t totalthrust; @@ -1913,20 +1864,18 @@ static void P_3dMovement(player_t *player) else movepushangle = player->mo->angle; } + movepushsideangle = movepushangle-ANGLE_90; // cmomx/cmomy stands for the conveyor belt speed. if (player->onconveyor == 2) // Wind/Current { - //if (player->mo->z > player->mo->watertop || player->mo->z + player->mo->height < player->mo->waterbottom) if (!(player->mo->eflags & (MFE_UNDERWATER|MFE_TOUCHWATER))) player->cmomx = player->cmomy = 0; } else if (player->onconveyor == 4 && !P_IsObjectOnGround(player->mo)) // Actual conveyor belt player->cmomx = player->cmomy = 0; - else if (player->onconveyor != 2 && player->onconveyor != 4 - && player->onconveyor != 1 - ) + else if (player->onconveyor != 2 && player->onconveyor != 4 && player->onconveyor != 1) player->cmomx = player->cmomy = 0; player->rmomx = player->mo->momx - player->cmomx; @@ -1942,29 +1891,8 @@ static void P_3dMovement(player_t *player) if (dangle > ANGLE_180) //flip to keep to one side { dangle = InvAngle(dangle); - //dangleflip = true; } - // anything else will leave both at 0, so no need to do anything else - - //{ SRB2kart 220217 - Toaster Code for misplaced thrust - /* - if (!player->kartstuff[k_drift]) // Not Drifting - { - angle_t difference = dangle/2; - boolean reverse = (dangle >= ANGLE_90); - - if (dangleflip) - difference = InvAngle(difference); - - if (reverse) - difference += ANGLE_180; - - P_InstaThrust(player->mo, player->mo->angle + difference, player->speed); - } - */ - //} - // When sliding, don't allow forward/back if (player->pflags & PF_SLIDING) cmd->forwardmove = 0; @@ -1978,16 +1906,12 @@ static void P_3dMovement(player_t *player) // Forward movement if (!((player->exiting || mapreset) || (P_PlayerInPain(player) && !onground))) { - //movepushforward = cmd->forwardmove * (thrustfactor * acceleration); movepushforward = K_3dKartMovement(player, onground, cmd->forwardmove); // allow very small movement while in air for gameplay if (!onground) movepushforward >>= 2; // proper air movement - // don't need to account for scale here with kart accel code - //movepushforward = FixedMul(movepushforward, player->mo->scale); - if (player->mo->movefactor != FRACUNIT) // Friction-scaled acceleration... movepushforward = FixedMul(movepushforward, player->mo->movefactor); @@ -2054,9 +1978,11 @@ static void P_3dMovement(player_t *player) // If "no" to 1, we're not reaching any limits yet, so ignore this entirely! // -Shadow Hog newMagnitude = R_PointToDist2(player->mo->momx - player->cmomx, player->mo->momy - player->cmomy, 0, 0); + if (newMagnitude > K_GetKartSpeed(player, true)) //topspeed) { fixed_t tempmomx, tempmomy; + if (oldMagnitude > K_GetKartSpeed(player, true) && onground) // SRB2Kart: onground check for air speed cap { if (newMagnitude > oldMagnitude) @@ -2255,8 +2181,6 @@ static void P_MovePlayer(player_t *player) { player->pflags |= PF_FULLSTASIS; // If you're in stasis in tag, you don't drown. - /*if (player->powers[pw_underwater] <= 12*TICRATE + 1) - P_RestoreMusic(player);*/ player->powers[pw_underwater] = player->powers[pw_spacetime] = 0; } } @@ -2285,7 +2209,9 @@ static void P_MovePlayer(player_t *player) { player->lturn_max[leveltime%MAXPREDICTTICS] = K_GetKartTurnValue(player, KART_FULLTURN)+1; player->rturn_max[leveltime%MAXPREDICTTICS] = K_GetKartTurnValue(player, -KART_FULLTURN)-1; - } else { + } + else + { player->lturn_max[leveltime%MAXPREDICTTICS] = player->rturn_max[leveltime%MAXPREDICTTICS] = 0; } @@ -2536,8 +2462,6 @@ static void P_DoZoomTube(player_t *player) fixed_t dist; boolean reverse; - //player->mo->height = P_GetPlayerSpinHeight(player); - if (player->speed > 0) reverse = false; else @@ -2643,11 +2567,6 @@ static void P_DoZoomTube(player_t *player) else if (player == &players[displayplayers[3]]) localangle[3] = player->mo->angle; } -#if 0 - if (player->mo->state != &states[S_KART_SPIN]) - P_SetPlayerMobjState(player->mo, S_KART_SPIN); - player->frameangle -= ANGLE_22h; -#endif } // @@ -2758,6 +2677,7 @@ boolean P_LookForEnemies(player_t *player) continue; // not a mobj thinker mo = (mobj_t *)think; + if (!(mo->flags & (MF_ENEMY|MF_BOSS|MF_MONITOR|MF_SPRING))) continue; // not a valid enemy @@ -2823,14 +2743,12 @@ void P_HomingAttack(mobj_t *source, mobj_t *enemy) // Home in on your target fixed_t dist; fixed_t ns = 0; - if (!enemy) - return; - - if (!(enemy->health)) + if (!enemy || !enemy->health) return; // change angle source->angle = R_PointToAngle2(source->x, source->y, enemy->x, enemy->y); + if (source->player) { if (source->player == &players[consoleplayer]) @@ -2883,6 +2801,7 @@ void P_FindEmerald(void) continue; mo2 = (mobj_t *)th; + if (mo2->type == MT_EMERHUNT) { if (!hunt1) @@ -2903,9 +2822,6 @@ void P_FindEmerald(void) // static void P_DeathThink(player_t *player) { - //ticcmd_t *cmd = &player->cmd; - //player->deltaviewheight = 0; - if (player->deadtimer < INT32_MAX) player->deadtimer++; @@ -3746,6 +3662,33 @@ static boolean P_CheckNoclipCameraPosition(player_t *player, camera_t *thiscam, } #endif +static void P_MoveCameraToSpawn(UINT8 playernum) +{ + camera_t *thiscam = &camera[playernum]; + player_t *player = playernum == 0 ? &players[consoleplayer] : &players[displayplayers[playernum]]; + + if (!thiscam || !player->mo) + return; + + thiscam->x = player->mo->x - P_ReturnThrustX(player->mo, thiscam->angle, player->mo->radius); + thiscam->y = player->mo->y - P_ReturnThrustY(player->mo, thiscam->angle, player->mo->radius); + if (player->mo->eflags & MFE_VERTICALFLIP) + thiscam->z = player->mo->z + player->mo->height - (32<z = player->mo->z + (32<reset = true; + + thiscam->angle = player->mo->angle; + thiscam->aiming = 0; + + thiscam->subsector = R_PointInSubsector(thiscam->x,thiscam->y); + + thiscam->reset_aiming = true; + + R_ResetViewInterpolation(playernum); +} + boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcalled) { static boolean lookbackactive[MAXSPLITSCREENPLAYERS]; @@ -3779,6 +3722,13 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall if (thiscam->freecam || player->spectator) { + // idk if this is the best place? + if (player->spectator && InputDown(gc_freecam, num+1)) + { + P_MoveCameraToSpawn(num); + return true; // dont move while you hold this + } + P_DemoCameraMovement(thiscam, num); P_CalcChasePostImg(player, thiscam); return true; @@ -4046,7 +3996,7 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall if (player->playerstate != PST_DEAD && !((player->pflags & PF_NIGHTSMODE) && player->exiting)) angle += (focusaiming < ANGLE_180 ? focusaiming/2 : InvAngle(InvAngle(focusaiming)/2)); // overcomplicated version of '((signed)focusaiming)/2;' - if (twodlevel || (mo->flags2 & MF2_TWOD) || (!camstill && !timeover)) // Keep the view still... + if (!camstill && !timeover) // Keep the view still... { G_ClipAimingPitch((INT32 *)&angle); @@ -5049,19 +4999,12 @@ void P_PlayerThink(player_t *player) else player->mo->flags2 &= ~MF2_DONTDRAW; } - /*else if (player->mo->tracer) - { - if (player->powers[pw_flashing] & 1) - player->mo->tracer->flags2 |= MF2_DONTDRAW; - else - player->mo->tracer->flags2 &= ~MF2_DONTDRAW; - }*/ player->pflags &= ~PF_SLIDING; K_KartPlayerThink(player, cmd); // SRB2kart - if (rendermode != render_none && cv_tilting.value) + if (cv_tilting.value && rendermode != render_none) DoABarrelRoll(player); LUA_HookPlayer(player, HOOK(PlayerThink)); @@ -5075,7 +5018,6 @@ void P_PlayerThink(player_t *player) void P_PlayerAfterThink(player_t *player) { ticcmd_t *cmd; - //INT32 oldweapon = player->currentweapon; // SRB2kart - unused camera_t *thiscam = NULL; // if not one of the displayed players, just don't bother UINT8 i; @@ -5137,11 +5079,10 @@ void P_PlayerAfterThink(player_t *player) else if (cmd->forwardmove < 0 && player->mo->tracer->target->lastlook > player->mo->tracer->target->movecount) player->mo->tracer->target->lastlook -= 2; - if (!(player->mo->tracer->target->flags & MF_SLIDEME) // Noclimb on chain parameters gives this - && !(twodlevel || player->mo->flags2 & MF2_TWOD)) // why on earth would you want to turn them in 2D mode? + if (!(player->mo->tracer->target->flags & MF_SLIDEME)) // Noclimb on chain parameters gives this { player->mo->tracer->target->health += cmd->sidemove; - player->mo->angle += cmd->sidemove< ANGLE_MAX + player->mo->angle += cmd->sidemove << ANGLETOFINESHIFT; // 2048 --> ANGLE_MAX if (player == &players[consoleplayer]) localangle[0] = player->mo->angle; // Adjust the local control angle. @@ -5166,6 +5107,7 @@ void P_PlayerAfterThink(player_t *player) // defaults to make sure 1st person cam doesn't do anything weird on startup //player->deltaviewheight = 0; player->viewheight = FixedMul(32 << FRACBITS, player->mo->scale); + if (player->mo->eflags & MFE_VERTICALFLIP) player->viewz = player->mo->z + player->mo->height - player->viewheight; else diff --git a/src/r_fps.c b/src/r_fps.c index 5dbae1e9f..4938988dc 100644 --- a/src/r_fps.c +++ b/src/r_fps.c @@ -41,13 +41,49 @@ static CV_PossibleValue_t fpscap_cons_t[] = { {0, "Match refresh rate"}, {0, NULL} }; + consvar_t cv_fpscap = {"fpscap", "Match refresh rate", CV_SAVE, fpscap_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_fpscapbg = {"fpscapbackground", "Match refresh rate", CV_SAVE, fpscap_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_precipinterp = {"precipinterpolation", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; ps_metric_t ps_interp_frac = {0}; ps_metric_t ps_interp_lag = {0}; +static boolean R_UseBackgroundFramerateCap(void) +{ + if (!window_notinfocus) + return false; + + // if foreground is unlimited or matched to refresh rate but bg is limited + if (cv_fpscap.value <= 0 && cv_fpscapbg.value >= 0) + return true; + + // use the lower value + if ((cv_fpscap.value > 0 && cv_fpscapbg.value > 0) + && (cv_fpscapbg.value < cv_fpscap.value)) + return true; + + return false; +} + +static UINT32 R_GetBackgroundFramerateCap(void) +{ + if (cv_fpscapbg.value == 0) + { + // 0: Match refresh rate + return I_GetRefreshRate(); + } + + if (cv_fpscapbg.value < 0) + { + // -1: Unlimited + return 0; + } + + return cv_fpscapbg.value; +} + UINT32 R_GetFramerateCap(void) { if (rendermode == render_none) @@ -57,6 +93,11 @@ UINT32 R_GetFramerateCap(void) return TICRATE; } + if (R_UseBackgroundFramerateCap()) + { + return R_GetBackgroundFramerateCap(); + } + if (cv_fpscap.value == 0) { // 0: Match refresh rate @@ -167,16 +208,13 @@ void R_InterpolateViewRollAngle(fixed_t frac) void R_InterpolateView(fixed_t frac, boolean forceinvalid) { viewvars_t* prevview = oldview; - UINT8 i; if (FIXED_TO_FLOAT(frac) < 0) frac = 0; if (frac > FRACUNIT) frac = FRACUNIT; - i = R_GetViewNumber(); - - if (oldview_invalid[i] != 0 || forceinvalid) + if (oldview_invalid[R_GetViewNumber()] != 0 || forceinvalid) { // interpolate from newview to newview prevview = newview; diff --git a/src/r_fps.h b/src/r_fps.h index 2ca6f1bf3..7ed55c848 100644 --- a/src/r_fps.h +++ b/src/r_fps.h @@ -20,7 +20,7 @@ #include "r_state.h" #include "m_perfstats.h" -extern consvar_t cv_fpscap; +extern consvar_t cv_fpscap, cv_fpscapbg; extern consvar_t cv_precipinterp; extern ps_metric_t ps_interp_frac; diff --git a/src/r_main.c b/src/r_main.c index b1b707d1d..5a7d77acd 100644 --- a/src/r_main.c +++ b/src/r_main.c @@ -1576,5 +1576,6 @@ void R_RegisterEngineStuff(void) // Frame interpolation/uncapped CV_RegisterVar(&cv_fpscap); + CV_RegisterVar(&cv_fpscapbg); CV_RegisterVar(&cv_precipinterp); } diff --git a/src/screen.c b/src/screen.c index 0a9468d25..e41b5360f 100644 --- a/src/screen.c +++ b/src/screen.c @@ -65,6 +65,9 @@ consvar_t cv_renderview = {"renderview", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, consvar_t cv_vhseffect = {"vhspause", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_shittyscreen = {"televisionsignal", "Okay", CV_NOSHOWHELP, shittyscreen_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t votescale_cons_t[] = {{0, "Vanilla"}, {1, "Adaptive"}, {2, "VerticalFill"}, {3, "HorizontalFill"}, {0, NULL}}; +consvar_t cv_votebgscaling = {"votebgscaling", "Adaptive", CV_SAVE, votescale_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; + static void Highreshudscale_OnChange(void); static CV_PossibleValue_t highreshudscale_cons_t[] = {{4*FRACUNIT/5, "MIN"}, {6*FRACUNIT/5, "MAX"}, {0, NULL}}; consvar_t cv_highreshudscale = {"highreshudscale", "1", CV_SAVE|CV_FLOAT|CV_CALL|CV_NOINIT|CV_NOSHOWHELP, highreshudscale_cons_t, Highreshudscale_OnChange, 0, NULL, NULL, 0, 0, NULL}; @@ -106,41 +109,18 @@ void SCR_SetMode(void) V_SetPalette(0); - // - // setup the right draw routines for either 8bpp or 16bpp - // - if (true)//vid.bpp == 1) //Always run in 8bpp. todo: remove all 16bpp code? - { - spanfunc = basespanfunc = R_DrawSpan_8; - splatfunc = R_DrawSplat_8; - transcolfunc = R_DrawTranslatedColumn_8; - transtransfunc = R_DrawTranslatedTranslucentColumn_8; + spanfunc = basespanfunc = R_DrawSpan_8; + splatfunc = R_DrawSplat_8; + transcolfunc = R_DrawTranslatedColumn_8; + transtransfunc = R_DrawTranslatedTranslucentColumn_8; - colfunc = basecolfunc = R_DrawColumn_8; - shadecolfunc = R_DrawShadeColumn_8; - fuzzcolfunc = R_DrawTranslucentColumn_8; - walldrawerfunc = R_DrawWallColumn_8; - twosmultipatchfunc = R_Draw2sMultiPatchColumn_8; - twosmultipatchtransfunc = R_Draw2sMultiPatchTranslucentColumn_8; - } -/* else if (vid.bpp > 1) - { - I_OutputMsg("using highcolor mode\n"); - spanfunc = basespanfunc = R_DrawSpan_16; - transcolfunc = R_DrawTranslatedColumn_16; - transtransfunc = R_DrawTranslucentColumn_16; // No 16bit operation for this function + colfunc = basecolfunc = R_DrawColumn_8; + shadecolfunc = R_DrawShadeColumn_8; + fuzzcolfunc = R_DrawTranslucentColumn_8; + walldrawerfunc = R_DrawWallColumn_8; + twosmultipatchfunc = R_Draw2sMultiPatchColumn_8; + twosmultipatchtransfunc = R_Draw2sMultiPatchTranslucentColumn_8; - colfunc = basecolfunc = R_DrawColumn_16; - shadecolfunc = NULL; // detect error if used somewhere.. - fuzzcolfunc = R_DrawTranslucentColumn_16; - walldrawerfunc = R_DrawWallColumn_16; - }*/ - else - I_Error("unknown bytes per pixel mode %d\n", vid.bpp); -/* - if (SCR_IsAspectCorrect(vid.width, vid.height)) - CONS_Alert(CONS_WARNING, M_GetText("Resolution is not aspect-correct!\nUse a multiple of %dx%d\n"), BASEVIDWIDTH, BASEVIDHEIGHT); -*/ // set the apprpriate drawer for the sky (tall or INT16) setmodeneeded = 0; } @@ -164,10 +144,7 @@ void SCR_Startup(void) vid.fdupx = FixedDiv(vid.width*FRACUNIT, BASEVIDWIDTH*FRACUNIT); vid.fdupy = FixedDiv(vid.height*FRACUNIT, BASEVIDHEIGHT*FRACUNIT); -//#ifdef HWRENDER - //if (rendermode != render_opengl && rendermode != render_none) // This was just placing it incorrectly at non aspect correct resolutions in opengl -//#endif - vid.fdupx = vid.fdupy = (vid.fdupx < vid.fdupy ? vid.fdupx : vid.fdupy); + vid.fdupx = vid.fdupy = (vid.fdupx < vid.fdupy ? vid.fdupx : vid.fdupy); vid.meddupx = (UINT8)(vid.dupx >> 1) + 1; vid.meddupy = (UINT8)(vid.dupy >> 1) + 1; @@ -216,6 +193,8 @@ void SCR_Startup(void) CV_RegisterVar(&cv_bsaturation); CV_RegisterVar(&cv_msaturation); + CV_RegisterVar(&cv_votebgscaling); + V_SetPalette(0); } @@ -245,13 +224,7 @@ void SCR_Recalc(void) vid.fdupy = FixedDiv(vid.fdupy, cv_highreshudscale.value); } -#ifdef HWRENDER - //if (rendermode != render_opengl && rendermode != render_none) // This was just placing it incorrectly at non aspect correct resolutions in opengl - // 13/11/18: - // The above is no longer necessary, since we want OpenGL to be just like software now - // -- Monster Iestyn -#endif - vid.fdupx = vid.fdupy = (vid.fdupx < vid.fdupy ? vid.fdupx : vid.fdupy); + vid.fdupx = vid.fdupy = (vid.fdupx < vid.fdupy ? vid.fdupx : vid.fdupy); //vid.baseratio = FixedDiv(vid.height << FRACBITS, BASEVIDHEIGHT << FRACBITS); vid.baseratio = FRACUNIT; diff --git a/src/screen.h b/src/screen.h index 4a97e159b..224897def 100644 --- a/src/screen.h +++ b/src/screen.h @@ -153,6 +153,8 @@ extern consvar_t cv_timescale; extern consvar_t cv_alwaysgrabmouse; +extern consvar_t cv_votebgscaling; + // quick fix for tall/short skies, depending on bytesperpixel extern void (*walldrawerfunc)(void); diff --git a/src/sdl/i_system.c b/src/sdl/i_system.c index e23f155e0..b0890913a 100644 --- a/src/sdl/i_system.c +++ b/src/sdl/i_system.c @@ -1642,37 +1642,6 @@ void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) #undef WINMUMBLE #endif // NOMUMBLE -// -// I_Tactile -// -void I_Tactile(FFType pFFType, const JoyFF_t *FFEffect) -{ - // UNUSED. - (void)pFFType; - (void)FFEffect; -} - -void I_Tactile2(FFType pFFType, const JoyFF_t *FFEffect) -{ - // UNUSED. - (void)pFFType; - (void)FFEffect; -} - -void I_Tactile3(FFType pFFType, const JoyFF_t *FFEffect) -{ - // UNUSED. - (void)pFFType; - (void)FFEffect; -} - -void I_Tactile4(FFType pFFType, const JoyFF_t *FFEffect) -{ - // UNUSED. - (void)pFFType; - (void)FFEffect; -} - /** \brief empty ticcmd for player 1 */ static ticcmd_t emptycmd; diff --git a/src/sdl/ogl_sdl.c b/src/sdl/ogl_sdl.c index d6805cf21..c8701506e 100644 --- a/src/sdl/ogl_sdl.c +++ b/src/sdl/ogl_sdl.c @@ -212,7 +212,7 @@ boolean OglSdlSurface(INT32 w, INT32 h) #ifdef USE_FBO_OGL char videodriver[4] = {'S','D','L',0}; if (supportFBO && strstr((const char*)gl_renderer, "NVIDIA") - && (*strncpy(videodriver, SDL_GetCurrentVideoDriver(), 4) != '\0') + && (*strncpy(videodriver, SDL_GetCurrentVideoDriver(), sizeof(videodriver)-1) != '\0') && (strncasecmp("x11",videodriver,4) == 0)) xwaylandcrap = true; #endif @@ -221,19 +221,6 @@ boolean OglSdlSurface(INT32 w, INT32 h) 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) - { - GL_FlushScreenTextures(); - -#ifdef USE_FBO_OGL - GL_Framebuffer_DeleteAttachments(); -#endif - } - - screen_width = (GLint)w; - screen_height = (GLint)h; - GL_SetModelView(w, h); GL_SetStates(); pglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); diff --git a/src/v_video.c b/src/v_video.c index 65fcc3440..0f3306696 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -1562,6 +1562,51 @@ void V_DrawPatchFill(patch_t *pat) } } +// Draws a patch and tries to always fill the screen with the patch +void V_DrawAdaptiveScaledFullScreenPatch(patch_t *patch) +{ + fixed_t x = 0, y = 0; + fixed_t scale = ((vid.width * FRACUNIT) / patch->width); // fit the screen horizontally + fixed_t scaled_height = FixedMul(patch->height << FRACBITS, scale); + + // however, if this means the patch doesent fill out the screen vertically then + if (scaled_height < (vid.height << FRACBITS)) + { + scale = ((vid.height * FRACUNIT) / patch->height); // scale it to fit the screen vertically + x = ((vid.width << FRACBITS) - FixedMul(patch->width << FRACBITS, scale)) / 2; + } + else + y = (vid.height << FRACBITS) - scaled_height; + + V_DrawFixedPatch(x, y, scale, V_NOSCALEPATCH, patch, NULL); +} + +// Draws a patch and scales it to fill out the screen vertically while remaining centered +void V_DrawVerticallyScaledFullScreenPatch(patch_t *patch) +{ + fixed_t scale = ((vid.height * FRACUNIT) / patch->height); + fixed_t x = ((vid.width << FRACBITS) - FixedMul(patch->width << FRACBITS, scale)) / 2; // i fucking hate maths + + V_DrawFixedPatch(x, 0, scale, V_NOSCALEPATCH, patch, NULL); +} + +// Draws a patch and scales it to fill out the screen horizontally +// centers the patch when its too small to fit the screen vertically +void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch) +{ + fixed_t scale = ((vid.width * FRACUNIT) / patch->width); + fixed_t scaled_height = FixedMul(patch->height << FRACBITS, scale); + fixed_t y = (vid.height << FRACBITS) - scaled_height; + + // center it if it does not fit the screen vertically + if (scaled_height < (vid.height << FRACBITS)) + { + y /= 2; + } + + V_DrawFixedPatch(0, y, scale, V_NOSCALEPATCH, patch, NULL); +} + void V_DrawVhsEffect(boolean rewind) { static fixed_t upbary = 100*FRACUNIT, downbary = 150*FRACUNIT; diff --git a/src/v_video.h b/src/v_video.h index 00d0f6cb2..3a8cf7396 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -283,6 +283,10 @@ void V_DoPostProcessor(INT32 view, INT32 param); void V_DrawPatchFill(patch_t *pat); +void V_DrawAdaptiveScaledFullScreenPatch(patch_t *patch); +void V_DrawVerticallyScaledFullScreenPatch(patch_t *patch); +void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch); + void VID_BlitLinearScreen(const UINT8 *srcptr, UINT8 *destptr, INT32 width, INT32 height, size_t srcrowbytes, size_t destrowbytes); diff --git a/src/y_inter.c b/src/y_inter.c index 65871cc78..3c0a77ac1 100644 --- a/src/y_inter.c +++ b/src/y_inter.c @@ -294,27 +294,23 @@ static void Y_CalculateMatchData(UINT8 rankingsmode, void (*comparison)(INT32)) static void Y_AnimatedVoteScreenCheck(void) { char tmpPrefix[] = "INTS"; - boolean stopSearching = false; if (luaVoteScreen) strncpy(tmpPrefix, luaVoteScreen, 4); - else - { - if (G_BattleGametype()) - strcpy(tmpPrefix, "BTLS"); - } + else if (G_BattleGametype()) + strcpy(tmpPrefix, "BTLS"); strncpy(animPrefix, tmpPrefix, 4); animPrefix[4] = 'C'; strncpy(animWidePrefix, tmpPrefix, 4); animWidePrefix[4] = 'W'; - foundAnimVoteFrames = 0; - foundAnimVoteWideFrames = 0; + foundAnimVoteFrames = foundAnimVoteWideFrames = 0; currentAnimFrame = 0; INT32 i = 1; - while (!stopSearching) + + for (;;) { boolean normalLumpExists = W_LumpExists(va("%sC%d", tmpPrefix, i)); boolean wideLumpExists = W_LumpExists(va("%sW%d", tmpPrefix, i)); @@ -328,7 +324,7 @@ static void Y_AnimatedVoteScreenCheck(void) foundAnimVoteWideFrames++; } else // If we don't find at least frame 1 (e.g VEXTRN1), let's just stop looking - stopSearching = true; + break; i++; } @@ -608,8 +604,6 @@ void Y_Ticker(void) if (demo.savemode == DSM_WILLSAVE || demo.savemode == DSM_WILLAUTOSAVE) G_SaveDemo(); - else if (demo.savemode != DSM_TITLEENTRY) - G_ResetDemoRecording(); } // Check for pause or menu up in single player @@ -908,41 +902,67 @@ static void Y_UnloadData(void) // SRB2Kart: Voting! +static void Y_DrawVoteBackground(patch_t *patch) +{ + switch (cv_votebgscaling.value) + { + case 1: // adaptive + V_DrawAdaptiveScaledFullScreenPatch(patch); + break; + case 2: // vertical-fill + V_DrawVerticallyScaledFullScreenPatch(patch); + break; + case 3: // horizontal-fill + V_DrawHorizontallyScaledFullScreenPatch(patch); + break; + case 0: // vanilla + default: + V_DrawScaledPatch(((vid.width/2) / vid.dupx) - (patch->width/2), + (vid.height / vid.dupy) - patch->height, + V_SNAPTOTOP|V_SNAPTOLEFT, patch); + break; + } +} + // Y_DrawAnimatedVoteScreenPatch // // Draw animated patch based on frame counter on vote screen // static void Y_DrawAnimatedVoteScreenPatch(boolean widePatch) { + INT32 nextframe = 0; + patch_t *votebg = NULL; char tempAnimPrefix[7]; - widePatch ? strcpy(tempAnimPrefix, animWidePrefix) : strcpy(tempAnimPrefix, animPrefix); - const INT32 tempFoundAnimVoteFrames = widePatch ? foundAnimVoteWideFrames : foundAnimVoteFrames; + const INT32 tempFoundAnimVoteFrames = ((widePatch ? foundAnimVoteWideFrames : foundAnimVoteFrames) - 1); + + strcpy(tempAnimPrefix, (widePatch ? animWidePrefix : animPrefix)); // Just in case someone provides LESS widescreen frames than normal frames or vice versa, reset the frame counter to 0 - if (currentAnimFrame > tempFoundAnimVoteFrames - 1) + if (currentAnimFrame > tempFoundAnimVoteFrames) currentAnimFrame = 0; - patch_t *background = W_CachePatchName(va("%s%d", tempAnimPrefix, currentAnimFrame + 1), PU_PATCH); - V_DrawScaledPatch(((vid.width/2) / vid.dupx) - (background->width/2), // Keep the width/height adjustments, for screens that are less wide than 320(?) - (vid.height / vid.dupy) - background->height, - V_SNAPTOTOP|V_SNAPTOLEFT, background); + nextframe = (currentAnimFrame + 1); - if (renderisnewtic && votetic % 2 == 0 && !paused) - currentAnimFrame = (currentAnimFrame + 1 > tempFoundAnimVoteFrames - 1) ? 0 : currentAnimFrame + 1; + votebg = W_CachePatchName(va("%s%d", (widePatch ? animWidePrefix : animPrefix), nextframe), PU_PATCH); + + Y_DrawVoteBackground(votebg); + + if (renderisnewtic && (votetic % 2 == 0) && !paused) + currentAnimFrame = (nextframe > tempFoundAnimVoteFrames) ? 0 : nextframe; } static void Y_DrawVoteScreenPatch(void) { + patch_t *votebg = NULL; const boolean widescreen = (vid.width / vid.dupx > 320); - const boolean animvote = (foundAnimVoteWideFrames || foundAnimVoteFrames); - if (animvote) + if (foundAnimVoteWideFrames || foundAnimVoteFrames) { Y_DrawAnimatedVoteScreenPatch((foundAnimVoteWideFrames && widescreen)); return; } - patch_t *votebg = bgpatch; // non widescreen patch + votebg = bgpatch; // non widescreen patch UINT8 prefgametype = (votelevels[0][1] & ~0x80); const boolean widebgreplaced = (prefgametype == GT_MATCH) ? widebattlereplaced : wideracereplaced; @@ -954,9 +974,7 @@ static void Y_DrawVoteScreenPatch(void) votebg = widebgpatch; } - V_DrawScaledPatch(((vid.width/2) / vid.dupx) - (votebg->width/2), - (vid.height / vid.dupy) - votebg->height, - V_SNAPTOTOP|V_SNAPTOLEFT, votebg); + Y_DrawVoteBackground(votebg); } // @@ -1009,6 +1027,7 @@ void Y_VoteDrawer(void) } y = (200-height)/2; + for (i = 0; i < 4; i++) { const char *str; diff --git a/tools/.gitignore b/tools/.gitignore deleted file mode 100644 index e69de29bb..000000000 diff --git a/tools/IRC_Bot/SRB2MS_Bot.php b/tools/IRC_Bot/SRB2MS_Bot.php deleted file mode 100644 index 842083bf9..000000000 --- a/tools/IRC_Bot/SRB2MS_Bot.php +++ /dev/null @@ -1,227 +0,0 @@ - - * SRB2MS.php Copyright (c) 2004 by Logan Arias of Sonic Team JR. - * - * the Rest is Copyright (c) 2004 Logan Arias - * This is LGPL! that means you can change and use as you like - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -include_once('./SmartIRC.php'); - -class SRB2MS_BOT -{ - - function ListGamesPM(&$irc, &$data) - { - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012360000"; - fwrite($fd, $buff); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'Running SRB2 NetGames '); - while (1) - { - $content=fgets($fd, 13); // skip 13 first bytes - $content=fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$content"); - //echo "$content"; - if (feof($fd)) break; - } - } - else - { - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, 'The SRB2 MasterServer is not up'); - } - } - - function ListGamesChan(&$irc, &$data) - { - $fd = fsockopen("192.168.0.2", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012360000"; - fwrite($fd, $buff); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'Running SRB2 NetGames '); - while (1) - { - $content=fgets($fd, 13); // skip 13 first bytes - $content=fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - //echo "$content"; - if (feof($fd)) break; - } - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer is not up'); - } - } - - function BeenInvited(&$irc, &$data) - { - if ($data->message == '#srb2fun') - $irc->join($data->message); - - foreach ($irc->channel['#srb2fun']->ops as $invitenick => $key ) - { - if ($data->nick == $invitenick) - { - $irc->join($data->message); - return; - } - if ($data->nick == 'Logan_GBA') - { - $irc->join($data->message); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key ) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - return; - } - } - //$irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - } - - function Talk(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!talk ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Action(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!action ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_ACTION, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Kick(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!kick ", '', "$data->message"); - $irc->kick('#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function DebugPM(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "from:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->from"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "nick:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->nick"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "ident:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->ident"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "host:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->host"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "channel:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->channel"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "message:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->message"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "type:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->type"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "rawmessage:"); - $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->rawmessage"); - } - -} - -// the Bot is the Class SRB2MS_BOT -$bot = &new SRB2MS_BOT(); -// Create SmartIRC, and name it as irc for use to, well, do irc stuff ^_^ -$esperirc = &new Net_SmartIRC(); -//no Excess Flood! -//$esperirc->setSendDelay(300); -// To Debug or Not -//$esperirc->setDebug(SMARTIRC_DEBUG_IRCMESSAGES); -// Do connect to the Internet -$esperirc->setUseSockets(TRUE); -// Register the trigger !listgames as to call ListGames with the class of SRB2MS_BOT -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!gamelist$', $bot, 'ListGamesPM'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'ListGamesChan'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_INVITE, '', $bot, 'BeenInvited'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_ALL, '', $bot, 'DebugPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!talk', $bot, 'Talk'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!action', $bot, 'Action'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!kick', $bot, 'Kick'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!ban', $bot, 'Ban'); -// If you fail once, try agian -$esperirc->setAutoRetry(TRUE); -// Connect to EsperNet -$esperirc->connect('cosmos.esper.net', 6667); -// kep a list of all the users in the channel -$esperirc->setChannelSyncing(TRUE); -// Reconnect as needed -$esperirc->setAutoReconnect(TRUE); -// Use the name SRB2MS, and set other stuff -$esperirc->login('SRB2MS2', 'Net_SmartIRC Client '.SMARTIRC_VERSION.' (SRB2MS_Bot.php)', 0, 'Net_SmartIRC'); -// Join #srb2fun and #srb2general -$esperirc->join((array('#srb2general,#srb2fun'))); -// SRB2MS_Pass.php have "$esperirc->message(SMARTIRC_TYPE_QUERY, 'nickserv', 'identify ');" -include('./SRB2MS_Pass.php'); -// Idle -$esperirc->listen(); -// Rejoin? -$esperirc->reconnect(); -?> diff --git a/tools/IRC_Bot/SRB2MS_Bot_beta.php b/tools/IRC_Bot/SRB2MS_Bot_beta.php deleted file mode 100644 index 3933d5405..000000000 --- a/tools/IRC_Bot/SRB2MS_Bot_beta.php +++ /dev/null @@ -1,739 +0,0 @@ - - * SRB2MS.php Copyright (c) 2004 by Logan Arias of Sonic Team JR. - * - * the Rest is Copyright (c) 2004 Logan Arias - * This is LGPL! that means you can change and use as you like - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -include_once('./SmartIRC.php'); -define('MAGPIE_DIR', './magpierss/'); -// define('MAGPIE_CACHE_AGE', 30); // half-min -require_once(MAGPIE_DIR.'rss_fetch.inc'); -require_once(MAGPIE_DIR.'rss_utils.inc'); -$today = getdate(); -$lastupdatetime = mktime($today['hours'],$today['minutes']-6,0,$today['mon'], $today['mday'], $today['year']); -$lastlisttime = mktime($today['hours'],$today['minutes']-1,0,$today['mon'], $today['mday'], $today['year']); - -class SRB2MS_BOT -{ - - function ListUsersPM(&$irc, &$data) - { - global $rssdatabase; - if ($rssdatabase->users[0]) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'List of RSS users'); - foreach ($rssdatabase->users as $users) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$users"); - } - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'there are no RSS users'); - } - } - - function RSSupdateuser(&$irc, &$data) - { - global $rssdatabase; - if ($rssdatabase->OnList("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->message, "I am trying to update $data->nick to $data->message from the list"); - if ($rssdatabase->ReplaceUser("$data->nick","$data->message")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->message, "I have changed $data->nick to $data->message on the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->message, "$data->nick was not on the list"); - } - } - } - - function RSScheckuser(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I going to check if you are on the list"); - global $rssdatabase; - if ($rssdatabase->OnList("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "you are on the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "you are not on the list"); - } - } - - function RSSremoveuser(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I am trying to remove $data->nick from the list"); - global $rssdatabase; - if ($rssdatabase->DeleteUser("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I have removed $data->nick from the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$data->nick is not on the list"); - } - } - - function RSSadduser(&$irc, &$data) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I am trying to add you $data->nick to the list"); - global $rssdatabase; - if ($rssdatabase->AddUser("$data->nick")) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "I have added $data->nick to the list"); - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$data->nick is already on the list"); - } - } -/* - function RSSListGamesPM(&$irc, &$data) - { - $content = $this->GenFeed(); - $SRB2MSRSS10 = new MagpieRSS( $content ); - if ($SRB2MSRSS10) - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'Running SRB2 netgames '); - foreach ($SRB2MSRSS10->items as $item) - { - $description = $item['dc']['description']; - $title = $item['title']; - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "Name: $title $description"); - } - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, '.magpie_error()'); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'The SRB2 MasterServer RSS feed is not up'); - } - } -*/ - function RSSListUpdate(&$irc) - { - global $lastupdatetime; - global $SRB2MS_mute; - if ($SRB2MS_mute) - { - return; - } - $RSS10content = $this->GenFeed(); - $SRB2MSRSS10 = new MagpieRSS( $RSS10content ); - if ($SRB2MSRSS10) - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'Running SRB2 netgames '); - foreach ($SRB2MSRSS10->items as $item) - { - if ( $item['title'] == "No servers" ) - { - // NOP - } - elseif ( $item['title'] == "No master server" ) - { - // NOP - } - else - { - $published = parse_w3cdtf($item['dc']['date']); - if ( $published >= $lastupdatetime ) - { - $title = $item['title']; - $serveraddress = $item['srb2ms']['address']; - $serverport = $item['srb2ms']['port']; - $serverversion = $item['srb2ms']['version']; - //if ( $serverversion == "1.09.3" ) - //{ - // $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "New Server, $serveraddress:$serverport Name: $title"); - //} - //else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "New Server, $serveraddress:$serverport Name: $title Version: $serverversion"); - } - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2general', "New Server, Name: $title $description"); - } - else - { - // NOP - } - } - - } - $today = getdate(); - // update time - $lastupdatetime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', '.magpie_error()'); - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'The SRB2 MasterServer RSS feed is not up'); - } - } - - function Mute(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key ) - { - if ($data->nick == $nick || $data->nick == 'Logan_GBA') - { - global $lastupdatetime; - $today = getdate(); - // update time - $lastupdatetime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - $GLOBALS['SRB2MS_mute'] = TRUE; - return; - } - } - } - - function Unmute(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key ) - { - if ($data->nick == $nick || $data->nick == 'Logan_GBA') - { - $GLOBALS['SRB2MS_mute'] = FALSE; - return; - } - } - } - - - function Mute2(&$irc, &$data) - { - if ($data->nick == 'Logan_GBA') - { - global $lastupdatetime; - $today = getdate(); - // update time - $lastupdatetime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - $GLOBALS['SRB2MS_mute'] = TRUE; - } - } - - function Unmute2(&$irc, &$data) - { - if ($data->nick == 'Logan_GBA') - { - $GLOBALS['SRB2MS_mute'] = FALSE; - } - } - - function RSSListGames(&$irc, &$data) - { - global $lastlisttime; - $content = $this->GenFeed(); - $today = getdate(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'testing feed'); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - //$content1 = $this->Gettextfromserver(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content1"); - $SRB2MSRSS10 = new MagpieRSS( $content ); - if ($SRB2MSRSS10) - { - if ((mktime($today['hours'],$today['minutes']-2,0,$today['mon'], $today['mday'], $today['year'])) >= $lastlisttime) - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'Running SRB2 netgames '); - foreach ($SRB2MSRSS10->items as $item) - { - if ( $item['title'] == "No servers" ) - { - //0$description = $item['dc']['description']; - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "No SRB2 Games are running, so why don't you start one?"); - } - elseif ( $item['title'] == "No master server" ) - { - $description = $item['dc']['description']; - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$description"); - } - else - { - $title = $item['title']; - $serveraddress = $item['srb2ms']['address']; - $serverport = $item['srb2ms']['port']; - $serverversion = $item['srb2ms']['version']; - //if ( $serverport == " 5029" ) - //{ - // $serverport = "5029"; - //} - //if ( $serverversion == "1.09.3" ) - //{ - // $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "$serveraddress:$serverport Name: $title"); - //} - //else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "$serveraddress:$serverport Name: $title Version: $serverversion"); - } - - } - - } - $today = getdate(); - $lastlisttime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - } - - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, ".magpie_error()"); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer RSS feed is not up'); - } - } - - function RSSListGamesPM(&$irc, &$data) - { - global $lastlisttime; - $content = $this->GenFeed(); - $today = getdate(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'testing feed'); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - //$content1 = $this->Gettextfromserver(); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content1"); - $SRB2MSRSS10 = new MagpieRSS( $content ); - if ($SRB2MSRSS10) - { - //if ((mktime($today['hours'],$today['minutes']-2,0,$today['mon'], $today['mday'], $today['year'])) >= $lastlisttime) - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', 'Running SRB2 netgames '); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "Running SRB2 netgames from http://srb2.servegame.org/"); - foreach ($SRB2MSRSS10->items as $item) - { - if ( $item['title'] == "No servers" ) - { - //0$description = $item['dc']['description']; - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "No SRB2 Games are running, so why don't you start one?"); - } - elseif ( $item['title'] == "No master server" ) - { - $description = $item['dc']['description']; - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$description"); - } - else - { - $title = $item['title']; - $serveraddress = $item['srb2ms']['address']; - $serverport = $item['srb2ms']['port']; - $serverversion = $item['srb2ms']['version']; - //if ( $serverport == " 5029" ) - //{ - // $serverport = "5029"; - //} - //if ( $serverversion == "1.09.3" ) - //{ - // $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun' , "$serveraddress:$serverport Name: $title"); - //} - //else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$serveraddress:$serverport Name: $title Version: $serverversion"); - } - - } - - } - $today = getdate(); - $lastlisttime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - } - - } - else - { - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, ".magpie_error()"); - //$irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer RSS feed is not up'); - } - } - - function ListGamesPM(&$irc, &$data) - { - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012360000"; - fwrite($fd, $buff); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'Running SRB2 netgames '); - while (1) - { - $content=fgets($fd, 13); // skip 13 first bytes - $content=fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, "$content"); - //echo "$content"; - if (feof($fd)) break; - } - } - else - { - $irc->message(SMARTIRC_TYPE_NOTICE, $data->nick, 'The SRB2 MasterServer is not up'); - } - } - - function ListGamesChan(&$irc, &$data) - { - global $lastlisttime; - $today = getdate(); - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - stream_set_timeout ($fd, 5); - $buff = "000012360000"; - fwrite($fd, $buff); - if ( (mktime($today['hours'],$today['minutes']-5,0,$today['mon'], $today['mday'], $today['year'])) >= $lastlisttime ) - { - $content = ""; - while (1) - { - fgets($fd, 13); // skip 13 first bytes - $content = fgets($fd, 1024); - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, "$content"); - $today = getdate(); - $lastlisttime = mktime($today['hours'],$today['minutes'],0,$today['mon'], $today['mday'], $today['year']); - if (feof($fd)) break; - } - } - } - else - { - $irc->message(SMARTIRC_TYPE_CHANNEL, $data->channel, 'The SRB2 MasterServer is not up'); - } - } - - function byebye(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $quitnick => $key ) - { - if ($data->nick == $quitnick) - { - $irc->setAutoReconnect(FALSE); - $irc->setAutoRetry(FALSE); - $irc->quit('This quit was done by' + "$data->nick"); - return; - } - } - } - - function BeenInvited(&$irc, &$data) - { - if ($data->message == '#srb2fun') - $irc->join($data->message); - - foreach ($irc->channel['#srb2fun']->ops as $invitenick => $key ) - { - if ($data->nick == $invitenick) - { - $irc->join($data->message); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key ) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - return; - } - } - //$irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "Sorry, but I don't like you, or your channel, $data->message"); - } - - function Talk(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!talk ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_CHANNEL, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Action(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!action ", '', "$data->message"); - $irc->message(SMARTIRC_TYPE_ACTION, '#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function Kick(&$irc, &$data) - { - foreach ($irc->channel['#srb2fun']->ops as $nick => $key) - { - if ($data->nick == $nick) - { - $msg = str_replace("!kick ", '', "$data->message"); - $irc->kick('#srb2fun', $msg); - return; - } - } - foreach ($irc->channel['#srb2fun']->users as $nick => $key) - { - if ($data->nick == $nick) - { - $irc->kick('#srb2fun', $data->nick, 'Stop talking to me!'); - return; - } - } - } - - function DebugPM(&$irc, &$data) - { -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "from:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->from"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "nick:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->nick"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "ident:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->ident"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "host:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->host"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "channel:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->channel"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "message:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->message"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "type:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->type"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "rawmessage:"); -// $irc->message(SMARTIRC_TYPE_QUERY, $data->nick, "$data->rawmessage"); - - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "from: $data->from"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "nick: $data->nick"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "ident: $data->ident"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "host: $data->host"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "channel: $data->channel"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "message: $data->message"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "type: $data->type"); - $irc->message(SMARTIRC_TYPE_QUERY, "Alam_GBC", "rawmessage: $data->rawmessage"); - } - - function GetRSS10datafromserver() - { - $content = ""; - $fd = fsockopen("srb2.servegame.org", 28900, $errno, $errstr, 5); - if ($fd) - { - $buff = "000012400000"; - fwrite($fd, $buff); - while (1) - { - fgets($fd, 13); // skip 13 first bytes - $content .= fgets($fd, 1024); - if (feof($fd)) break; - } - fclose($fd); - } - else - { - $content = ''; - $content .= ''; - $content .= ''; - $content .= ''; - $content .= ''; - $content .= ''; - $content .= "\n"; - $content .= ' '; - $content .= 'No master serverThe master server is not running'; - } - return "$content"; - } - - function GenFeed() - { - $content = ''; - $content .= "\n"; - $content .= 'GetRSS10datafromserver(); - $content .= "$feed"; - $content .= ''; - return $content; - } -} - -class RSSDataBase_Class -{ - var $users = array(); - - function OnList($User) - { - $userbeenfound = FALSE; - foreach ($this->users as $Userlist) - { - if ($Userlist == $User) { - $userbeenfound = TRUE; } - } - return $userbeenfound; - } - - function AddUser($User) - { - $userbeenfound = FALSE; - foreach ($this->users as $Userlist) - { - if ($Userlist == $User) { - $userbeenfound = TRUE; } - } - if (!$userbeenfound) { - $this->users[] = $User; - } - return !$userbeenfound; - } - - function DeleteUser($User) - { - $userbeenfound = FALSE; - foreach ($this->users as $index => $Userlist) - { - if ($Userlist == $User) - { - $userbeenfound = TRUE; - $id = $index; - } - } - if ($userbeenfound) - { - unset($this->users[$id]); - $this->users = array_values($this->users); - } - return $userbeenfound; - } - function ReplaceUser($oldUser,$newUser) - { - $userbeenfound = FALSE; - foreach ($this->users as $index => $Userlist) - { - if ($Userlist == $oldUser) - { - $userbeenfound = TRUE; - $id = $index; - } - } - if ($userbeenfound) - { - $this->users[$id] = $newUser; - } - return $userbeenfound; - } -} -// gobal var for muting the Bot -$SRB2MS_mute = FALSE; -//$SRB2MSRSS10 = fetch_rss( 'http://srb2.servegame.org/RSS1.0.php' ); -// thing to hold RSS stuff -$rssdatabase = &new RSSDataBase_Class(); -// PHP error reporting -//error_reporting(E_ERROR); -// the Bot is the Class SRB2MS_BOT -$bot = &new SRB2MS_BOT(); -// Create SmartIRC, and name it as irc for use to, well, do irc stuff ^_^ -$esperirc = &new Net_SmartIRC(); -// To Debug or Not -//$esperirc->setDebug(SMARTIRC_DEBUG_ALL); -// Do connect to the Internet -$esperirc->setUseSockets(TRUE); -// kep a list of all the users in the channel -$esperirc->setChannelSyncing(TRUE); -// Register the triggers with the class of SRB2MS_BOT -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'ListGamesChan'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!gamelist$', $bot, 'ListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!RSSgamelist$', $bot, 'RSSListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist0$', $bot, 'RSSListGames'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'RSSListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!gamelist$', $bot, 'RSSListGamesPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!addme$', $bot, 'RSSadduser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!removeme$', $bot, 'RSSremoveuser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!listusers$', $bot, 'ListUsersPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_NICKCHANGE, '', $bot, 'RSSupdateuser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!checkme$', $bot, 'RSScheckuser'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!shutdown$', $bot, 'byebye'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!mute$', $bot, 'Mute'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!unmute$', $bot, 'Unmute'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!shutup$', $bot, 'Mute2'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!talktome$', $bot, 'Unmute2'); -$esperirc->registerTimehandler(120000, $bot, 'RSSListUpdate'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_CHANNEL, '^!gamelist$', $bot, 'ListGamesChan'); -$esperirc->registerActionhandler(SMARTIRC_TYPE_INVITE, '', $bot, 'BeenInvited'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!talk', $bot, 'Talk'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!action', $bot, 'Action'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!kick', $bot, 'Kick'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_QUERY, '^!ban', $bot, 'Ban'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_ALL, '', $bot, 'DebugPM'); -//$esperirc->registerActionhandler(SMARTIRC_TYPE_KICK | SMARTIRC_TYPE_QUIT | SMARTIRC_TYPE_PART, '', $bot, 'DebugPM'); -// If you fail once, try agian -$esperirc->setAutoRetry(TRUE); -// Connect to EsperNet -//$esperirc->connect('irc.esper.net', 6667); -$esperirc->connect('excalibur.esper.net', 6667); -// Reconnect as needed -$esperirc->setAutoReconnect(TRUE); -// Use the name SRB2MS, and set other stuff -$esperirc->login('SRB2MS', 'Net_SmartIRC Client '.SMARTIRC_VERSION.' (SRB2MS_Bot.php)', 0, 'Net_SmartIRC'); -// Join #srb2fun -$esperirc->join(array('#srb2fun')); -// SRB2MS_Pass.php have "$esperirc->message(SMARTIRC_TYPE_QUERY, 'nickserv', 'identify ');" -include('./SRB2MS_Pass.php'); -// Idle -$esperirc->listen(); -// Rejoin? -$esperirc->reconnect(); - -?> diff --git a/tools/IRC_Bot/SmartIRC.php b/tools/IRC_Bot/SmartIRC.php deleted file mode 100644 index e0167a8e5..000000000 --- a/tools/IRC_Bot/SmartIRC.php +++ /dev/null @@ -1,2553 +0,0 @@ - and - * Latest versions of Net_SmartIRC you will find on the project homepage - * or get it through PEAR since SmartIRC is an official PEAR package. - * See . - * - * Official Projet Homepage: - * - * Net_SmartIRC conforms to RFC 2812 (Internet Relay Chat: Client Protocol) - * - * Copyright (c) 2002-2003 Mirco 'meebey' Bauer - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ -// ------- PHP code ---------- -include_once('SmartIRC/defines.php'); -include_once('SmartIRC/irccommands.php'); -include_once('SmartIRC/messagehandler.php'); -define('SMARTIRC_VERSION', '1.0.0 ($Revision: 1.54.2.14 $)'); -define('SMARTIRC_VERSIONSTRING', 'Net_SmartIRC '.SMARTIRC_VERSION); - -/** - * main SmartIRC class - * - * @package Net_SmartIRC - * @version 0.5.5 - * @author Mirco 'meebey' Bauer - * @access public - */ -class Net_SmartIRC_base -{ - /** - * @var resource - * @access private - */ - var $_socket; - - /** - * @var string - * @access private - */ - var $_address; - - /** - * @var integer - * @access private - */ - var $_port; - - /** - * @var string - * @access private - */ - var $_nick; - - /** - * @var string - * @access private - */ - var $_username; - - /** - * @var string - * @access private - */ - var $_realname; - - /** - * @var string - * @access private - */ - var $_usermode; - - /** - * @var string - * @access private - */ - var $_password; - - /** - * @var boolean - * @access private - */ - var $_state = false; - - /** - * @var array - * @access private - */ - var $_actionhandler = array(); - - /** - * @var array - * @access private - */ - var $_timehandler = array(); - - /** - * @var integer - * @access private - */ - var $_debug = SMARTIRC_DEBUG_NOTICE; - - /** - * @var array - * @access private - */ - var $_messagebuffer = array(); - - /** - * @var integer - * @access private - */ - var $_messagebuffersize; - - /** - * @var boolean - * @access private - */ - var $_usesockets = false; - - /** - * @var integer - * @access private - */ - var $_receivedelay = 100; - - /** - * @var integer - * @access private - */ - var $_senddelay = 250; - - /** - * @var integer - * @access private - */ - var $_logdestination = SMARTIRC_STDOUT; - - /** - * @var resource - * @access private - */ - var $_logfilefp = 0; - - /** - * @var string - * @access private - */ - var $_logfile = 'Net_SmartIRC.log'; - - /** - * @var integer - * @access private - */ - var $_disconnecttime = 1000; - - /** - * @var boolean - * @access private - */ - var $_loggedin = false; - - /** - * @var boolean - * @access private - */ - var $_benchmark = false; - - /** - * @var integer - * @access private - */ - var $_benchmark_starttime; - - /** - * @var integer - * @access private - */ - var $_benchmark_stoptime; - - /** - * @var integer - * @access private - */ - var $_actionhandlerid = 0; - - /** - * @var integer - * @access private - */ - var $_timehandlerid = 0; - - /** - * @var array - * @access private - */ - var $_motd = array(); - - /** - * @var array - * @access private - */ - var $_channels = array(); - - /** - * @var boolean - * @access private - */ - var $_channelsyncing = false; - - /** - * @var string - * @access private - */ - var $_ctcpversion; - - /** - * @var mixed - * @access private - */ - var $_mintimer = false; - - /** - * @var integer - * @access private - */ - var $_maxtimer = 300000; - - /** - * @var integer - * @access private - */ - var $_txtimeout = 300; - - /** - * @var integer - * @access private - */ - var $_rxtimeout = 300; - - /** - * @var integer - * @access private - */ - var $_selecttimeout; - - /** - * @var integer - * @access private - */ - var $_lastrx; - - /** - * @var integer - * @access private - */ - var $_lasttx; - - /** - * @var boolean - * @access private - */ - var $_autoreconnect = false; - - /** - * @var boolean - * @access private - */ - var $_autoretry = false; - - /** - * All IRC replycodes, the index is the replycode name. - * - * @see $SMARTIRC_replycodes - * @var array - * @access public - */ - var $replycodes; - - /** - * All numeric IRC replycodes, the index is the numeric replycode. - * - * @see $SMARTIRC_nreplycodes - * @var array - * @access public - */ - var $nreplycodes; - - /** - * Stores all channels in this array where we are joined, works only if channelsyncing is activated. - * Eg. for accessing a user, use it like this: (in this example the SmartIRC object is stored in $irc) - * $irc->channel['#test']->users['meebey']->nick; - * - * @see setChannelSyncing() - * @see Net_SmartIRC_channel - * @see Net_SmartIRC_channeluser - * @var array - * @access public - */ - var $channel; - - /** - * Constructor. Initiales the messagebuffer and "links" the replycodes from - * global into properties. Also some PHP runtime settings are configured. - * - * @access public - * @return void - */ - function Net_SmartIRC_base() - { - // precheck - $this->_checkPHPVersion(); - - ob_implicit_flush(true); - @set_time_limit(0); - ignore_user_abort(true); - $this->_messagebuffer[SMARTIRC_CRITICAL] = array(); - $this->_messagebuffer[SMARTIRC_HIGH] = array(); - $this->_messagebuffer[SMARTIRC_MEDIUM] = array(); - $this->_messagebuffer[SMARTIRC_LOW] = array(); - $this->replycodes = &$GLOBALS['SMARTIRC_replycodes']; - $this->nreplycodes = &$GLOBALS['SMARTIRC_nreplycodes']; - - // hack till PHP allows (PHP5) $object->method($param)->$object - $this->channel = &$this->_channels; - // another hack - $this->user = &$this->_users; - - if (isset($_SERVER['REQUEST_METHOD'])) { - // the script is called from a browser, lets set default log destination - // to SMARTIRC_BROWSEROUT (makes browser friendly output) - $this->setLogdestination(SMARTIRC_BROWSEROUT); - } - } - - /** - * Enables/disables the usage of real sockets. - * - * Enables/disables the usage of real sockets instead of fsocks - * (works only if your PHP build has loaded the PHP socket extension) - * Default: false - * - * @param bool $boolean - * @return void - * @access public - */ - function setUseSockets($boolean) - { - if ($boolean === true) { - if (@extension_loaded('sockets')) { - $this->_usesockets = true; - } else { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket extension not loaded, trying to load it...', __FILE__, __LINE__); - - if (strtoupper(substr(PHP_OS, 0,3) == 'WIN')) { - $load_status = @dl('php_sockets.dll'); - } else { - $load_status = @dl('sockets.so'); - } - - if ($load_status) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket extension succesfully loaded', __FILE__, __LINE__); - $this->_usesockets = true; - } else { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: couldn\'t load the socket extension', __FILE__, __LINE__); - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: your PHP build doesn\'t support real sockets, will use fsocks instead', __FILE__, __LINE__); - $this->_usesockets = false; - } - } - } else { - $this->_usesockets = false; - } - } - - /** - * Sets the level of debug messages. - * - * Sets the debug level (bitwise), useful for testing/developing your code. - * Here the list of all possible debug levels: - * SMARTIRC_DEBUG_NONE - * SMARTIRC_DEBUG_NOTICE - * SMARTIRC_DEBUG_CONNECTION - * SMARTIRC_DEBUG_SOCKET - * SMARTIRC_DEBUG_IRCMESSAGES - * SMARTIRC_DEBUG_MESSAGETYPES - * SMARTIRC_DEBUG_ACTIONHANDLER - * SMARTIRC_DEBUG_TIMEHANDLER - * SMARTIRC_DEBUG_MESSAGEHANDLER - * SMARTIRC_DEBUG_CHANNELSYNCING - * SMARTIRC_DEBUG_MODULES - * SMARTIRC_DEBUG_USERSYNCING - * SMARTIRC_DEBUG_ALL - * - * Default: SMARTIRC_DEBUG_NOTICE - * - * @see DOCUMENTATION - * @see SMARTIRC_DEBUG_NOTICE - * @param integer $level - * @return void - * @access public - */ - function setDebug($level) - { - $this->_debug = $level; - } - - /** - * Enables/disables the benchmark engine. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setBenchmark($boolean) - { - if (is_bool($boolean)) { - $this->_benchmark = $boolean; - } else { - $this->_benchmark = false; - } - } - - /** - * Deprecated, use setChannelSyncing() instead! - * - * @deprecated - * @param boolean $boolean - * @return void - * @access public - */ - function setChannelSynching($boolean) - { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: you are using setChannelSynching() which is a deprecated method, use setChannelSyncing() instead!', __FILE__, __LINE__); - $this->setChannelSyncing($boolean); - } - - /** - * Enables/disables channel syncing. - * - * Channel syncing means, all users on all channel we are joined are tracked in the - * channel array. This makes it very handy for botcoding. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setChannelSyncing($boolean) - { - if (is_bool($boolean)) { - $this->_channelsyncing = $boolean; - } else { - $this->_channelsyncing = false; - } - - if ($this->_channelsyncing == true) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: Channel syncing enabled', __FILE__, __LINE__); - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: Channel syncing disabled', __FILE__, __LINE__); - } - } - - /** - * Sets the CTCP version reply string. - * - * @param string $versionstring - * @return void - * @access public - */ - function setCtcpVersion($versionstring) - { - $this->_ctcpversion = $versionstring; - } - - /** - * Sets the destination of all log messages. - * - * Sets the destination of log messages. - * $type can be: - * SMARTIRC_FILE for saving the log into a file - * SMARTIRC_STDOUT for echoing the log to stdout - * SMARTIRC_SYSLOG for sending the log to the syslog - * Default: SMARTIRC_STDOUT - * - * @see SMARTIRC_STDOUT - * @param integer $type must be on of the constants - * @return void - * @access public - */ - function setLogdestination($type) - { - switch ($type) { - case (SMARTIRC_FILE || - SMARTIRC_STDOUT || - SMARTIRC_SYSLOG || - SMARTIRC_BROWSEROUT || - SMARTIRC_NONE): - $this->_logdestination = $type; - break; - default: - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: unknown logdestination type ('.$type.'), will use STDOUT instead', __FILE__, __LINE__); - $this->_logdestination = SMARTIRC_STDOUT; - } - } - - /** - * Sets the file for the log if the destination is set to file. - * - * Sets the logfile, if {@link setLogdestination logdestination} is set to SMARTIRC_FILE. - * This should be only used with full path! - * - * @param string $file - * @return void - * @access public - */ - function setLogfile($file) - { - $this->_logfile = $file; - } - - /** - * Sets the delaytime before closing the socket when disconnect. - * - * @param integer $milliseconds - * @return void - * @access public - */ - function setDisconnecttime($milliseconds) - { - if (is_integer($milliseconds) && $milliseconds >= 100) { - $this->_disconnecttime = $milliseconds; - } else { - $this->_disconnecttime = 100; - } - } - - /** - * Sets the delay for receiving data from the IRC server. - * - * Sets the delaytime between messages that are received, this reduces your CPU load. - * Don't set this too low (min 100ms). - * Default: 100 - * - * @param integer $milliseconds - * @return void - * @access public - */ - function setReceivedelay($milliseconds) - { - if (is_integer($milliseconds) && $milliseconds >= 100) { - $this->_receivedelay = $milliseconds; - } else { - $this->_receivedelay = 100; - } - } - - /** - * Sets the delay for sending data to the IRC server. - * - * Sets the delaytime between messages that are sent, because IRC servers doesn't like floods. - * This will avoid sending your messages too fast to the IRC server. - * Default: 250 - * - * @param integer $milliseconds - * @return void - * @access public - */ - function setSenddelay($milliseconds) - { - if (is_integer($milliseconds)) { - $this->_senddelay = $milliseconds; - } else { - $this->_senddelay = 250; - } - } - - /** - * Enables/disables autoreconnecting. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setAutoReconnect($boolean) - { - if (is_bool($boolean)) { - $this->_autoreconnect = $boolean; - } else { - $this->_autoreconnect = false; - } - } - - /** - * Enables/disables autoretry for connecting to a server. - * - * @param boolean $boolean - * @return void - * @access public - */ - function setAutoRetry($boolean) - { - if (is_bool($boolean)) { - $this->_autoretry = $boolean; - } else { - $this->_autoretry = false; - } - } - - /** - * Sets the receive timeout. - * - * If the timeout occurs, the connection will be reinitialized - * Default: 300 seconds - * - * @param integer $seconds - * @return void - * @access public - */ - function setReceiveTimeout($seconds) - { - if (is_integer($seconds)) { - $this->_rxtimeout = $seconds; - } else { - $this->_rxtimeout = 300; - } - } - - /** - * Sets the transmit timeout. - * - * If the timeout occurs, the connection will be reinitialized - * Default: 300 seconds - * - * @param integer $seconds - * @return void - * @access public - */ - function setTransmitTimeout($seconds) - { - if (is_integer($seconds)) { - $this->_txtimeout = $seconds; - } else { - $this->_txtimeout = 300; - } - } - - /** - * Starts the benchmark (sets the counters). - * - * @return void - * @access public - */ - function startBenchmark() - { - $this->_benchmark_starttime = $this->_microint(); - $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark started', __FILE__, __LINE__); - } - - /** - * Stops the benchmark and displays the result. - * - * @return void - * @access public - */ - function stopBenchmark() - { - $this->_benchmark_stoptime = $this->_microint(); - $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark stopped', __FILE__, __LINE__); - - if ($this->_benchmark) { - $this->showBenchmark(); - } - } - - /** - * Shows the benchmark result. - * - * @return void - * @access public - */ - function showBenchmark() - { - $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark time: '.((float)$this->_benchmark_stoptime-(float)$this->_benchmark_starttime), __FILE__, __LINE__); - } - - /** - * Adds an entry to the log. - * - * Adds an entry to the log with Linux style log format. - * Possible $level constants (can also be combined with "|"s) - * SMARTIRC_DEBUG_NONE - * SMARTIRC_DEBUG_NOTICE - * SMARTIRC_DEBUG_CONNECTION - * SMARTIRC_DEBUG_SOCKET - * SMARTIRC_DEBUG_IRCMESSAGES - * SMARTIRC_DEBUG_MESSAGETYPES - * SMARTIRC_DEBUG_ACTIONHANDLER - * SMARTIRC_DEBUG_TIMEHANDLER - * SMARTIRC_DEBUG_MESSAGEHANDLER - * SMARTIRC_DEBUG_CHANNELSYNCING - * SMARTIRC_DEBUG_MODULES - * SMARTIRC_DEBUG_USERSYNCING - * SMARTIRC_DEBUG_ALL - * - * @see SMARTIRC_DEBUG_NOTICE - * @param integer $level bit constants (SMARTIRC_DEBUG_*) - * @param string $entry the new log entry - * @return void - * @access public - */ - function log($level, $entry, $file = null, $line = null) - { - // prechecks - if (!(is_integer($level)) || - !($level & SMARTIRC_DEBUG_ALL)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: invalid log level passed to log() ('.$level.')', __FILE__, __LINE__); - return; - } - - if (!($level & $this->_debug) || - ($this->_logdestination == SMARTIRC_NONE)) { - return; - } - - if (substr($entry, -1) != "\n") { - $entry .= "\n"; - } - - if ($file !== null && - $line !== null) { - $file = basename($file); - $entry = $file.'('.$line.') '.$entry; - } else { - $entry = 'unknown(0) '.$entry; - } - - $formatedentry = date('M d H:i:s ').$entry; - switch ($this->_logdestination) { - case SMARTIRC_STDOUT: - echo $formatedentry; - flush(); - break; - case SMARTIRC_BROWSEROUT: - echo '
'.htmlentities($formatedentry).'
'; - break; - case SMARTIRC_FILE: - if (!is_resource($this->_logfilefp)) { - if ($this->_logfilefp === null) { - // we reconncted and don't want to destroy the old log entries - $this->_logfilefp = @fopen($this->_logfile,'a'); - } else { - $this->_logfilefp = @fopen($this->_logfile,'w'); - } - } - @fwrite($this->_logfilefp, $formatedentry); - fflush($this->_logfilefp); - break; - case SMARTIRC_SYSLOG: - define_syslog_variables(); - if (!is_int($this->_logfilefp)) { - $this->_logfilefp = openlog('Net_SmartIRC', LOG_NDELAY, LOG_DAEMON); - } - syslog(LOG_INFO, $entry); - break; - } - } - - /** - * Returns the full motd. - * - * @return array - * @access public - */ - function getMotd() - { - return $this->_motd; - } - - /** - * Returns the usermode. - * - * @return string - * @access public - */ - function getUsermode() - { - return $this->_usermode; - } - - /** - * Creates the sockets and connects to the IRC server on the given port. - * - * @param string $address - * @param integer $port - * @return void - * @access public - */ - function connect($address, $port) - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connecting', __FILE__, __LINE__); - $this->_address = $address; - $this->_port = $port; - - if ($this->_usesockets == true) { - $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: using real sockets', __FILE__, __LINE__); - $this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - $result = @socket_connect($this->_socket, $this->_address, $this->_port); - } else { - $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: using fsockets', __FILE__, __LINE__); - $result = @fsockopen($this->_address, $this->_port, $errno, $errstr); - } - - if ($result === false) { - if ($this->_usesockets == true) { - $error = socket_strerror(socket_last_error($this->_socket)); - } else { - $error = $errstr.' ('.$errno.')'; - } - - $error_msg = 'couldn\'t connect to "'.$address.'" reason: "'.$error.'"'; - $this->log(SMARTIRC_DEBUG_NOTICE, 'DEBUG_NOTICE: '.$error_msg, __FILE__, __LINE__); - // TODO! muss return wert sein - $this->throwError($error_msg); - - // doesn't work somehow.... I only want to retry 4 times! no endless loop (causes segfault) - static $tries = 0; - if ($this->_autoretry == true && $tries < 5) { - $this->reconnect(); - $tries++; - } else { - die(); - } - } else { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connected', __FILE__, __LINE__); - - if ($this->_usesockets != true) { - $this->_socket = $result; - $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: activating nonblocking fsocket mode', __FILE__, __LINE__); - socket_set_blocking($this->_socket, false); - } - } - - $this->_lastrx = time(); - $this->_lasttx = $this->_lastrx; - $this->_updatestate(); - - if ($result !== false) { - return true; - } else { - return false; - } - } - - /** - * Disconnects from the IRC server nicely with a QUIT or just destroys the socket. - * - * Disconnects from the IRC server in the given quickness mode. - * $quickdisconnect: - * true, just close the socket - * false, send QUIT and wait {@link $_disconnectime $_disconnectime} before closing the socket - * - * @param boolean $quickdisconnect default: false - * @return boolean - * @access public - */ - function disconnect($quickdisconnect = false) - { - if ($this->_state() == SMARTIRC_STATE_CONNECTED) { - if ($quickdisconnect == false) { - $this->_send('QUIT', SMARTIRC_CRITICAL); - usleep($this->_disconnecttime*1000); - } - - if ($this->_usesockets == true) { - @socket_shutdown($this->_socket); - @socket_close($this->_socket); - } else { - fclose($this->_socket); - } - - $this->_updatestate(); - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: disconnected', __FILE__, __LINE__); - } else { - return false; - } - - if ($this->_channelsyncing == true) { - // let's clean our channel array - $this->_channels = array(); - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: cleaned channel array', __FILE__, __LINE__); - } - - if ($this->_logdestination == SMARTIRC_FILE) { - fclose($this->_logfilefp); - $this->_logfilefp = null; - } else if ($this->_logdestination == SMARTIRC_SYSLOG) { - closelog(); - } - - return true; - } - - /** - * Reconnects to the IRC server with the same login info, - * it also rejoins the channels - * - * @return void - * @access public - */ - function reconnect() - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: reconnecting...', __FILE__, __LINE__); - - // remember in which channels we are joined - $channels = array(); - foreach ($this->_channels as $value) { - if (empty($value->key)) { - $channels[] = array('name' => $value->name); - } else { - $channels[] = array('name' => $value->name, 'key' => $value->key); - } - } - - $this->disconnect(true); - $this->connect($this->_address, $this->_port); - $this->login($this->_nick, $this->_realname, $this->_usermode, $this->_username, $this->_password); - - // rejoin the channels - foreach ($channels as $value) { - if (isset($value['key'])) { - $this->join($value['name'], $value['key']); - } else { - $this->join($value['name']); - } - } - } - - /** - * login and register nickname on the IRC network - * - * Registers the nickname and user information on the IRC network. - * - * @param string $nick - * @param string $realname - * @param integer $usermode - * @param string $username - * @param string $password - * @return void - * @access public - */ - function login($nick, $realname, $usermode = 0, $username = null, $password = null) - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: logging in', __FILE__, __LINE__); - - $this->_nick = str_replace(' ', '', $nick); - $this->_realname = $realname; - - if ($username !== null) { - $this->_username = str_replace(' ', '', $username); - } else { - $this->_username = str_replace(' ', '', exec('whoami')); - } - - if ($password !== null) { - $this->_password = $password; - $this->_send('PASS '.$this->_password, SMARTIRC_CRITICAL); - } - - if (!is_numeric($usermode)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'DEBUG_NOTICE: login() usermode ('.$usermode.') is not valid, will use 0 instead', __FILE__, __LINE__); - $usermode = 0; - } - - $this->_send('NICK '.$this->_nick, SMARTIRC_CRITICAL); - $this->_send('USER '.$this->_username.' '.$usermode.' '.SMARTIRC_UNUSED.' :'.$this->_realname, SMARTIRC_CRITICAL); - } - - // - - /** - * checks if we or the given user is joined to the specified channel and returns the result - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $nickname - * @return boolean - * @access public - */ - function isJoined($channel, $nickname = null) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isJoined() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($nickname === null) { - $nickname = $this->_nick; - } - - if (isset($this->_channels[strtolower($channel)]->users[strtolower($nickname)])) { - return true; - } - - return false; - } - - /** - * Checks if we or the given user is opped on the specified channel and returns the result. - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $nickname - * @return boolean - * @access public - */ - function isOpped($channel, $nickname = null) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isOpped() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($nickname === null) { - $nickname = $this->_nick; - } - - if ($this->isJoined($channel, $nickname)) { - if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->op) { - return true; - } - } - - return false; - } - - /** - * Checks if we or the given user is voiced on the specified channel and returns the result. - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $nickname - * @return boolean - * @access public - */ - function isVoiced($channel, $nickname = null) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isVoiced() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($nickname === null) { - $nickname = $this->_nick; - } - - if ($this->isJoined($channel, $nickname)) { - if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->voice) { - return true; - } - } - - return false; - } - - /** - * Checks if the hostmask is on the specified channel banned and returns the result. - * ChannelSyncing is required for this. - * - * @see setChannelSyncing - * @param string $channel - * @param string $hostmask - * @return boolean - * @access public - */ - function isBanned($channel, $hostmask) - { - if ($this->_channelsyncing != true) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isBanned() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); - return false; - } - - if ($this->isJoined($channel)) { - $result = array_search($hostmask, $this->_channels[strtolower($channel)]->bans); - - if ($result !== false) { - return true; - } - } - - return false; - } - - /** - * goes into receive mode - * - * Goes into receive and idle mode. Only call this if you want to "spawn" the bot. - * No further lines of PHP code will be processed after this call, only the bot methods! - * - * @return boolean - * @access public - */ - function listen() - { - if ($this->_state() == SMARTIRC_STATE_CONNECTED) { - $this->_rawreceive(); - return true; - } else { - return false; - } - } - - /** - * waits for a special message type and puts the answer in $result - * - * Creates a special actionhandler for that given TYPE and returns the answer. - * This will only receive the requested type, immediately quit and disconnect from the IRC server. - * Made for showing IRC statistics on your homepage, or other IRC related information. - * - * @param integer $messagetype see in the documentation 'Message Types' - * @return array answer from the IRC server for this $messagetype - * @access public - */ - function listenFor($messagetype) - { - $listenfor = &new Net_SmartIRC_listenfor(); - $this->registerActionhandler($messagetype, '.*', $listenfor, 'handler'); - $this->listen(); - $result = $listenfor->result; - - if (isset($listenfor)) { - unset($listenfor); - } - - return $result; - } - - /** - * waits for a special message type and puts the answer in $result - * - * Creates a special actionhandler for that given TYPE and returns the answer. - * This will only receive the requested type, immediately quit and disconnect from the IRC server. - * Made for showing IRC statistics on your homepage, or other IRC related information. - * This special version of listenFor() stores the whole ircdata object, not just the message! - * - * @param integer $messagetype see in the documentation 'Message Types' - * @return array answer from the IRC server for this $messagetype - * @access public - */ - function objListenFor($messagetype) - { - $objlistenfor = &new Net_SmartIRC_objListenFor(); - $this->registerActionhandler($messagetype, '.*', $objlistenfor, 'handler'); - $this->listen(); - $result = $objlistenfor->result; - - if (isset($objlistenfor)) { - unset($objlistenfor); - } - - return $result; - } - - /** - * registers a new actionhandler and returns the assigned id - * - * Registers an actionhandler in Net_SmartIRC for calling it later. - * The actionhandler id is needed for unregistering the actionhandler. - * - * @see example.php - * @param integer $handlertype bits constants, see in this documentation Message Types - * @param string $regexhandler the message that has to be in the IRC message in regex syntax - * @param object $object a reference to the objects of the method - * @param string $methodname the methodname that will be called when the handler happens - * @return integer assigned actionhandler id - * @access public - */ - function registerActionhandler($handlertype, $regexhandler, &$object, $methodname) - { - // precheck - if (!$this->_isValidType($handlertype)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: passed invalid handlertype to registerActionhandler()', __FILE__, __LINE__); - return false; - } - - $id = $this->_actionhandlerid++; - $newactionhandler = &new Net_SmartIRC_actionhandler(); - - $newactionhandler->id = $id; - $newactionhandler->type = $handlertype; - $newactionhandler->message = $regexhandler; - $newactionhandler->object = &$object; - $newactionhandler->method = $methodname; - - $this->_actionhandler[] = &$newactionhandler; - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') registered', __FILE__, __LINE__); - return $id; - } - - /** - * unregisters an existing actionhandler - * - * @param integer $handlertype - * @param string $regexhandler - * @param object $object - * @param string $methodname - * @return boolean - * @access public - */ - function unregisterActionhandler($handlertype, $regexhandler, &$object, $methodname) - { - // precheck - if (!$this->_isValidType($handlertype)) { - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: passed invalid handlertype to unregisterActionhandler()', __FILE__, __LINE__); - return false; - } - - $handler = &$this->_actionhandler; - $handlercount = count($handler); - - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if ($handlerobject->type == $handlertype && - $handlerobject->message == $regexhandler && - $handlerobject->method == $methodname) { - - $id = $handlerobject->id; - - if (isset($this->_actionhandler[$i])) { - unset($this->_actionhandler[$i]); - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') unregistered', __FILE__, __LINE__); - $this->_reorderactionhandler(); - return true; - } - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: could not find actionhandler type: "'.$handlertype.'" message: "'.$regexhandler.'" method: "'.$methodname.'" from object "'.get_class($object).'" _not_ unregistered', __FILE__, __LINE__); - return false; - } - - /** - * unregisters an existing actionhandler via the id - * - * @param integer $id - * @return boolean - * @access public - */ - function unregisterActionid($id) - { - $handler = &$this->_actionhandler; - $handlercount = count($handler); - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if ($handlerobject->id == $id) { - if (isset($this->_actionhandler[$i])) { - unset($this->_actionhandler[$i]); - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') unregistered', __FILE__, __LINE__); - $this->_reorderactionhandler(); - return true; - } - } - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: could not find actionhandler id: '.$id.' _not_ unregistered', __FILE__, __LINE__); - return false; - } - - /** - * registers a timehandler and returns the assigned id - * - * Registers a timehandler in Net_SmartIRC, which will be called in the specified interval. - * The timehandler id is needed for unregistering the timehandler. - * - * @see example7.php - * @param integer $interval interval time in milliseconds - * @param object $object a reference to the objects of the method - * @param string $methodname the methodname that will be called when the handler happens - * @return integer assigned timehandler id - * @access public - */ - function registerTimehandler($interval, &$object, $methodname) - { - $id = $this->_timehandlerid++; - $newtimehandler = &new Net_SmartIRC_timehandler(); - - $newtimehandler->id = $id; - $newtimehandler->interval = $interval; - $newtimehandler->object = &$object; - $newtimehandler->method = $methodname; - $newtimehandler->lastmicrotimestamp = $this->_microint(); - - $this->_timehandler[] = &$newtimehandler; - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: timehandler('.$id.') registered', __FILE__, __LINE__); - - if (($interval < $this->_mintimer) || ($this->_mintimer == false)) { - $this->_mintimer = $interval; - } - - return $id; - } - - /** - * unregisters an existing timehandler via the id - * - * @see example7.php - * @param integer $id - * @return boolean - * @access public - */ - function unregisterTimeid($id) - { - $handler = &$this->_timehandler; - $handlercount = count($handler); - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if ($handlerobject->id == $id) { - if (isset($this->_timehandler[$i])) { - unset($this->_timehandler[$i]); - } - - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: timehandler('.$id.') unregistered', __FILE__, __LINE__); - $this->_reordertimehandler(); - $this->_updatemintimer(); - return true; - } - } - - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: could not find timehandler id: '.$id.' _not_ unregistered', __FILE__, __LINE__); - return false; - } - - // - /** - * changes a already used nickname to a new nickname plus 3 random digits - * - * @return void - * @access private - */ - function _nicknameinuse() - { - $newnickname = substr($this->_nick, 0, 5).rand(0, 999); - $this->changeNick($newnickname, SMARTIRC_CRITICAL); - } - - /** - * sends an IRC message - * - * Adds a message to the messagequeue, with the optional priority. - * $priority: - * SMARTIRC_CRITICAL - * SMARTIRC_HIGH - * SMARTIRC_MEDIUM - * SMARTIRC_LOW - * - * @param string $data - * @param integer $priority must be one of the priority constants - * @return boolean - * @access private - */ - function _send($data, $priority = SMARTIRC_MEDIUM) - { - switch ($priority) { - case SMARTIRC_CRITICAL: - $this->_rawsend($data); - return true; - break; - case (SMARTIRC_HIGH|| - SMARTIRC_MEDIUM|| - SMARTIRC_LOW): - $this->_messagebuffer[$priority][] = $data; - return true; - break; - default: - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: message ('.$data.') with an invalid priority passed ('.$priority.'), message is ignored!', __FILE__, __LINE__); - return false; - } - } - - /** - * checks the buffer if there are messages to send - * - * @return void - * @access private - */ - function _checkbuffer() - { - if (!$this->_loggedin) { - return; - } - - static $highsent = 0; - static $lastmicrotimestamp = 0; - - if ($lastmicrotimestamp == 0) { - $lastmicrotimestamp = $this->_microint(); - } - - $highcount = count($this->_messagebuffer[SMARTIRC_HIGH]); - $mediumcount = count($this->_messagebuffer[SMARTIRC_MEDIUM]); - $lowcount = count($this->_messagebuffer[SMARTIRC_LOW]); - $this->_messagebuffersize = $highcount+$mediumcount+$lowcount; - - // don't send them too fast - if ($this->_microint() >= ($lastmicrotimestamp+($this->_senddelay/1000))) { - if ($highcount > 0 && $highsent <= 2) { - $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_HIGH])); - $lastmicrotimestamp = $this->_microint(); - $highsent++; - } else if ($mediumcount > 0) { - $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_MEDIUM])); - $lastmicrotimestamp = $this->_microint(); - $highsent = 0; - } else if ($lowcount > 0) { - $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_LOW])); - $lastmicrotimestamp = $this->_microint(); - } - } - } - - /** - * Checks the running timers and calls the registered timehandler, - * when the interval is reached. - * - * @return void - * @access private - */ - function _checktimer() - { - if (!$this->_loggedin) { - return; - } - - // has to be count() because the array may change during the loop! - for ($i = 0; $i < count($this->_timehandler); $i++) { - $handlerobject = &$this->_timehandler[$i]; - $microtimestamp = $this->_microint(); - if ($microtimestamp >= ($handlerobject->lastmicrotimestamp+($handlerobject->interval/1000))) { - $methodobject = &$handlerobject->object; - $method = $handlerobject->method; - $handlerobject->lastmicrotimestamp = $microtimestamp; - - if (@method_exists($methodobject, $method)) { - $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: calling method "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); - $methodobject->$method($this); - } - } - } - } - - /** - * Checks if a receive or transmit timeout occured and reconnects if configured - * - * @return void - * @access private - */ - function _checktimeout() - { - if ($this->_autoreconnect == true) { - $timestamp = time(); - if ($this->_lastrx < ($timestamp - $this->_rxtimeout)) { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: receive timeout detected, doing reconnect...', __FILE__, __LINE__); - $this->reconnect(); - } else if ($this->_lasttx < ($timestamp - $this->_txtimeout)) { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: transmit timeout detected, doing reconnect...', __FILE__, __LINE__); - $this->reconnect(); - } - } - } - - /** - * sends a raw message to the IRC server (don't use this!!) - * - * Use message() or _send() instead. - * - * @param string $data - * @return boolean - * @access private - */ - function _rawsend($data) - { - if ($this->_state() == SMARTIRC_STATE_CONNECTED) { - $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: sent: "'.$data.'"', __FILE__, __LINE__); - - if ($this->_usesockets == true) { - $result = @socket_write($this->_socket, $data.SMARTIRC_CRLF); - } else { - $result = @fwrite($this->_socket, $data.SMARTIRC_CRLF); - } - - - if ($result === false) { - return false; - } else { - $this->_lasttx = time(); - return true; - } - } else { - return false; - } - } - - /** - * goes into main idle loop for waiting messages from the IRC server - * - * @return void - * @access private - */ - function _rawreceive() - { - $lastpart = ''; - $rawdataar = array(); - - while ($this->_state() == SMARTIRC_STATE_CONNECTED) { - $this->_checkbuffer(); - - $timeout = $this->_selecttimeout(); - if ($this->_usesockets == true) { - $sread = array($this->_socket); - $result = @socket_select($sread, $w = null, $e = null, 0, $timeout*1000); - - if ($result == 1) { - // the socket got data to read - $rawdata = @socket_read($this->_socket, 10240); - } else if ($result === false) { - // panic! panic! something went wrong! - $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket_select() returned false, something went wrong! Reason: '.socket_strerror(socket_last_error()), __FILE__, __LINE__); - exit; - } else { - // no data - $rawdata = null; - } - } else { - usleep($this->_receivedelay*1000); - $rawdata = @fread($this->_socket, 10240); - } - - $this->_checktimer(); - $this->_checktimeout(); - - if ($rawdata !== null && !empty($rawdata)) { - $this->_lastrx = time(); - $rawdata = str_replace("\r", '', $rawdata); - $rawdata = $lastpart.$rawdata; - - $lastpart = substr($rawdata, strrpos($rawdata ,"\n")+1); - $rawdata = substr($rawdata, 0, strrpos($rawdata ,"\n")); - $rawdataar = explode("\n", $rawdata); - } - - // loop through our received messages - while (count($rawdataar) > 0) { - $rawline = array_shift($rawdataar); - $validmessage = false; - - $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: received: "'.$rawline.'"', __FILE__, __LINE__); - - // building our data packet - $ircdata = &new Net_SmartIRC_data(); - $ircdata->rawmessage = $rawline; - $lineex = explode(' ', $rawline); - $ircdata->rawmessageex = $lineex; - $messagecode = $lineex[0]; - - if (substr($rawline, 0, 1) == ':') { - $validmessage = true; - $line = substr($rawline, 1); - $lineex = explode(' ', $line); - - // conform to RFC 2812 - $from = $lineex[0]; - $messagecode = $lineex[1]; - $exclamationpos = strpos($from, '!'); - $atpos = strpos($from, '@'); - $colonpos = strpos($line, ' :'); - if ($colonpos !== false) { - // we want the exact position of ":" not beginning from the space - $colonpos += 1; - } - $ircdata->nick = substr($from, 0, $exclamationpos); - $ircdata->ident = substr($from, $exclamationpos+1, ($atpos-$exclamationpos)-1); - $ircdata->host = substr($from, $atpos+1); - $ircdata->type = $this->_gettype($rawline); - $ircdata->from = $from; - if ($colonpos !== false) { - $ircdata->message = substr($line, $colonpos+1); - $ircdata->messageex = explode(' ', $ircdata->message); - } - - if ($ircdata->type & (SMARTIRC_TYPE_CHANNEL| - SMARTIRC_TYPE_ACTION| - SMARTIRC_TYPE_MODECHANGE| - SMARTIRC_TYPE_KICK| - SMARTIRC_TYPE_PART| - SMARTIRC_TYPE_JOIN)) { - $ircdata->channel = $lineex[2]; - } else if ($ircdata->type & (SMARTIRC_TYPE_WHO| - SMARTIRC_TYPE_BANLIST| - SMARTIRC_TYPE_TOPIC| - SMARTIRC_TYPE_CHANNELMODE)) { - $ircdata->channel = $lineex[3]; - } else if ($ircdata->type & SMARTIRC_TYPE_NAME) { - $ircdata->channel = $lineex[4]; - } - - if ($ircdata->channel !== null) { - if (substr($ircdata->channel, 0, 1) == ':') { - $ircdata->channel = substr($ircdata->channel, 1); - } - } - - $this->log(SMARTIRC_DEBUG_MESSAGEPARSER, 'DEBUG_MESSAGEPARSER: ircdata nick: "'.$ircdata->nick. - '" ident: "'.$ircdata->ident. - '" host: "'.$ircdata->host. - '" type: "'.$ircdata->type. - '" from: "'.$ircdata->from. - '" channel: "'.$ircdata->channel. - '" message: "'.$ircdata->message. - '"', __FILE__, __LINE__); - } - - // lets see if we have a messagehandler for it - $this->_handlemessage($messagecode, $ircdata); - - if ($validmessage == true) { - // now the actionhandlers are comming - $this->_handleactionhandler($ircdata); - } - - if (isset($ircdata)) { - unset($ircdata); - } - } - } - } - - /** - * sends the pong for keeping alive - * - * Sends the PONG signal as reply of the PING from the IRC server. - * - * @param string $data - * @return void - * @access private - */ - function _pong($data) - { - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: Ping? Pong!', __FILE__, __LINE__); - $this->_send('PONG '.$data, SMARTIRC_CRITICAL); - } - - /** - * returns the calculated selecttimeout value - * - * @return integer selecttimeout in microseconds - * @access private - */ - function _selecttimeout() { - if ($this->_messagebuffersize == 0) { - $this->_selecttimeout = null; - - if ($this->_mintimer != false) { - $this->_calculateselecttimeout($this->_mintimer); - } - - if ($this->_autoreconnect == true) { - $this->_calculateselecttimeout($this->_rxtimeout*1000); - } - - $this->_calculateselecttimeout($this->_maxtimer); - return $this->_selecttimeout; - } else { - return $this->_senddelay; - } - } - - /** - * calculates the selecttimeout value - * - * @return void - * @access private - */ - function _calculateselecttimeout($microseconds) - { - if (($this->_selecttimeout > $microseconds) || $this->_selecttimeout === null) { - $this->_selecttimeout = $microseconds; - } - } - - /** - * updates _mintimer to the smallest timer interval - * - * @return void - * @access private - */ - function _updatemintimer() - { - $timerarray = array(); - foreach ($this->_timehandler as $values) { - $timerarray[] = $values->interval; - } - - $result = array_multisort($timerarray, SORT_NUMERIC, SORT_ASC); - if ($result == true && isset($timerarray[0])) { - $this->_mintimer = $timerarray[0]; - } else { - $this->_mintimer = false; - } - } - - /** - * reorders the actionhandler array, needed after removing one - * - * @return void - * @access private - */ - function _reorderactionhandler() - { - $orderedactionhandler = array(); - foreach ($this->_actionhandler as $value) { - $orderedactionhandler[] = $value; - } - $this->_actionhandler = &$orderedactionhandler; - } - - /** - * reorders the timehandler array, needed after removing one - * - * @return void - * @access private - */ - function _reordertimehandler() - { - $orderedtimehandler = array(); - foreach ($this->_timehandler as $value) { - $orderedtimehandler[] = $value; - } - $this->_timehandler = &$orderedtimehandler; - } - - /** - * reorders the modules array, needed after removing one - * - * @return void - * @access private - */ - function _reordermodules() - { - $orderedmodules = array(); - foreach ($this->_modules as $value) { - $orderedmodules[] = $value; - } - $this->_modules = &$orderedmodules; - } - - /** - * determines the messagetype of $line - * - * Analyses the type of an IRC message and returns the type. - * - * @param string $line - * @return integer SMARTIRC_TYPE_* constant - * @access private - */ - function _gettype($line) - { - if (preg_match('/^:[^ ]+? [0-9]{3} .+$/', $line) == 1) { - $lineex = explode(' ', $line); - $code = $lineex[1]; - - switch ($code) { - case SMARTIRC_RPL_WELCOME: - case SMARTIRC_RPL_YOURHOST: - case SMARTIRC_RPL_CREATED: - case SMARTIRC_RPL_MYINFO: - case SMARTIRC_RPL_BOUNCE: - return SMARTIRC_TYPE_LOGIN; - case SMARTIRC_RPL_LUSERCLIENT: - case SMARTIRC_RPL_LUSEROP: - case SMARTIRC_RPL_LUSERUNKNOWN: - case SMARTIRC_RPL_LUSERME: - case SMARTIRC_RPL_LUSERCHANNELS: - return SMARTIRC_TYPE_INFO; - case SMARTIRC_RPL_MOTDSTART: - case SMARTIRC_RPL_MOTD: - case SMARTIRC_RPL_ENDOFMOTD: - return SMARTIRC_TYPE_MOTD; - case SMARTIRC_RPL_NAMREPLY: - case SMARTIRC_RPL_ENDOFNAMES: - return SMARTIRC_TYPE_NAME; - case SMARTIRC_RPL_WHOREPLY: - case SMARTIRC_RPL_ENDOFWHO: - return SMARTIRC_TYPE_WHO; - case SMARTIRC_RPL_LISTSTART: - return SMARTIRC_TYPE_NONRELEVANT; - case SMARTIRC_RPL_LIST: - case SMARTIRC_RPL_LISTEND: - return SMARTIRC_TYPE_LIST; - case SMARTIRC_RPL_BANLIST: - case SMARTIRC_RPL_ENDOFBANLIST: - return SMARTIRC_TYPE_BANLIST; - case SMARTIRC_RPL_TOPIC: - return SMARTIRC_TYPE_TOPIC; - case SMARTIRC_RPL_WHOISUSER: - case SMARTIRC_RPL_WHOISSERVER: - case SMARTIRC_RPL_WHOISOPERATOR: - case SMARTIRC_RPL_WHOISIDLE: - case SMARTIRC_RPL_ENDOFWHOIS: - case SMARTIRC_RPL_WHOISCHANNELS: - return SMARTIRC_TYPE_WHOIS; - case SMARTIRC_RPL_WHOWASUSER: - case SMARTIRC_RPL_ENDOFWHOWAS: - return SMARTIRC_TYPE_WHOWAS; - case SMARTIRC_RPL_UMODEIS: - return SMARTIRC_TYPE_USERMODE; - case SMARTIRC_RPL_CHANNELMODEIS: - return SMARTIRC_TYPE_CHANNELMODE; - case SMARTIRC_ERR_NICKNAMEINUSE: - case SMARTIRC_ERR_NOTREGISTERED: - return SMARTIRC_TYPE_ERROR; - default: - $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: replycode UNKNOWN ('.$code.'): "'.$line.'"', __FILE__, __LINE__); - } - } - - if (preg_match('/^:.*? PRIVMSG .* :'.chr(1).'ACTION .*'.chr(1).'$/', $line) == 1) { - return SMARTIRC_TYPE_ACTION; - } else if (preg_match('/^:.*? PRIVMSG .* :'.chr(1).'.*'.chr(1).'$/', $line) == 1) { - return SMARTIRC_TYPE_CTCP; - } else if (preg_match('/^:.*? PRIVMSG (\&|\#|\+|\!).* :.*$/', $line) == 1) { - return SMARTIRC_TYPE_CHANNEL; - } else if (preg_match('/^:.*? PRIVMSG .*:.*$/', $line) == 1) { - return SMARTIRC_TYPE_QUERY; - } else if (preg_match('/^:.*? NOTICE .* :.*$/', $line) == 1) { - return SMARTIRC_TYPE_NOTICE; - } else if (preg_match('/^:.*? INVITE .* .*$/', $line) == 1) { - return SMARTIRC_TYPE_INVITE; - } else if (preg_match('/^:.*? JOIN .*$/', $line) == 1) { - return SMARTIRC_TYPE_JOIN; - } else if (preg_match('/^:.*? TOPIC .* :.*$/', $line) == 1) { - return SMARTIRC_TYPE_TOPICCHANGE; - } else if (preg_match('/^:.*? NICK .*$/', $line) == 1) { - return SMARTIRC_TYPE_NICKCHANGE; - } else if (preg_match('/^:.*? KICK .* .*$/', $line) == 1) { - return SMARTIRC_TYPE_KICK; - } else if (preg_match('/^:.*? PART .*$/', $line) == 1) { - return SMARTIRC_TYPE_PART; - } else if (preg_match('/^:.*? MODE .* .*$/', $line) == 1) { - return SMARTIRC_TYPE_MODECHANGE; - } else if (preg_match('/^:.*? QUIT :.*$/', $line) == 1) { - return SMARTIRC_TYPE_QUIT; - } else { - $this->log(SMARTIRC_DEBUG_MESSAGETYPES, 'DEBUG_MESSAGETYPES: SMARTIRC_TYPE_UNKNOWN!: "'.$line.'"', __FILE__, __LINE__); - return SMARTIRC_TYPE_UNKNOWN; - } - } - - /** - * updates the current connection state - * - * @return boolean - * @access private - */ - function _updatestate() - { - $rtype = get_resource_type($this->_socket); - if ((is_resource($this->_socket)) && - ($this->_socket !== false) && - ($rtype == 'socket' || $rtype == 'Socket' || $rtype == 'stream')) { - - $this->_state = true; - return true; - } else { - $this->_state = false; - $this->_loggedin = false; - return false; - } - } - - /** - * returns the current connection state - * - * @return integer SMARTIRC_STATE_CONNECTED or SMARTIRC_STATE_DISCONNECTED - * @access private - */ - function _state() - { - $result = $this->_updatestate(); - - if ($result == true) { - return SMARTIRC_STATE_CONNECTED; - } else { - return SMARTIRC_STATE_DISCONNECTED; - } - } - - /** - * tries to find a messagehandler for the received message ($ircdata) and calls it - * - * @param string $messagecode - * @param object $ircdata - * @return void - * @access private - */ - function _handlemessage($messagecode, &$ircdata) - { - $found = false; - - if (is_numeric($messagecode)) { - if (!array_key_exists($messagecode, $this->nreplycodes)) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: ignoring unreconzied messagecode! "'.$messagecode.'"', __FILE__, __LINE__); - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: this IRC server ('.$this->_address.') doesn\'t conform to the RFC 2812!', __FILE__, __LINE__); - return; - } - - $methodname = 'event_'.strtolower($this->nreplycodes[$messagecode]); - $_methodname = '_'.$methodname; - $_codetype = 'by numeric'; - } else if (is_string($messagecode)) { // its not numericcode so already a name/string - $methodname = 'event_'.strtolower($messagecode); - $_methodname = '_'.$methodname; - $_codetype = 'by string'; - } - - // if exists call internal method for the handling - if (@method_exists($this, $_methodname)) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: calling internal method "'.get_class($this).'->'.$_methodname.'" ('.$_codetype.')', __FILE__, __LINE__); - $this->$_methodname($ircdata); - $found = true; - } - - // if exist, call user defined method for the handling - if (@method_exists($this, $methodname)) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: calling user defined method "'.get_class($this).'->'.$methodname.'" ('.$_codetype.')', __FILE__, __LINE__); - $this->$methodname($ircdata); - $found = true; - } - - if ($found == false) { - $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: no method found for "'.$messagecode.'" ('.$methodname.')', __FILE__, __LINE__); - } - } - - /** - * tries to find a actionhandler for the received message ($ircdata) and calls it - * - * @param object $ircdata - * @return void - * @access private - */ - function _handleactionhandler(&$ircdata) - { - $handler = &$this->_actionhandler; - $handlercount = count($handler); - for ($i = 0; $i < $handlercount; $i++) { - $handlerobject = &$handler[$i]; - - if (substr($handlerobject->message, 0, 1) == '/') { - $regex = $handlerobject->message; - } else { - $regex = '/'.$handlerobject->message.'/'; - } - - if (($handlerobject->type & $ircdata->type) && - (preg_match($regex, $ircdata->message) == 1)) { - - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler match found for id: '.$i.' type: '.$ircdata->type.' message: "'.$ircdata->message.'" regex: "'.$regex.'"', __FILE__, __LINE__); - - $methodobject = &$handlerobject->object; - $method = $handlerobject->method; - - if (@method_exists($methodobject, $method)) { - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: calling method "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); - $methodobject->$method($this, $ircdata); - } else { - $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: method doesn\'t exist! "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); - } - - break; - } - } - } - - /** - * getting current microtime, needed for benchmarks - * - * @return float - * @access private - */ - function _microint() - { - $tmp = microtime(); - $parts = explode(' ', $tmp); - $floattime = (float)$parts[0] + (float)$parts[1]; - return $floattime; - } - - /** - * adds an user to the channelobject or updates his info - * - * @param object $channel - * @param object $newuser - * @return void - * @access private - */ - function _adduser(&$channel, &$newuser) - { - $lowerednick = strtolower($newuser->nick); - if (isset($channel->users[$lowerednick])) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: updating user: '.$newuser->nick.' on channel: '.$channel->name, __FILE__, __LINE__); - - // lets update the existing user - $currentuser = &$channel->users[$lowerednick]; - - if ($newuser->ident !== null) { - $currentuser->ident = $newuser->ident; - } - if ($newuser->host !== null) { - $currentuser->host = $newuser->host; - } - if ($newuser->realname !== null) { - $currentuser->realname = $newuser->realname; - } - if ($newuser->op !== null) { - $currentuser->op = $newuser->op; - } - if ($newuser->voice !== null) { - $currentuser->voice = $newuser->voice; - } - if ($newuser->ircop !== null) { - $currentuser->ircop = $newuser->ircop; - } - if ($newuser->away !== null) { - $currentuser->away = $newuser->away; - } - if ($newuser->server !== null) { - $currentuser->server = $newuser->server; - } - if ($newuser->hopcount !== null) { - $currentuser->hopcount = $newuser->hopcount; - } - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding user: '.$newuser->nick.' to channel: '.$channel->name, __FILE__, __LINE__); - - // he is new just add the reference to him - $channel->users[$lowerednick] = &$newuser; - } - - $user = &$channel->users[$lowerednick]; - if ($user->op) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding op: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->ops[$user->nick] = true; - } - if ($user->voice) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding voice: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->voices[$user->nick] = true; - } - } - - /** - * removes an user from one channel or all if he quits - * - * @param object $ircdata - * @return void - * @access private - */ - function _removeuser(&$ircdata) - { - if ($ircdata->type & (SMARTIRC_TYPE_PART|SMARTIRC_TYPE_QUIT)) { - $nick = $ircdata->nick; - } else if ($ircdata->type & SMARTIRC_TYPE_KICK) { - $nick = $ircdata->rawmessageex[3]; - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: unknown TYPE ('.$ircdata->type.') in _removeuser(), trying default', __FILE__, __LINE__); - $nick = $ircdata->nick; - } - - $lowerednick = strtolower($nick); - - if ($this->_nick == $nick) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: we left channel: '.$ircdata->channel.' destroying...', __FILE__, __LINE__); - unset($this->_channels[strtolower($ircdata->channel)]); - } else { - if ($ircdata->type & SMARTIRC_TYPE_QUIT) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: user '.$nick.' quit, removing him from all channels', __FILE__, __LINE__); - // remove the user from all channels - foreach ($this->_channels as $channelkey => $channelvalue) { - // loop through all channels - $channel = &$this->_channels[$channelkey]; - foreach ($channel->users as $userkey => $uservalue) { - // loop through all user in this channel - - if ($nick == $uservalue->nick) { - // found him - // kill him - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: found him on channel: '.$channel->name.' destroying...', __FILE__, __LINE__); - unset($channel->users[$lowerednick]); - - if (isset($channel->ops[$nick])) { - // die! - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from op list', __FILE__, __LINE__); - unset($channel->ops[$nick]); - } - - if (isset($channel->voices[$nick])) { - // die!! - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from voice list', __FILE__, __LINE__); - unset($channel->voices[$nick]); - } - - // ups this was not DukeNukem 3D - } - } - } - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing user: '.$nick.' from channel: '.$ircdata->channel, __FILE__, __LINE__); - $channel = &$this->_channels[strtolower($ircdata->channel)]; - unset($channel->users[$lowerednick]); - - if (isset($channel->ops[$nick])) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from op list', __FILE__, __LINE__); - unset($channel->ops[$nick]); - } - - if (isset($channel->voices[$nick])) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from voice list', __FILE__, __LINE__); - unset($channel->voices[$nick]); - } - } - } - } - - /** - * @return void - * @access private - */ - function _checkPHPVersion() - { - // doing nothing at the moment - } - - /** - * checks if the passed handlertype is valid - * - * @param integer $handlertype - * @return boolean - * @access private - */ - function _isValidType($handlertype) { - if ($handlertype & SMARTIRC_TYPE_ALL ) { - return true; - } else { - return false; - } - } - - // - - function isError($object) { - return (bool)(is_object($object) && (strtolower(get_class($object)) == 'net_smartirc_error')); - } - - function &throwError($message) { - return new Net_SmartIRC_Error($message); - } -} - -class Net_SmartIRC extends Net_SmartIRC_messagehandler -{ - // empty -} - -/** - * @access public - */ -class Net_SmartIRC_data -{ - /** - * @var string - * @access public - */ - var $from; - - /** - * @var string - * @access public - */ - var $nick; - - /** - * @var string - * @access public - */ - var $ident; - - /** - * @var string - * @access public - */ - var $host; - - /** - * @var string - * @access public - */ - var $channel; - - /** - * @var string - * @access public - */ - var $message; - - /** - * @var array - * @access public - */ - var $messageex = array(); - - /** - * @var integer - * @access public - */ - var $type; - - /** - * @var string - * @access public - */ - var $rawmessage; - - /** - * @var array - * @access public - */ - var $rawmessageex = array(); -} - -/** - * @access public - */ -class Net_SmartIRC_actionhandler -{ - /** - * @var integer - * @access public - */ - var $id; - - /** - * @var integer - * @access public - */ - var $type; - - /** - * @var string - * @access public - */ - var $message; - - /** - * @var object - * @access public - */ - var $object; - - /** - * @var string - * @access public - */ - var $method; -} - -/** - * @access public - */ -class Net_SmartIRC_timehandler -{ - /** - * @var integer - * @access public - */ - var $id; - - /** - * @var integer - * @access public - */ - var $interval; - - /** - * @var integer - * @access public - */ - var $lastmicrotimestamp; - - /** - * @var object - * @access public - */ - var $object; - - /** - * @var string - * @access public - */ - var $method; -} - -/** - * @access public - */ -class Net_SmartIRC_channel -{ - /** - * @var string - * @access public - */ - var $name; - - /** - * @var string - * @access public - */ - var $key; - - /** - * @var array - * @access public - */ - var $users = array(); - - /** - * @var array - * @access public - */ - var $ops = array(); - - /** - * @var array - * @access public - */ - var $voices = array(); - - /** - * @var array - * @access public - */ - var $bans = array(); - - /** - * @var string - * @access public - */ - var $topic; - - /** - * @var string - * @access public - */ - var $mode; -} - -/** - * @access public - */ -class Net_SmartIRC_user -{ - /** - * @var string - * @access public - */ - var $nick; - - /** - * @var string - * @access public - */ - var $ident; - - /** - * @var string - * @access public - */ - var $host; - - /** - * @var string - * @access public - */ - var $realname; - - /** - * @var boolean - * @access public - */ - var $ircop; - - /** - * @var boolean - * @access public - */ - var $away; - - /** - * @var string - * @access public - */ - var $server; - - /** - * @var integer - * @access public - */ - var $hopcount; -} - -/** - * @access public - */ -class Net_SmartIRC_channeluser extends Net_SmartIRC_user -{ - /** - * @var boolean - * @access public - */ - var $op; - - /** - * @var boolean - * @access public - */ - var $voice; -} - -/** - * @access public - */ -class Net_SmartIRC_ircuser extends Net_SmartIRC_user -{ - /** - * @var array - * @access public - */ - var $joinedchannels = array(); -} - -/** - * @access public - */ -class Net_SmartIRC_listenfor -{ - /** - * @var array - * @access public - */ - var $result = array(); - - /** - * stores the received answer into the result array - * - * @param object $irc - * @param object $ircdata - * @return void - */ - function handler(&$irc, &$ircdata) - { - $irc->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: listenfor handler called', __FILE__, __LINE__); - $this->result[] = $ircdata->message; - $irc->disconnect(true); - } -} - -// so we don't break BC! -/** - * @access public - */ -class Net_SmartIRC_objListenFor -{ - /** - * @var array - * @access public - */ - var $result = array(); - - /** - * stores the received answer into the result array - * - * @param object $irc - * @param object $ircdata - * @return void - */ - function handler(&$irc, &$ircdata) - { - $irc->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: objListenFor handler called', __FILE__, __LINE__); - $this->result[] = $ircdata; - $irc->disconnect(true); - } -} - -class Net_SmartIRC_Error -{ - var $error_msg; - - function Net_SmartIRC_Error($message) - { - $this->error_msg = $message; - } - - function getMessage() - { - return $this->error_msg; - } -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/SmartIRC/defines.php b/tools/IRC_Bot/SmartIRC/defines.php deleted file mode 100644 index c095b13fc..000000000 --- a/tools/IRC_Bot/SmartIRC/defines.php +++ /dev/null @@ -1,234 +0,0 @@ - - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -// don't change this! unless you know what you do -define('SMARTIRC_CRLF', "\r\n"); -define('SMARTIRC_UNUSED', '*'); -define('SMARTIRC_STDOUT', 0); -define('SMARTIRC_FILE', 1); -define('SMARTIRC_SYSLOG', 2); -define('SMARTIRC_BROWSEROUT', 3); -define('SMARTIRC_NONE', 4); -define('SMARTIRC_LOW', 0); -define('SMARTIRC_MEDIUM', 1); -define('SMARTIRC_HIGH', 2); -define('SMARTIRC_CRITICAL', 3); -define('SMARTIRC_STATE_DISCONNECTED', 0); -define('SMARTIRC_STATE_CONNECTING', 1); -define('SMARTIRC_STATE_CONNECTED', 2); -define('SMARTIRC_DEBUG_NONE', 0); -define('SMARTIRC_DEBUG_NOTICE', 1); -define('SMARTIRC_DEBUG_CONNECTION', 2); -define('SMARTIRC_DEBUG_SOCKET', 4); -define('SMARTIRC_DEBUG_IRCMESSAGES', 8); -define('SMARTIRC_DEBUG_MESSAGETYPES', 16); -define('SMARTIRC_DEBUG_ACTIONHANDLER', 32); -define('SMARTIRC_DEBUG_TIMEHANDLER', 64); -define('SMARTIRC_DEBUG_MESSAGEHANDLER', 128); -define('SMARTIRC_DEBUG_CHANNELSYNCING', 256); -define('SMARTIRC_DEBUG_MODULES', 512); -define('SMARTIRC_DEBUG_USERSYNCING', 1024); -define('SMARTIRC_DEBUG_MESSAGEPARSER', 2048); -define('SMARTIRC_DEBUG_ALL', 4095); -define('SMARTIRC_TYPE_UNKNOWN', 1); -define('SMARTIRC_TYPE_CHANNEL', 2); -define('SMARTIRC_TYPE_QUERY', 4); -define('SMARTIRC_TYPE_CTCP', 8); -define('SMARTIRC_TYPE_NOTICE', 16); -define('SMARTIRC_TYPE_WHO', 32); -define('SMARTIRC_TYPE_JOIN', 64); -define('SMARTIRC_TYPE_INVITE', 128); -define('SMARTIRC_TYPE_ACTION', 256); -define('SMARTIRC_TYPE_TOPICCHANGE', 512); -define('SMARTIRC_TYPE_NICKCHANGE', 1024); -define('SMARTIRC_TYPE_KICK', 2048); -define('SMARTIRC_TYPE_QUIT', 4096); -define('SMARTIRC_TYPE_LOGIN', 8192); -define('SMARTIRC_TYPE_INFO', 16384); -define('SMARTIRC_TYPE_LIST', 32768); -define('SMARTIRC_TYPE_NAME', 65536); -define('SMARTIRC_TYPE_MOTD', 131072); -define('SMARTIRC_TYPE_MODECHANGE', 262144); -define('SMARTIRC_TYPE_PART', 524288); -define('SMARTIRC_TYPE_ERROR', 1048576); -define('SMARTIRC_TYPE_BANLIST', 2097152); -define('SMARTIRC_TYPE_TOPIC', 4194304); -define('SMARTIRC_TYPE_NONRELEVANT', 8388608); -define('SMARTIRC_TYPE_WHOIS', 16777216); -define('SMARTIRC_TYPE_WHOWAS', 33554432); -define('SMARTIRC_TYPE_USERMODE', 67108864); -define('SMARTIRC_TYPE_CHANNELMODE', 134217728); -define('SMARTIRC_TYPE_CTCP_REQUEST', 268435456); -define('SMARTIRC_TYPE_CTCP_REPLY', 536870912); -define('SMARTIRC_TYPE_ALL', 1073741823); - -$SMARTIRC_replycodes = array( -'RPL_WELCOME' => '001', -'RPL_YOURHOST' => '002', -'RPL_CREATED' => '003', -'RPL_MYINFO' => '004', -'RPL_BOUNCE' => '005', -'RPL_TRACELINK' => '200', -'RPL_TRACECONNECTING' => '201', -'RPL_TRACEHANDSHAKE' => '202', -'RPL_TRACEUNKNOWN' => '203', -'RPL_TRACEOPERATOR' => '204', -'RPL_TRACEUSER' => '205', -'RPL_TRACESERVER' => '206', -'RPL_TRACESERVICE' => '207', -'RPL_TRACENEWTYPE' => '208', -'RPL_TRACECLASS' => '209', -'RPL_TRACERECONNECT' => '210', -'RPL_STATSLINKINFO' => '211', -'RPL_STATSCOMMANDS' => '212', -'RPL_ENDOFSTATS' => '219', -'RPL_UMODEIS' => '221', -'RPL_SERVLIST' => '234', -'RPL_SERVLISTEND' => '235', -'RPL_STATSUPTIME' => '242', -'RPL_STATSOLINE' => '243', -'RPL_LUSERCLIENT' => '251', -'RPL_LUSEROP' => '252', -'RPL_LUSERUNKNOWN' => '253', -'RPL_LUSERCHANNELS' => '254', -'RPL_LUSERME' => '255', -'RPL_ADMINME' => '256', -'RPL_ADMINLOC1' => '257', -'RPL_ADMINLOC2' => '258', -'RPL_ADMINEMAIL' => '259', -'RPL_TRACELOG' => '261', -'RPL_TRACEEND' => '262', -'RPL_TRYAGAIN' => '263', -'RPL_AWAY' => '301', -'RPL_USERHOST' => '302', -'RPL_ISON' => '303', -'RPL_UNAWAY' => '305', -'RPL_NOWAWAY' => '306', -'RPL_WHOISUSER' => '311', -'RPL_WHOISSERVER' => '312', -'RPL_WHOISOPERATOR' => '313', -'RPL_WHOWASUSER' => '314', -'RPL_ENDOFWHO' => '315', -'RPL_WHOISIDLE' => '317', -'RPL_ENDOFWHOIS' => '318', -'RPL_WHOISCHANNELS' => '319', -'RPL_LISTSTART' => '321', -'RPL_LIST' => '322', -'RPL_LISTEND' => '323', -'RPL_CHANNELMODEIS' => '324', -'RPL_UNIQOPIS' => '325', -'RPL_NOTOPIC' => '331', -'RPL_TOPIC' => '332', -'RPL_INVITING' => '341', -'RPL_SUMMONING' => '342', -'RPL_INVITELIST' => '346', -'RPL_ENDOFINVITELIST' => '347', -'RPL_EXCEPTLIST' => '348', -'RPL_ENDOFEXCEPTLIST' => '349', -'RPL_VERSION' => '351', -'RPL_WHOREPLY' => '352', -'RPL_NAMREPLY' => '353', -'RPL_LINKS' => '364', -'RPL_ENDOFLINKS' => '365', -'RPL_ENDOFNAMES' => '366', -'RPL_BANLIST' => '367', -'RPL_ENDOFBANLIST' => '368', -'RPL_ENDOFWHOWAS' => '369', -'RPL_INFO' => '371', -'RPL_MOTD' => '372', -'RPL_ENDOFINFO' => '374', -'RPL_MOTDSTART' => '375', -'RPL_ENDOFMOTD' => '376', -'RPL_YOUREOPER' => '381', -'RPL_REHASHING' => '382', -'RPL_YOURESERVICE' => '383', -'RPL_TIME' => '391', -'RPL_USERSSTART' => '392', -'RPL_USERS' => '393', -'RPL_ENDOFUSERS' => '394', -'RPL_NOUSERS' => '395', -'ERR_NOSUCHNICK' => '401', -'ERR_NOSUCHSERVER' => '402', -'ERR_NOSUCHCHANNEL' => '403', -'ERR_CANNOTSENDTOCHAN' => '404', -'ERR_TOOMANYCHANNELS' => '405', -'ERR_WASNOSUCHNICK' => '406', -'ERR_TOOMANYTARGETS' => '407', -'ERR_NOSUCHSERVICE' => '408', -'ERR_NOORIGIN' => '409', -'ERR_NORECIPIENT' => '411', -'ERR_NOTEXTTOSEND' => '412', -'ERR_NOTOPLEVEL' => '413', -'ERR_WILDTOPLEVEL' => '414', -'ERR_BADMASK' => '415', -'ERR_UNKNOWNCOMMAND' => '421', -'ERR_NOMOTD' => '422', -'ERR_NOADMININFO' => '423', -'ERR_FILEERROR' => '424', -'ERR_NONICKNAMEGIVEN' => '431', -'ERR_ERRONEUSNICKNAME' => '432', -'ERR_NICKNAMEINUSE' => '433', -'ERR_NICKCOLLISION' => '436', -'ERR_UNAVAILRESOURCE' => '437', -'ERR_USERNOTINCHANNEL' => '441', -'ERR_NOTONCHANNEL' => '442', -'ERR_USERONCHANNEL' => '443', -'ERR_NOLOGIN' => '444', -'ERR_SUMMONDISABLED' => '445', -'ERR_USERSDISABLED' => '446', -'ERR_NOTREGISTERED' => '451', -'ERR_NEEDMOREPARAMS' => '461', -'ERR_ALREADYREGISTRED' => '462', -'ERR_NOPERMFORHOST' => '463', -'ERR_PASSWDMISMATCH' => '464', -'ERR_YOUREBANNEDCREEP' => '465', -'ERR_YOUWILLBEBANNED' => '466', -'ERR_KEYSET' => '467', -'ERR_CHANNELISFULL' => '471', -'ERR_UNKNOWNMODE' => '472', -'ERR_INVITEONLYCHAN' => '473', -'ERR_BANNEDFROMCHAN' => '474', -'ERR_BADCHANNELKEY' => '475', -'ERR_BADCHANMASK' => '476', -'ERR_NOCHANMODES' => '477', -'ERR_BANLISTFULL' => '478', -'ERR_NOPRIVILEGES' => '481', -'ERR_CHANOPRIVSNEEDED' => '482', -'ERR_CANTKILLSERVER' => '483', -'ERR_RESTRICTED' => '484', -'ERR_UNIQOPPRIVSNEEDED' => '485', -'ERR_NOOPERHOST' => '491', -'ERR_UMODEUNKNOWNFLAG' => '501', -'ERR_USERSDONTMATCH' => '502', -); - -$SMARTIRC_nreplycodes = array(); - -foreach ($SMARTIRC_replycodes as $key => $value) { - define('SMARTIRC_'.$key, $value); - $SMARTIRC_nreplycodes[$value] = $key; -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/SmartIRC/irccommands.php b/tools/IRC_Bot/SmartIRC/irccommands.php deleted file mode 100644 index 3c7b76c13..000000000 --- a/tools/IRC_Bot/SmartIRC/irccommands.php +++ /dev/null @@ -1,433 +0,0 @@ - - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -class Net_SmartIRC_irccommands extends Net_SmartIRC_base -{ - /** - * sends a new message - * - * Sends a message to a channel or user. - * - * @see DOCUMENTATION - * @param integer $type specifies the type, like QUERY/ACTION or CTCP see 'Message Types' - * @param string $destination can be a user or channel - * @param string $message the message - * @return boolean - * @access public - */ - function message($type, $destination, $message, $priority = SMARTIRC_MEDIUM) - { - switch ($type) { - case SMARTIRC_TYPE_CHANNEL: - case SMARTIRC_TYPE_QUERY: - $this->_send('PRIVMSG '.$destination.' :'.$message, $priority); - break; - case SMARTIRC_TYPE_ACTION: - $this->_send('PRIVMSG '.$destination.' :'.chr(1).'ACTION '.$message.chr(1), $priority); - break; - case SMARTIRC_TYPE_NOTICE: - $this->_send('NOTICE '.$destination.' :'.$message, $priority); - break; - case SMARTIRC_TYPE_CTCP: // backwards compatibilty - case SMARTIRC_TYPE_CTCP_REPLY: - $this->_send('NOTICE '.$destination.' :'.chr(1).$message.chr(1), $priority); - break; - case SMARTIRC_TYPE_CTCP_REQUEST: - $this->_send('PRIVMSG '.$destination.' :'.chr(1).$message.chr(1), $priority); - break; - default: - return false; - } - - return true; - } - - /** - * returns an object reference to the specified channel - * - * If the channel does not exist (because not joint) false will be returned. - * - * @param string $channelname - * @return object reference to the channel object - * @access public - */ - function &channel($channelname) - { - if (isset($this->_channels[strtolower($channelname)])) { - return $this->_channels[strtolower($channelname)]; - } else { - return false; - } - } - - // - /** - * Joins one or more IRC channels with an optional key. - * - * @param mixed $channelarray - * @param string $key - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function join($channelarray, $key = null, $priority = SMARTIRC_MEDIUM) - { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - - if ($key !== null) { - $this->_send('JOIN '.$channellist.' '.$key, $priority); - } else { - $this->_send('JOIN '.$channellist, $priority); - } - } - - /** - * parts from one or more IRC channels with an optional reason - * - * @param mixed $channelarray - * @param string $reason - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function part($channelarray, $reason = null, $priority = SMARTIRC_MEDIUM) - { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - - if ($reason !== null) { - $this->_send('PART '.$channellist.' :'.$reason, $priority); - } else { - $this->_send('PART '.$channellist, $priority); - } - } - - /** - * Kicks one or more user from an IRC channel with an optional reason. - * - * @param string $channel - * @param mixed $nicknamearray - * @param string $reason - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function kick($channel, $nicknamearray, $reason = null, $priority = SMARTIRC_MEDIUM) - { - if (!is_array($nicknamearray)) { - $nicknamearray = array($nicknamearray); - } - - $nicknamelist = implode(',', $nicknamearray); - - if ($reason !== null) { - $this->_send('KICK '.$channel.' '.$nicknamelist.' :'.$reason, $priority); - } else { - $this->_send('KICK '.$channel.' '.$nicknamelist, $priority); - } - } - - /** - * gets a list of one ore more channels - * - * Requests a full channellist if $channelarray is not given. - * (use it with care, usualy its a looooong list) - * - * @param mixed $channelarray - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function getList($channelarray = null, $priority = SMARTIRC_MEDIUM) - { - if ($channelarray !== null) { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - $this->_send('LIST '.$channellist, $priority); - } else { - $this->_send('LIST', $priority); - } - } - - /** - * requests all nicknames of one or more channels - * - * The requested nickname list also includes op and voice state - * - * @param mixed $channelarray - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function names($channelarray = null, $priority = SMARTIRC_MEDIUM) - { - if ($channelarray !== null) { - if (!is_array($channelarray)) { - $channelarray = array($channelarray); - } - - $channellist = implode(',', $channelarray); - $this->_send('NAMES '.$channellist, $priority); - } else { - $this->_send('NAMES', $priority); - } - } - - /** - * sets a new topic of a channel - * - * @param string $channel - * @param string $newtopic - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function setTopic($channel, $newtopic, $priority = SMARTIRC_MEDIUM) - { - $this->_send('TOPIC '.$channel.' :'.$newtopic, $priority); - } - - /** - * gets the topic of a channel - * - * @param string $channel - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function getTopic($channel, $priority = SMARTIRC_MEDIUM) - { - $this->_send('TOPIC '.$channel, $priority); - } - - /** - * sets or gets the mode of an user or channel - * - * Changes/requests the mode of the given target. - * - * @param string $target the target, can be an user (only yourself) or a channel - * @param string $newmode the new mode like +mt - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function mode($target, $newmode = null, $priority = SMARTIRC_MEDIUM) - { - if ($newmode !== null) { - $this->_send('MODE '.$target.' '.$newmode, $priority); - } else { - $this->_send('MODE '.$target, $priority); - } - } - - /** - * ops an user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function op($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '+o '.$nickname, $priority); - } - - /** - * deops an user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function deop($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '-o '.$nickname, $priority); - } - - /** - * voice a user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function voice($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '+v '.$nickname, $priority); - } - - /** - * devoice a user in the given channel - * - * @param string $channel - * @param string $nickname - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function devoice($channel, $nickname, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '-v '.$nickname, $priority); - } - - /** - * bans a hostmask for the given channel or requests the current banlist - * - * The banlist will be requested if no hostmask is specified - * - * @param string $channel - * @param string $hostmask - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function ban($channel, $hostmask = null, $priority = SMARTIRC_MEDIUM) - { - if ($hostmask !== null) { - $this->mode($channel, '+b '.$hostmask, $priority); - } else { - $this->mode($channel, 'b', $priority); - } - } - - /** - * unbans a hostmask on the given channel - * - * @param string $channel - * @param string $hostmask - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function unban($channel, $hostmask, $priority = SMARTIRC_MEDIUM) - { - $this->mode($channel, '-b '.$hostmask, $priority); - } - - /** - * invites a user to the specified channel - * - * @param string $nickname - * @param string $channel - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function invite($nickname, $channel, $priority = SMARTIRC_MEDIUM) - { - $this->_send('INVITE '.$nickname.' '.$channel, $priority); - } - - /** - * changes the own nickname - * - * Trys to set a new nickname, nickcollisions are handled. - * - * @param string $newnick - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function changeNick($newnick, $priority = SMARTIRC_MEDIUM) - { - $this->_send('NICK '.$newnick, $priority); - $this->_nick = $newnick; - } - - /** - * requests a 'WHO' from the specified target - * - * @param string $target - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function who($target, $priority = SMARTIRC_MEDIUM) - { - $this->_send('WHO '.$target, $priority); - } - - /** - * requests a 'WHOIS' from the specified target - * - * @param string $target - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function whois($target, $priority = SMARTIRC_MEDIUM) - { - $this->_send('WHOIS '.$target, $priority); - } - - /** - * requests a 'WHOWAS' from the specified target - * (if he left the IRC network) - * - * @param string $target - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function whowas($target, $priority = SMARTIRC_MEDIUM) - { - $this->_send('WHOWAS '.$target, $priority); - } - - /** - * sends QUIT to IRC server and disconnects - * - * @param string $quitmessage optional quitmessage - * @param integer $priority message priority, default is SMARTIRC_MEDIUM - * @return void - * @access public - */ - function quit($quitmessage = null, $priority = SMARTIRC_MEDIUM) - { - if ($quitmessage !== null) { - $this->_send('QUIT :'.$quitmessage, $priority); - } else { - $this->_send('QUIT', $priority); - } - } -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/SmartIRC/messagehandler.php b/tools/IRC_Bot/SmartIRC/messagehandler.php deleted file mode 100644 index 54c46169e..000000000 --- a/tools/IRC_Bot/SmartIRC/messagehandler.php +++ /dev/null @@ -1,411 +0,0 @@ - - * - * Full LGPL License: - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -class Net_SmartIRC_messagehandler extends Net_SmartIRC_irccommands -{ - /* misc */ - function _event_ping(&$ircdata) - { - $this->_pong(substr($ircdata->rawmessage, 5)); - } - - function _event_error(&$ircdata) - { - if ($this->_autoretry == true) { - $this->reconnect(); - } else { - $this->disconnect(true); - } - } - - function _event_join(&$ircdata) - { - if ($this->_channelsyncing == true) { - if ($this->_nick == $ircdata->nick) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: joining channel: '.$ircdata->channel, __FILE__, __LINE__); - $channel = &new Net_SmartIRC_channel(); - $channel->name = $ircdata->channel; - $this->_channels[strtolower($channel->name)] = &$channel; - - $this->who($channel->name); - $this->mode($channel->name); - $this->ban($channel->name); - } - - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: '.$ircdata->nick.' joins channel: '.$ircdata->channel, __FILE__, __LINE__); - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $user = &new Net_SmartIRC_channeluser(); - $user->nick = $ircdata->nick; - $user->ident = $ircdata->ident; - $user->host = $ircdata->host; - - $this->_adduser($channel, $user); - $this->who($user->nick); - } - } - - function _event_part(&$ircdata) - { - if ($this->_channelsyncing == true) { - $this->_removeuser($ircdata); - } - } - - function _event_kick(&$ircdata) - { - if ($this->_channelsyncing == true) { - $this->_removeuser($ircdata); - } - } - - function _event_quit(&$ircdata) - { - if ($this->_channelsyncing == true) { - $this->_removeuser($ircdata); - } - } - - function _event_nick(&$ircdata) - { - if ($this->_channelsyncing == true) { - $newnick = substr($ircdata->rawmessageex[2], 1); - $lowerednewnick = strtolower($newnick); - $lowerednick = strtolower($ircdata->nick); - - foreach ($this->_channels as $channelkey => $channelvalue) { - // loop through all channels - $channel = &$this->_channels[$channelkey]; - foreach ($channel->users as $userkey => $uservalue) { - // loop through all user in this channel - - if ($ircdata->nick == $uservalue->nick) { - // found him - // time for updating the object and his nickname - $channel->users[$lowerednewnick] = $channel->users[$lowerednick]; - $channel->users[$lowerednewnick]->nick = $newnick; - - if ($lowerednewnick != $lowerednick) { - unset($channel->users[$lowerednick]); - } - - // he was maybe op or voice, update comming - if (isset($channel->ops[$ircdata->nick])) { - $channel->ops[$newnick] = $channel->ops[$ircdata->nick]; - unset($channel->ops[$ircdata->nick]); - } - if (isset($channel->voices[$ircdata->nick])) { - $channel->voices[$newnick] = $channel->voices[$ircdata->nick]; - unset($channel->voices[$ircdata->nick]); - } - - break; - } - } - } - } - } - - function _event_mode(&$ircdata) - { - // check if its own usermode - if ($ircdata->rawmessageex[2] == $this->_nick) { - $this->_usermode = substr($ircdata->rawmessageex[3], 1); - } else if ($this->_channelsyncing == true) { - // it's not, and we do channel syching - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: updating channel mode for: '.$channel->name, __FILE__, __LINE__); - $mode = $ircdata->rawmessageex[3]; - $parameters = array_slice($ircdata->rawmessageex, 4); - - $add = false; - $remove = false; - $channelmode = ''; - $modelength = strlen($mode); - for ($i = 0; $i < $modelength; $i++) { - switch($mode[$i]) { - case '-': - $remove = true; - $add = false; - break; - case '+': - $add = true; - $remove = false; - break; - // user modes - case 'o': - $nick = array_shift($parameters); - $lowerednick = strtolower($nick); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->ops[$nick] = true; - $channel->users[$lowerednick]->op = true; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - unset($channel->ops[$nick]); - $channel->users[$lowerednick]->op = false; - } - break; - case 'v': - $nick = array_shift($parameters); - $lowerednick = strtolower($nick); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding voice: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - $channel->voices[$nick] = true; - $channel->users[$lowerednick]->voice = true; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing voice: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); - unset($channel->voices[$nick]); - $channel->users[$lowerednick]->voice = false; - } - break; - case 'k': - $key = array_shift($parameters); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: stored channel key for: '.$channel->name, __FILE__, __LINE__); - $channel->key = $key; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removed channel key for: '.$channel->name, __FILE__, __LINE__); - $channel->key = ''; - } - break; - default: - // channel modes - if ($mode[$i] == 'b') { - $hostmask = array_shift($parameters); - if ($add) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding ban: '.$hostmask.' for: '.$channel->name, __FILE__, __LINE__); - $channel->bans[$hostmask] = true; - } - if ($remove) { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing ban: '.$hostmask.' for: '.$channel->name, __FILE__, __LINE__); - unset($channel->bans[$hostmask]); - } - } else { - $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: storing unknown channelmode ('.$mode.') in channel->mode for: '.$channel->name, __FILE__, __LINE__); - if ($add) { - $channel->mode .= $mode[$i]; - } - if ($remove) { - $channel->mode = str_replace($mode[$i], '', $channel->mode); - } - } - } - } - } - } - - function _event_topic(&$ircdata) - { - if ($this->_channelsyncing == true) { - $channel = &$this->_channels[strtolower($ircdata->rawmessageex[2])]; - $channel->topic = $ircdata->message; - } - } - - function _event_privmsg(&$ircdata) - { - if ($ircdata->type == SMARTIRC_TYPE_CTCP) { - // substr must be 1,4 because of \001 in CTCP messages - if (substr($ircdata->message, 1, 4) == 'PING') { - $this->message(SMARTIRC_TYPE_CTCP, $ircdata->nick, 'PING '.substr($ircdata->message, 5, -1)); - } elseif (substr($ircdata->message, 1, 7) == 'VERSION') { - if (!empty($this->_ctcpversion)) { - $versionstring = $this->_ctcpversion.' | using '.SMARTIRC_VERSIONSTRING; - } else { - $versionstring = SMARTIRC_VERSIONSTRING; - } - - $this->message(SMARTIRC_TYPE_CTCP, $ircdata->nick, 'VERSION '.$versionstring); - } - } - } - - /* rpl_ */ - function _event_rpl_welcome(&$ircdata) - { - $this->_loggedin = true; - $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: logged in', __FILE__, __LINE__); - - // updating our nickname, that we got (maybe cutted...) - $this->_nick = $ircdata->rawmessageex[2]; - } - - function _event_rpl_motdstart(&$ircdata) - { - $this->_motd[] = $ircdata->message; - } - - function _event_rpl_motd(&$ircdata) - { - $this->_motd[] = $ircdata->message; - } - - function _event_rpl_endofmotd(&$ircdata) - { - $this->_motd[] = $ircdata->message; - } - - function _event_rpl_umodeis(&$ircdata) - { - $this->_usermode = $ircdata->message; - } - - function _event_rpl_channelmodeis(&$ircdata) { - if ($this->_channelsyncing == true && $this->isJoined($ircdata->channel)) { - $mode = $ircdata->rawmessageex[4]; - $parameters = array_slice($ircdata->rawmessageex, 5); - - $ircdata->rawmessageex = array( 0 => '', - 1 => '', - 2 => '', - 3 => $mode); - - foreach ($parameters as $value) { - $ircdata->rawmessageex[] = $value; - } - - // let _mode() handle the received mode - $this->_event_mode($ircdata); - } - } - - function _event_rpl_whoreply(&$ircdata) - { - if ($this->_channelsyncing == true) { - $nick = $ircdata->rawmessageex[7]; - if ($ircdata->channel == '*') { - // we got who info without channel info, so we need to search the user - // on all channels and update him - foreach ($this->_channels as $channel) { - if ($this->isJoined($channel->name, $nick)) { - $ircdata->channel = $channel->name; - $this->_event_rpl_whoreply($ircdata); - } - } - } else { - if (!$this->isJoined($ircdata->channel, $nick)) { - return; - } - - $channel = &$this->_channels[strtolower($ircdata->channel)]; - - $user = &new Net_SmartIRC_channeluser(); - $user->ident = $ircdata->rawmessageex[4]; - $user->host = $ircdata->rawmessageex[5]; - $user->server = $ircdata->rawmessageex[6]; - $user->nick = $ircdata->rawmessageex[7]; - - $user->op = false; - $user->voice = false; - $user->ircop = false; - - $usermode = $ircdata->rawmessageex[8]; - $usermodelength = strlen($usermode); - for ($i = 0; $i < $usermodelength; $i++) { - switch ($usermode[$i]) { - case 'H': - $user->away = false; - break; - case 'G': - $user->away = true; - break; - case '@': - $user->op = true; - break; - case '+': - $user->voice = true; - break; - case '*': - $user->ircop = true; - break; - } - } - - $user->hopcount = substr($ircdata->rawmessageex[9], 1); - $user->realname = implode(array_slice($ircdata->rawmessageex, 10), ' '); - - $this->_adduser($channel, $user); - } - } - } - - function _event_rpl_namreply(&$ircdata) - { - if ($this->_channelsyncing == true) { - $channel = &$this->_channels[strtolower($ircdata->channel)]; - - $userarray = explode(' ', rtrim($ircdata->message)); - $userarraycount = count($userarray); - for ($i = 0; $i < $userarraycount; $i++) { - $user = &new Net_SmartIRC_channeluser(); - - $usermode = substr($userarray[$i], 0, 1); - switch ($usermode) { - case '@': - $user->op = true; - $user->nick = substr($userarray[$i], 1); - break; - case '+': - $user->voice = true; - $user->nick = substr($userarray[$i], 1); - break; - default: - $user->nick = $userarray[$i]; - } - - $this->_adduser($channel, $user); - } - } - } - - function _event_rpl_banlist(&$ircdata) - { - if ($this->_channelsyncing == true && $this->isJoined($ircdata->channel)) { - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $hostmask = $ircdata->rawmessageex[4]; - $channel->bans[$hostmask] = true; - } - } - - function _event_rpl_topic(&$ircdata) - { - if ($this->_channelsyncing == true) { - $channel = &$this->_channels[strtolower($ircdata->channel)]; - $topic = substr(implode(array_slice($ircdata->rawmessageex, 4), ' '), 1); - $channel->topic = $topic; - } - } - - /* err_ */ - function _event_err_nicknameinuse(&$ircdata) - { - $this->_nicknameinuse(); - } -} -?> \ No newline at end of file diff --git a/tools/IRC_Bot/magpierss/AUTHORS b/tools/IRC_Bot/magpierss/AUTHORS deleted file mode 100644 index 7d7f3f53e..000000000 --- a/tools/IRC_Bot/magpierss/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -kellan diff --git a/tools/IRC_Bot/magpierss/CHANGES b/tools/IRC_Bot/magpierss/CHANGES deleted file mode 100644 index b186af5c9..000000000 --- a/tools/IRC_Bot/magpierss/CHANGES +++ /dev/null @@ -1,37 +0,0 @@ -Version 0.7 ------------ - - support for input and output charset encoding - based on the work in FoF, uses iconv or mbstring if available - - - -Version 0.6 ------------ - - basic support for Atom syndication format - including support for Atom content constructs - - fixed support for private feeds (HTTP Auth and SSL) - (thanks to silverorange.com for providing test feeds) - - support for some broken webservers - -Version 0.52 ------------ - - support GZIP content negoiation - - PHP 4.3.2 support - -Version 0.4 ------------ - - improved error handling, better access for script authors - - included example scripts of working with MagpieRSS - - new Smarty plugin for RSS date parsing - -Version 0.3 ------------ - - added support for conditional gets (Last-Modified, ETag) - - now use Snoopy to handle fetching RSS files - -Version 0.2 ------------ - - MAJOR CLEAN UP - - removed kludgy $options array in favour of constants - - phased out returning arrays - - added better error handling - - re-worked comments diff --git a/tools/IRC_Bot/magpierss/ChangeLog b/tools/IRC_Bot/magpierss/ChangeLog deleted file mode 100644 index d52a58782..000000000 --- a/tools/IRC_Bot/magpierss/ChangeLog +++ /dev/null @@ -1,346 +0,0 @@ -2004-11-21 22:45 kellan - - * rss_fetch.inc: detab, bump version - -2004-11-21 20:52 kellan - - * rss_fetch.inc, rss_parse.inc: cache on $url . $output_encoding - otherwise we can get munged output - * rss_parse.inc: don't set ERROR on notice or warning (rss_fetch - dies on parse errors) - * rss_fetch.inc: add encoding defines (fix timeout error reporting) - -2004-11-21 17:21 kellan - - * rss_parse.inc: incorporate steve's patch - -2004-11-21 16:26 kellan - - * rss_parse.inc: remove old debugging functions, totally - arbitrarily. might break stuff. can't really explain why i'm - doing this. - -2004-10-28 12:52 kellan - - * rss_parse.inc: fixed '=' instead of '==' - -2004-10-25 21:48 kellan - - * rss_parse.inc: chance epoch to timestamp to conform w/ php naming - conventions - -2004-06-15 09:00 kellan - - * rss_parse.inc: [no log message] - -2004-04-26 11:16 kellan - - * rss_fetch.inc: bump version - -2004-04-26 09:36 kellan - - * rss_parse.inc: fix field doubling - -2004-04-24 14:47 kellan - - * CHANGES, ChangeLog: updated - -2004-04-24 14:35 kellan - - * rss_fetch.inc: bumped version - -2004-04-24 13:52 kellan - - * rss_parse.inc: support arbitrary atom content constructs - - some refactoring - -2004-04-24 13:15 kellan - - * rss_parse.inc: support summary content contstruct. add normalize - function - -2004-03-27 13:29 kellan - - * extlib/Snoopy.class.inc: accept self-signed certs - -2004-03-27 09:53 kellan - - * extlib/Snoopy.class.inc: fixed SSL support * set status * set - error on bad curl - - (also ripped out big chunks of dead weight (submit_form) which - were getting in my way - -2004-01-24 23:25 kellan - - * rss_parse.inc: make RSS 1.0's rdf:about available - -2004-01-24 23:07 kellan - - * rss_parse.inc: clean up text, and line formats. add support item - rdf:about - -2004-01-24 20:40 kellan - - * CHANGES, ChangeLog: update changes - -2004-01-24 20:37 kellan - - * rss_fetch.inc: updated version - -2004-01-24 20:35 kellan - - * rss_parse.inc: whitespace - -2004-01-24 20:23 kellan - - * extlib/Snoopy.class.inc: support badly formatted http headers - -2004-01-24 20:20 kellan - - * rss_parse.inc: added alpha atom parsing support - -2003-06-25 19:34 kellan - - * extlib/Snoopy.class.inc: fixed fread 4.3.2 compatibility problems - -2003-06-13 08:31 kellan - - * rss_fetch.inc: reset cache on 304 - -2003-06-12 18:37 kellan - - * rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc: - bumped up version numbers - -2003-06-12 18:32 kellan - - * htdocs/index.html: updated news - -2003-06-12 18:27 kellan - - * NEWS: a manual blog :) - -2003-06-12 18:22 kellan - - * htdocs/index.html: fully qualified img - -2003-06-12 18:20 kellan - - * htdocs/index.html: clean up. added badge. - -2003-06-12 18:04 kellan - - * rss_utils.inc: clean up regex - -2003-06-12 18:02 kellan - - * rss_cache.inc: suppress some warnings - -2003-05-30 17:44 kellan - - * extlib/Snoopy.class.inc: more comments, cleaned up notice - -2003-05-30 12:14 kellan - - * extlib/Snoopy.class.inc: don't advertise gzip support if the user - hasn't built php with gzinflate support - -2003-05-12 19:32 kellan - - * ChangeLog: changes - -2003-05-12 19:11 kellan - - * htdocs/index.html: announce 0.5 - -2003-05-12 18:42 kellan - - * htdocs/index.html: change - -2003-05-12 18:39 kellan - - * rss_fetch.inc: use gzip - -2003-05-12 18:37 kellan - - * extlib/Snoopy.class.inc: added support gzip encoded content - negoiation - -2003-05-12 18:32 kellan - - * rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc: fixed - typoes - -2003-04-26 18:44 kellan - - * rss_parse.inc: fix minor typo - -2003-04-18 05:19 kellan - - * htdocs/cookbook.html: updated cookbook to show more code for - limiting items - -2003-03-03 13:02 kellan - - * rss_parse.inc, scripts/magpie_slashbox.php: committed (or - adpated) patch from Nicola (www.technick.com) to quell 'Undefined - Indexes' notices - -2003-03-03 12:59 kellan - - * rss_fetch.inc: commited patch from nicola (www.technick.com) to - quell 'undefined indexes' notices. - - * Magpie now automatically includes its version in the - user-agent, & whether cacheing is turned on. - -2003-02-11 22:22 kellan - - * CHANGES, ChangeLog: ChangeLog now auto-generated by cvs2cl - -2003-02-11 21:21 kellan - - * rss_fetch.inc: better errors, hopefully stomped on pesky notices - -2003-02-11 21:19 kellan - - * rss_parse.inc: check to see is xml is supported, if not die - - also throw better xml errors - -2003-02-11 21:18 kellan - - * rss_cache.inc: hopefully cleared up some notices that were being - thrown into the log - - fixed a debug statement that was being called as an error - -2003-02-11 21:15 kellan - - * scripts/: magpie_simple.php, magpie_slashbox.php: moved - magpie_simple to magpie_slashbox, and replaced it with a simpler - demo. - -2003-02-11 21:02 kellan - - * INSTALL, README, TROUBLESHOOTING: Improved documentation. Better - install instructions. - - TROUBLESHOOTING cover common installation and usage problems - -2003-01-22 11:40 kellan - - * htdocs/cookbook.html: added cookbook.html - -2003-01-21 20:47 kellan - - * cookbook: a magpie cookbook - -2003-01-20 07:09 kellan - - * ChangeLog: updated - -2003-01-20 06:23 kellan - - * scripts/simple_smarty.php: minor clean up - -2003-01-20 06:15 kellan - - * scripts/README: added smarty url - -2003-01-20 06:14 kellan - - * magpie_simple.php, htdocs/index.html, scripts/README, - scripts/magpie_debug.php, scripts/magpie_simple.php, - scripts/simple_smarty.php, - scripts/smarty_plugin/modifier.rss_date_parse.php, - scripts/templates/simple.smarty: Added scripts directory for - examples on how to use MagpieRSS - - magpie_simple - is a simple example magpie_debug - spew all the - information from a parsed RSS feed simple_smary - example of - using magpie with Smarty template system - smarty_plugin/modifier.rss_date_parse.php - support file for the - smarty demo templates/simple.smary - template for the smarty demo - -2003-01-20 06:11 kellan - - * rss_fetch.inc, rss_parse.inc: changes to error handling to give - script authors more access to magpie's errors. - - added method magpie_error() to retrieve global MAGPIE_ERROR - variable for when fetch_rss() returns false - -2002-10-26 16:02 kellan - - * htdocs/index.html: putting the website under source control - -2002-10-26 15:43 kellan - - * AUTHORS, ChangeLog, INSTALL, README: some documentation to make - it all look official :) - -2002-10-25 20:04 kellan - - * magpie_simple.php: quxx - -2002-10-25 20:04 kellan - - * rss_parse.inc: added support for textinput and image - -2002-10-25 16:23 kellan - - * magpie_simple.php, rss_cache.inc, rss_fetch.inc, rss_parse.inc, - rss_utils.inc: switched to using Snoopy for fetching remote RSS - files. - - added support for conditional gets - -2002-10-25 16:22 kellan - - * rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc: - Change comment style to slavishly imitate the phpinsider style - found in Smarty and Snoopy :) - -2002-10-25 16:18 kellan - - * extlib/Snoopy.class.inc: added Snoopy in order to support - conditional gets - -2002-10-23 20:19 kellan - - * magpie_simple.php, rss_cache.inc, rss_fetch.inc, rss_parse.inc: - MAJOR CLEANUP! - - * rss_fetch got rid of the options array, replaced it with a more - PHP-like solution of using defines. constants are setup, with - defaults, in the function init() - - got rid of the idiom of passing back an array, its was awkward to - deal with in PHP, and unusual (and consquently confusing to - people). now i return true/false values, and try to setup error - string where appropiate (rss_cache has the most complete example - of this) - - change the logic for interacting with the cache - - * rss_cache major re-working of how error are handled. tried to - make the code more resillient. the cache is now much more aware - of MAX_AGE, where before this was being driven out of rss_fetch - (which was silly) - - * rss_parse properly handles xml parse errors. used to sail - along blithely unaware. - -2002-09-11 08:11 kellan - - * rss_cache.inc, rss_parse.inc, magpie_simple.php, rss_fetch.inc, - rss_utils.inc: Initial revision - -2002-09-11 08:11 kellan - - * rss_cache.inc, rss_parse.inc, magpie_simple.php, rss_fetch.inc, - rss_utils.inc: initial import - diff --git a/tools/IRC_Bot/magpierss/INSTALL b/tools/IRC_Bot/magpierss/INSTALL deleted file mode 100644 index 640833d50..000000000 --- a/tools/IRC_Bot/magpierss/INSTALL +++ /dev/null @@ -1,143 +0,0 @@ -REQUIREMENTS - - MapieRSS requires a recent PHP 4+ (developed with 4.2.0) - with xml (expat) support. - - Optionally: - * PHP5 with libxml2 support. - * cURL for SSL support - * iconv (preferred) or mb_string for expanded character set support - -QUICK START - - Magpie consists of 4 files (rss_fetch.inc, rss_parser.inc, rss_cache.inc, - and rss_utils.inc), and the directory extlib (which contains a modified - version of the Snoopy HTTP client) - - Copy these 5 resources to a directory named 'magpierss' in the same - directory as your PHP script. - - At the top of your script add the following line: - - require_once('magpierss/rss_fetch.inc'); - - Now you can use the fetch_rss() method: - - $rss = fetch_rss($url); - - Done. That's it. See README for more details on using MagpieRSS. - -NEXT STEPS - - Important: you'll probably want to get the cache directory working in - order to speed up your application, and not abuse the webserver you're - downloading the RSS from. - - Optionally you can install MagpieRSS in your PHP include path in order to - make it available server wide. - - Lastly you might want to look through the constants in rss_fetch.inc see if - there is anything you want to override (the defaults are pretty good) - - For more info, or if you have trouble, see TROUBLESHOOTING - -SETTING UP CACHING - - Magpie has built-in transparent caching. With caching Magpie will only - fetch and parse RSS feeds when there is new content. Without this feature - your pages will be slow, and the sites serving the RSS feed will be annoyed - with you. - -** Simple and Automatic ** - - By default Magpie will try to create a cache directory named 'cache' in the - same directory as your PHP script. - -** Creating a Local Cache Directory ** - - Often this will fail, because your webserver doesn't have sufficient - permissions to create the directory. - - Exact instructions for how to do this will vary from install to install and - platform to platform. The steps are: - - 1. Make a directory named 'cache' - 2. Give the web server write access to that directory. - - An example of how to do this on Debian would be: - - 1. mkdir /path/to/script/cache - 2. chgrp www-data /path/to/script/cache - 3. chmod 775 /path/to/script/cache - - On other Unixes you'll need to change 'www-data' to what ever user Apache - runs as. (on MacOS X the user would be 'www') - -** Cache in /tmp ** - - Sometimes you won't be able to create a local cache directory. Some reasons - might be: - - 1. No shell account - 2. Insufficient permissions to change ownership of a directory - 3. Webserver runs as 'nobody' - - In these situations using a cache directory in /tmp can often be a good - option. - - The drawback is /tmp is public, so anyone on the box can read the cache - files. Usually RSS feeds are public information, so you'll have to decide - how much of an issue that is. - - To use /tmp as your cache directory you need to add the following line to - your script: - - define('MAGPIE_CACHE_DIR', '/tmp/magpie_cache'); - -** Global Cache ** - - If you have several applications using Magpie, you can create a single - shared cache directory, either using the /tmp cache, or somewhere else on - the system. - - The upside is that you'll distribute fetching and parsing feeds across - several applications. - -INSTALLING MAGPIE SERVER WIDE - - Rather then following the Quickstart instructions which requires you to have - a copy of Magpie per application, alternately you can place it in some - shared location. - -** Adding Magpie to Your Include Path ** - - Copy the 5 resources (rss_fetch.inc, rss_parser.inc, rss_cache.inc, - rss_utils.inc, and extlib) to a directory named 'magpierss' in your include - path. Now any PHP file on your system can use Magpie with: - - require_once('magpierss/rss_fetch.inc'); - - Different installs have different include paths, and you'll have to figure - out what your include_path is. - - From shell you can try: - - php -i | grep 'include_path' - - Alternatley you can create a phpinfo.php file with contains: - - - - Debian's default is: - - /usr/share/php - - (though more idealogically pure location would be /usr/local/share/php) - - Apple's default include path is: - - /usr/lib/php - - While the Entropy PHP build seems to use: - - /usr/local/php/lib/php \ No newline at end of file diff --git a/tools/IRC_Bot/magpierss/NEWS b/tools/IRC_Bot/magpierss/NEWS deleted file mode 100644 index 5ac6b9788..000000000 --- a/tools/IRC_Bot/magpierss/NEWS +++ /dev/null @@ -1,53 +0,0 @@ -MagpieRSS News - -MAGPIERSS 0.51 RELEASED - * important bugfix! - * fix "silent failure" when PHP doesn't have zlib - -FEED ON FEEDS USES MAGPIE - * web-based RSS aggregator built with Magpie - * easy to install, easy to use. - http://minutillo.com/steve/feedonfeeds/ - -MAGPIERSS 0.5 RELEASED - * supports transparent HTTP gzip content negotiation for reduced bandwidth usage - * quashed some undefined index notices - -MAGPIERSS 0.46 RELEASED - * minor release, more error handling clean up - * documentation fixes, simpler example - * new trouble shooting guide for installation and usage problems - http://magpierss.sourceforge.net/TROUBLESHOOTING - -MAGPIE NEWS AS RSS - * releases, bug fixes, releated stories in RSS - -MAGPIERSS COOKBOOK: SIMPLE PHP RSS HOW TOS - * answers some of the most frequently asked Magpie questions - * feedback, suggestions, requests, recipes welcome - http://magpierss.sourceforge.net/cookbook.html - -MAGPIERSS 0.4 RELEASED! - * improved error handling, more flexibility for script authors, backwards compatible - * new and better examples! including using MagpieRSS and Smarty - * new Smarty plugin for RSS date parsing - http://smarty.php.net - -INFINITE PENGUIN NOW SUPPORTS MAGPIE 0.3 - * simple, sophisticated RSS viewer - * includes auto-generated javascript ticker from RSS feed - http://www.infinitepenguins.net/rss/ - -TRAUMWIND RELEASES REX BACKEND FOR MAGPIERSS - * drop in support using regex based XML parser - * parses improperly formed XML that chokes expat - http://traumwind.de/blog/magpie/magpie_alike.php - -MAGPIERSS 0.3 RELEASED! - * Support added for HTTP Conditional GETs. - http://fishbowl.pastiche.org/archives/001132.html - -MAGPIERSS 0.2! - * Major clean up of the code. Easier to use. - * Simpler install on shared hosts. - * Better documentation and comments. diff --git a/tools/IRC_Bot/magpierss/README b/tools/IRC_Bot/magpierss/README deleted file mode 100644 index 6af7edb07..000000000 --- a/tools/IRC_Bot/magpierss/README +++ /dev/null @@ -1,48 +0,0 @@ -NAME - - MagpieRSS - a simple RSS integration tool - -SYNOPSIS - - require_once(rss_fetch.inc); - $url = $_GET['url']; - $rss = fetch_rss( $url ); - - echo "Channel Title: " . $rss->channel['title'] . "

"; - echo "

    "; - foreach ($rss->items as $item) { - $href = $item['link']; - $title = $item['title']; - echo "
  • $title
  • "; - } - echo "
"; - -DESCRIPTION - - MapieRSS is an XML-based RSS parser in PHP. It attempts to be "PHP-like", - and simple to use. - - Some features include: - - * supports RSS 0.9 - 1.0, with limited RSS 2.0 support - * supports namespaces, and modules, including mod_content and mod_event - * open minded [1] - * simple, functional interface, to object oriented backend parser - * automatic caching of parsed RSS objects makes its easy to integrate - * supports conditional GET with Last-Modified, and ETag - * uses constants for easy override of default behaviour - * heavily commented - - -1. By open minded I mean Magpie will accept any tag it finds in good faith that - it was supposed to be here. For strict validation, look elsewhere. - - -GETTING STARTED - - - -COPYRIGHT: - Copyright(c) 2002 kellan@protest.net. All rights reserved. - This software is released under the GNU General Public License. - Please read the disclaimer at the top of the Snoopy.class.inc file. diff --git a/tools/IRC_Bot/magpierss/TROUBLESHOOTING b/tools/IRC_Bot/magpierss/TROUBLESHOOTING deleted file mode 100644 index 89068d382..000000000 --- a/tools/IRC_Bot/magpierss/TROUBLESHOOTING +++ /dev/null @@ -1,152 +0,0 @@ -TROUBLESHOOTING - - -Trouble Installing MagpieRSS: - -1. Fatal error: Failed opening required '/path/to/script/rss_fetch.inc' - (include_path='.:/usr/local/lib/php:/usr/local/lib/php/pear') - -2. Cache couldn't make dir './cache'. - -3. Fatal error: Failed to load PHP's XML Extension. - http://www.php.net/manual/en/ref.xml.php - -Trouble Using MagpieRSS - -4. Warning: MagpieRSS: Failed to fetch example.com/index.rdf. - (HTTP Error: Invalid protocol "") - -5. Warning: MagpieRSS: Failed to parse RSS file. - (not well-formed (invalid token) at line 19, column 98) - -6. Warning: MagpieRSS: Failed to fetch http://localhost/rss/features.1-0.rss. - (HTTP Response: HTTP/1.1 404 Not Found) - -If you would rather provide a custom error, see the COOKBOOK -(http://magpierss.sf.net/cookbook.html) recipe 2. - -************************************************************************* -1. Fatal error: Failed opening required '/path/to/script/rss_fetch.inc' - (include_path='.:/usr/local/lib/php:/usr/local/lib/php/pear') - - This could mean that: - - a) PHP can't find the MagpieRSS files. - b) PHP found them the MagpieRSS files, but can't read them. - - a. Telling PHP where to look for MagpieRSS file. - - This might mean your PHP program can't find the MagpieRSS libraries. - Magpie relies on 4 include files, rss_fetch.inc, rss_parse.inc, - rss_cache.inc, rss_util.inc, and for normal use you'll need all 4 (see the - cookbook for exceptions). - - This can be fixed by making sure the MagpieRSS files are in your include - path. - - If you can edit your include path (for example your on a shared host) then - you need to replace: - - require_once('rss_fetch.inc'); - - -with- - - define('MAGPIE_DIR', '/path/to/magpierss/'); - require_once(MAGPIE_DIR.'rss_fetch.inc'); - - b. PHP can't read the MagpieRSS files - - All PHP libraries need to be readable by your webserver. - - On Unix you can accomplish this with: - - chmod 755 rss_fetch.inc rss_parse.inc rss_cache.inc rss_util.inc - -************************************************************************* -2. Cache couldn't make dir './cache'. - - MagpieRSS caches the results of fetched and parsed RSS to reduce the load on - both your server, and the remote server providing the RSS. It does this by - writing files to a cache directory. - - This error means the webserver doesn't have write access to the current - directory. - - a. Make a webserver writeable cache directory - - Find the webserver's group. (on my system it is 'www') - - mkdir ./cache - chgrp www directory_name - chmod g+w directory_name - - (this is the best, and desired solution) - - b. Tell MagpieRSS to create the cache directory somewhere the webserver can - write to. - - define('MAGPIE_CACHE_DIR', '/tmp/magpierss'); - - (this is not a great solution, and might have security considerations) - - c. Turn off cacheing. - - Magpie can work fine with cacheing, but it will be slower, and you might - become a nuiance to the RSS provider, but it is an option. - - define('MAGPIE_CACHE_ON', 0); - - d. And lastly, do NOT - - chmod 777 ./cache - - Any of the above solutions are better then this. - - NOTE: If none of this works for you, let me know. I've got root, and a - custom compiled Apache on almost any box I ever touch, so I can be a little - out of touch with reality. But I won't know that if I don't feedback. - -************************************************************************* 3. -3. Fatal error: Failed to load PHP's XML Extension. - http://www.php.net/manual/en/ref.xml.php - - -or- - - Fatal error: Failed to create an instance of PHP's XML parser. - http://www.php.net/manual/en/ref.xml.php - - Make sure your PHP was built with --with-xml - - This has been turned on by default for several versions of PHP, but it might - be turned off in your build. - - See php.net for details on building and configuring PHP. - - -************************************************************************* -4. Warning: MagpieRSS: Failed to fetch index.rdf. - (HTTP Error: Invalid protocol "") - - You need to put http:// in front of your the URL to your RSS feed - -************************************************************************* -5. Warning: MagpieRSS: Failed to parse RSS file. - (not well-formed (invalid token) at line 19, column 98) - - There is a problem with the RSS feed you are trying to read. - MagpieRSS is an XML parser, and therefore can't parse RSS feed with invalid - characters. Some RSS parser are based on regular expressions, and can - parse invalid RSS but they have their own problems. - - You could try contacting the author of the RSS feed, and pointing them to - the online RSS validator at: - - http://feeds.archive.org/validator/ - -************************************************************************* -6. Warning: MagpieRSS: Failed to fetch http://example.com/index.rdf - (HTTP Response: HTTP/1.1 404 Not Found) - - Its a 404! The RSS file ain't there. - - diff --git a/tools/IRC_Bot/magpierss/extlib/Snoopy.class.inc b/tools/IRC_Bot/magpierss/extlib/Snoopy.class.inc deleted file mode 100644 index 532ecba10..000000000 --- a/tools/IRC_Bot/magpierss/extlib/Snoopy.class.inc +++ /dev/null @@ -1,899 +0,0 @@ - -Copyright (c): 1999-2000 ispi, all rights reserved -Version: 1.0 - - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -You may contact the author of Snoopy by e-mail at: -monte@ispi.net - -Or, write to: -Monte Ohrt -CTO, ispi -237 S. 70th suite 220 -Lincoln, NE 68510 - -The latest version of Snoopy can be obtained from: -http://snoopy.sourceforge.com - -*************************************************/ - -class Snoopy -{ - /**** Public variables ****/ - - /* user definable vars */ - - var $host = "www.php.net"; // host name we are connecting to - var $port = 80; // port we are connecting to - var $proxy_host = ""; // proxy host to use - var $proxy_port = ""; // proxy port to use - var $agent = "Snoopy v1.0"; // agent we masquerade as - var $referer = ""; // referer info to pass - var $cookies = array(); // array of cookies to pass - // $cookies["username"]="joe"; - var $rawheaders = array(); // array of raw headers to send - // $rawheaders["Content-type"]="text/html"; - - var $maxredirs = 5; // http redirection depth maximum. 0 = disallow - var $lastredirectaddr = ""; // contains address of last redirected address - var $offsiteok = true; // allows redirection off-site - var $maxframes = 0; // frame content depth maximum. 0 = disallow - var $expandlinks = true; // expand links to fully qualified URLs. - // this only applies to fetchlinks() - // or submitlinks() - var $passcookies = true; // pass set cookies back through redirects - // NOTE: this currently does not respect - // dates, domains or paths. - - var $user = ""; // user for http authentication - var $pass = ""; // password for http authentication - - // http accept types - var $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; - - var $results = ""; // where the content is put - - var $error = ""; // error messages sent here - var $response_code = ""; // response code returned from server - var $headers = array(); // headers returned from server sent here - var $maxlength = 500000; // max return data length (body) - var $read_timeout = 0; // timeout on read operations, in seconds - // supported only since PHP 4 Beta 4 - // set to 0 to disallow timeouts - var $timed_out = false; // if a read operation timed out - var $status = 0; // http request status - - var $curl_path = "/usr/bin/curl"; - // Snoopy will use cURL for fetching - // SSL content if a full system path to - // the cURL binary is supplied here. - // set to false if you do not have - // cURL installed. See http://curl.haxx.se - // for details on installing cURL. - // Snoopy does *not* use the cURL - // library functions built into php, - // as these functions are not stable - // as of this Snoopy release. - - // send Accept-encoding: gzip? - var $use_gzip = true; - - /**** Private variables ****/ - - var $_maxlinelen = 4096; // max line length (headers) - - var $_httpmethod = "GET"; // default http request method - var $_httpversion = "HTTP/1.0"; // default http request version - var $_submit_method = "POST"; // default submit method - var $_submit_type = "application/x-www-form-urlencoded"; // default submit type - var $_mime_boundary = ""; // MIME boundary for multipart/form-data submit type - var $_redirectaddr = false; // will be set if page fetched is a redirect - var $_redirectdepth = 0; // increments on an http redirect - var $_frameurls = array(); // frame src urls - var $_framedepth = 0; // increments on frame depth - - var $_isproxy = false; // set if using a proxy server - var $_fp_timeout = 30; // timeout for socket connection - -/*======================================================================*\ - Function: fetch - Purpose: fetch the contents of a web page - (and possibly other protocols in the - future like ftp, nntp, gopher, etc.) - Input: $URI the location of the page to fetch - Output: $this->results the output text from the fetch -\*======================================================================*/ - - function fetch($URI) - { - - //preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS); - $URI_PARTS = parse_url($URI); - if (!empty($URI_PARTS["user"])) - $this->user = $URI_PARTS["user"]; - if (!empty($URI_PARTS["pass"])) - $this->pass = $URI_PARTS["pass"]; - - switch($URI_PARTS["scheme"]) - { - case "http": - $this->host = $URI_PARTS["host"]; - if(!empty($URI_PARTS["port"])) - $this->port = $URI_PARTS["port"]; - if($this->_connect($fp)) - { - if($this->_isproxy) - { - // using proxy, send entire URI - $this->_httprequest($URI,$fp,$URI,$this->_httpmethod); - } - else - { - $path = $URI_PARTS["path"].(isset($URI_PARTS["query"]) ? "?".$URI_PARTS["query"] : ""); - // no proxy, send only the path - $this->_httprequest($path, $fp, $URI, $this->_httpmethod); - } - - $this->_disconnect($fp); - - if($this->_redirectaddr) - { - /* url was redirected, check if we've hit the max depth */ - if($this->maxredirs > $this->_redirectdepth) - { - // only follow redirect if it's on this site, or offsiteok is true - if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) - { - /* follow the redirect */ - $this->_redirectdepth++; - $this->lastredirectaddr=$this->_redirectaddr; - $this->fetch($this->_redirectaddr); - } - } - } - - if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) - { - $frameurls = $this->_frameurls; - $this->_frameurls = array(); - - while(list(,$frameurl) = each($frameurls)) - { - if($this->_framedepth < $this->maxframes) - { - $this->fetch($frameurl); - $this->_framedepth++; - } - else - break; - } - } - } - else - { - return false; - } - return true; - break; - case "https": - if(!$this->curl_path || (!is_executable($this->curl_path))) { - $this->error = "Bad curl ($this->curl_path), can't fetch HTTPS \n"; - return false; - } - $this->host = $URI_PARTS["host"]; - if(!empty($URI_PARTS["port"])) - $this->port = $URI_PARTS["port"]; - if($this->_isproxy) - { - // using proxy, send entire URI - $this->_httpsrequest($URI,$URI,$this->_httpmethod); - } - else - { - $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); - // no proxy, send only the path - $this->_httpsrequest($path, $URI, $this->_httpmethod); - } - - if($this->_redirectaddr) - { - /* url was redirected, check if we've hit the max depth */ - if($this->maxredirs > $this->_redirectdepth) - { - // only follow redirect if it's on this site, or offsiteok is true - if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) - { - /* follow the redirect */ - $this->_redirectdepth++; - $this->lastredirectaddr=$this->_redirectaddr; - $this->fetch($this->_redirectaddr); - } - } - } - - if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) - { - $frameurls = $this->_frameurls; - $this->_frameurls = array(); - - while(list(,$frameurl) = each($frameurls)) - { - if($this->_framedepth < $this->maxframes) - { - $this->fetch($frameurl); - $this->_framedepth++; - } - else - break; - } - } - return true; - break; - default: - // not a valid protocol - $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; - return false; - break; - } - return true; - } - - - -/*======================================================================*\ - Private functions -\*======================================================================*/ - - -/*======================================================================*\ - Function: _striplinks - Purpose: strip the hyperlinks from an html document - Input: $document document to strip. - Output: $match an array of the links -\*======================================================================*/ - - function _striplinks($document) - { - preg_match_all("'<\s*a\s+.*href\s*=\s* # find ]+)) # if quote found, match up to next matching - # quote, otherwise match up to next space - 'isx",$document,$links); - - - // catenate the non-empty matches from the conditional subpattern - - while(list($key,$val) = each($links[2])) - { - if(!empty($val)) - $match[] = $val; - } - - while(list($key,$val) = each($links[3])) - { - if(!empty($val)) - $match[] = $val; - } - - // return the links - return $match; - } - -/*======================================================================*\ - Function: _stripform - Purpose: strip the form elements from an html document - Input: $document document to strip. - Output: $match an array of the links -\*======================================================================*/ - - function _stripform($document) - { - preg_match_all("'<\/?(FORM|INPUT|SELECT|TEXTAREA|(OPTION))[^<>]*>(?(2)(.*(?=<\/?(option|select)[^<>]*>[\r\n]*)|(?=[\r\n]*))|(?=[\r\n]*))'Usi",$document,$elements); - - // catenate the matches - $match = implode("\r\n",$elements[0]); - - // return the links - return $match; - } - - - -/*======================================================================*\ - Function: _striptext - Purpose: strip the text from an html document - Input: $document document to strip. - Output: $text the resulting text -\*======================================================================*/ - - function _striptext($document) - { - - // I didn't use preg eval (//e) since that is only available in PHP 4.0. - // so, list your entities one by one here. I included some of the - // more common ones. - - $search = array("']*?>.*?'si", // strip out javascript - "'<[\/\!]*?[^<>]*?>'si", // strip out html tags - "'([\r\n])[\s]+'", // strip out white space - "'&(quote|#34);'i", // replace html entities - "'&(amp|#38);'i", - "'&(lt|#60);'i", - "'&(gt|#62);'i", - "'&(nbsp|#160);'i", - "'&(iexcl|#161);'i", - "'&(cent|#162);'i", - "'&(pound|#163);'i", - "'&(copy|#169);'i" - ); - $replace = array( "", - "", - "\\1", - "\"", - "&", - "<", - ">", - " ", - chr(161), - chr(162), - chr(163), - chr(169)); - - $text = preg_replace($search,$replace,$document); - - return $text; - } - -/*======================================================================*\ - Function: _expandlinks - Purpose: expand each link into a fully qualified URL - Input: $links the links to qualify - $URI the full URI to get the base from - Output: $expandedLinks the expanded links -\*======================================================================*/ - - function _expandlinks($links,$URI) - { - - preg_match("/^[^\?]+/",$URI,$match); - - $match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]); - - $search = array( "|^http://".preg_quote($this->host)."|i", - "|^(?!http://)(\/)?(?!mailto:)|i", - "|/\./|", - "|/[^\/]+/\.\./|" - ); - - $replace = array( "", - $match."/", - "/", - "/" - ); - - $expandedLinks = preg_replace($search,$replace,$links); - - return $expandedLinks; - } - -/*======================================================================*\ - Function: _httprequest - Purpose: go get the http data from the server - Input: $url the url to fetch - $fp the current open file pointer - $URI the full URI - $body body contents to send if any (POST) - Output: -\*======================================================================*/ - - function _httprequest($url,$fp,$URI,$http_method,$content_type="",$body="") - { - if($this->passcookies && $this->_redirectaddr) - $this->setcookies(); - - $URI_PARTS = parse_url($URI); - if(empty($url)) - $url = "/"; - $headers = $http_method." ".$url." ".$this->_httpversion."\r\n"; - if(!empty($this->agent)) - $headers .= "User-Agent: ".$this->agent."\r\n"; - if(!empty($this->host) && !isset($this->rawheaders['Host'])) - $headers .= "Host: ".$this->host."\r\n"; - if(!empty($this->accept)) - $headers .= "Accept: ".$this->accept."\r\n"; - - if($this->use_gzip) { - // make sure PHP was built with --with-zlib - // and we can handle gzipp'ed data - if ( function_exists(gzinflate) ) { - $headers .= "Accept-encoding: gzip\r\n"; - } - else { - trigger_error( - "use_gzip is on, but PHP was built without zlib support.". - " Requesting file(s) without gzip encoding.", - E_USER_NOTICE); - } - } - - if(!empty($this->referer)) - $headers .= "Referer: ".$this->referer."\r\n"; - if(!empty($this->cookies)) - { - if(!is_array($this->cookies)) - $this->cookies = (array)$this->cookies; - - reset($this->cookies); - if ( count($this->cookies) > 0 ) { - $cookie_headers .= 'Cookie: '; - foreach ( $this->cookies as $cookieKey => $cookieVal ) { - $cookie_headers .= $cookieKey."=".urlencode($cookieVal)."; "; - } - $headers .= substr($cookie_headers,0,-2) . "\r\n"; - } - } - if(!empty($this->rawheaders)) - { - if(!is_array($this->rawheaders)) - $this->rawheaders = (array)$this->rawheaders; - while(list($headerKey,$headerVal) = each($this->rawheaders)) - $headers .= $headerKey.": ".$headerVal."\r\n"; - } - if(!empty($content_type)) { - $headers .= "Content-type: $content_type"; - if ($content_type == "multipart/form-data") - $headers .= "; boundary=".$this->_mime_boundary; - $headers .= "\r\n"; - } - if(!empty($body)) - $headers .= "Content-length: ".strlen($body)."\r\n"; - if(!empty($this->user) || !empty($this->pass)) - $headers .= "Authorization: BASIC ".base64_encode($this->user.":".$this->pass)."\r\n"; - - $headers .= "\r\n"; - - // set the read timeout if needed - if ($this->read_timeout > 0) - socket_set_timeout($fp, $this->read_timeout); - $this->timed_out = false; - - fwrite($fp,$headers.$body,strlen($headers.$body)); - - $this->_redirectaddr = false; - unset($this->headers); - - // content was returned gzip encoded? - $is_gzipped = false; - - while($currentHeader = fgets($fp,$this->_maxlinelen)) - { - if ($this->read_timeout > 0 && $this->_check_timeout($fp)) - { - $this->status=-100; - return false; - } - - // if($currentHeader == "\r\n") - if(preg_match("/^\r?\n$/", $currentHeader) ) - break; - - // if a header begins with Location: or URI:, set the redirect - if(preg_match("/^(Location:|URI:)/i",$currentHeader)) - { - // get URL portion of the redirect - preg_match("/^(Location:|URI:)\s+(.*)/",chop($currentHeader),$matches); - // look for :// in the Location header to see if hostname is included - if(!preg_match("|\:\/\/|",$matches[2])) - { - // no host in the path, so prepend - $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; - // eliminate double slash - if(!preg_match("|^/|",$matches[2])) - $this->_redirectaddr .= "/".$matches[2]; - else - $this->_redirectaddr .= $matches[2]; - } - else - $this->_redirectaddr = $matches[2]; - } - - if(preg_match("|^HTTP/|",$currentHeader)) - { - if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status)) - { - $this->status= $status[1]; - } - $this->response_code = $currentHeader; - } - - if (preg_match("/Content-Encoding: gzip/", $currentHeader) ) { - $is_gzipped = true; - } - - $this->headers[] = $currentHeader; - } - - # $results = fread($fp, $this->maxlength); - $results = ""; - while ( $data = fread($fp, $this->maxlength) ) { - $results .= $data; - if ( - strlen($results) > $this->maxlength ) { - break; - } - } - - // gunzip - if ( $is_gzipped ) { - // per http://www.php.net/manual/en/function.gzencode.php - $results = substr($results, 10); - $results = gzinflate($results); - } - - if ($this->read_timeout > 0 && $this->_check_timeout($fp)) - { - $this->status=-100; - return false; - } - - // check if there is a a redirect meta tag - - if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) - { - $this->_redirectaddr = $this->_expandlinks($match[1],$URI); - } - - // have we hit our frame depth and is there frame src to fetch? - if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) - { - $this->results[] = $results; - for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); - } - // have we already fetched framed content? - elseif(is_array($this->results)) - $this->results[] = $results; - // no framed content - else - $this->results = $results; - - return true; - } - -/*======================================================================*\ - Function: _httpsrequest - Purpose: go get the https data from the server using curl - Input: $url the url to fetch - $URI the full URI - $body body contents to send if any (POST) - Output: -\*======================================================================*/ - - function _httpsrequest($url,$URI,$http_method,$content_type="",$body="") - { - if($this->passcookies && $this->_redirectaddr) - $this->setcookies(); - - $headers = array(); - - $URI_PARTS = parse_url($URI); - if(empty($url)) - $url = "/"; - // GET ... header not needed for curl - //$headers[] = $http_method." ".$url." ".$this->_httpversion; - if(!empty($this->agent)) - $headers[] = "User-Agent: ".$this->agent; - if(!empty($this->host)) - $headers[] = "Host: ".$this->host; - if(!empty($this->accept)) - $headers[] = "Accept: ".$this->accept; - if(!empty($this->referer)) - $headers[] = "Referer: ".$this->referer; - if(!empty($this->cookies)) - { - if(!is_array($this->cookies)) - $this->cookies = (array)$this->cookies; - - reset($this->cookies); - if ( count($this->cookies) > 0 ) { - $cookie_str = 'Cookie: '; - foreach ( $this->cookies as $cookieKey => $cookieVal ) { - $cookie_str .= $cookieKey."=".urlencode($cookieVal)."; "; - } - $headers[] = substr($cookie_str,0,-2); - } - } - if(!empty($this->rawheaders)) - { - if(!is_array($this->rawheaders)) - $this->rawheaders = (array)$this->rawheaders; - while(list($headerKey,$headerVal) = each($this->rawheaders)) - $headers[] = $headerKey.": ".$headerVal; - } - if(!empty($content_type)) { - if ($content_type == "multipart/form-data") - $headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary; - else - $headers[] = "Content-type: $content_type"; - } - if(!empty($body)) - $headers[] = "Content-length: ".strlen($body); - if(!empty($this->user) || !empty($this->pass)) - $headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass); - - for($curr_header = 0; $curr_header < count($headers); $curr_header++) - $cmdline_params .= " -H \"".$headers[$curr_header]."\""; - - if(!empty($body)) - $cmdline_params .= " -d \"$body\""; - - if($this->read_timeout > 0) - $cmdline_params .= " -m ".$this->read_timeout; - - $headerfile = uniqid(time()); - - # accept self-signed certs - $cmdline_params .= " -k"; - exec($this->curl_path." -D \"/tmp/$headerfile\"".$cmdline_params." ".$URI,$results,$return); - - if($return) - { - $this->error = "Error: cURL could not retrieve the document, error $return."; - return false; - } - - - $results = implode("\r\n",$results); - - $result_headers = file("/tmp/$headerfile"); - - $this->_redirectaddr = false; - unset($this->headers); - - for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++) - { - - // if a header begins with Location: or URI:, set the redirect - if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader])) - { - // get URL portion of the redirect - preg_match("/^(Location: |URI:)(.*)/",chop($result_headers[$currentHeader]),$matches); - // look for :// in the Location header to see if hostname is included - if(!preg_match("|\:\/\/|",$matches[2])) - { - // no host in the path, so prepend - $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; - // eliminate double slash - if(!preg_match("|^/|",$matches[2])) - $this->_redirectaddr .= "/".$matches[2]; - else - $this->_redirectaddr .= $matches[2]; - } - else - $this->_redirectaddr = $matches[2]; - } - - if(preg_match("|^HTTP/|",$result_headers[$currentHeader])) - { - $this->response_code = $result_headers[$currentHeader]; - if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$this->response_code, $match)) - { - $this->status= $match[1]; - } - } - $this->headers[] = $result_headers[$currentHeader]; - } - - // check if there is a a redirect meta tag - - if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) - { - $this->_redirectaddr = $this->_expandlinks($match[1],$URI); - } - - // have we hit our frame depth and is there frame src to fetch? - if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) - { - $this->results[] = $results; - for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); - } - // have we already fetched framed content? - elseif(is_array($this->results)) - $this->results[] = $results; - // no framed content - else - $this->results = $results; - - unlink("/tmp/$headerfile"); - - return true; - } - -/*======================================================================*\ - Function: setcookies() - Purpose: set cookies for a redirection -\*======================================================================*/ - - function setcookies() - { - for($x=0; $xheaders); $x++) - { - if(preg_match("/^set-cookie:[\s]+([^=]+)=([^;]+)/i", $this->headers[$x],$match)) - $this->cookies[$match[1]] = $match[2]; - } - } - - -/*======================================================================*\ - Function: _check_timeout - Purpose: checks whether timeout has occurred - Input: $fp file pointer -\*======================================================================*/ - - function _check_timeout($fp) - { - if ($this->read_timeout > 0) { - $fp_status = socket_get_status($fp); - if ($fp_status["timed_out"]) { - $this->timed_out = true; - return true; - } - } - return false; - } - -/*======================================================================*\ - Function: _connect - Purpose: make a socket connection - Input: $fp file pointer -\*======================================================================*/ - - function _connect(&$fp) - { - if(!empty($this->proxy_host) && !empty($this->proxy_port)) - { - $this->_isproxy = true; - $host = $this->proxy_host; - $port = $this->proxy_port; - } - else - { - $host = $this->host; - $port = $this->port; - } - - $this->status = 0; - - if($fp = fsockopen( - $host, - $port, - $errno, - $errstr, - $this->_fp_timeout - )) - { - // socket connection succeeded - - return true; - } - else - { - // socket connection failed - $this->status = $errno; - switch($errno) - { - case -3: - $this->error="socket creation failed (-3)"; - case -4: - $this->error="dns lookup failure (-4)"; - case -5: - $this->error="connection refused or timed out (-5)"; - default: - $this->error="connection failed (".$errno.")"; - } - return false; - } - } -/*======================================================================*\ - Function: _disconnect - Purpose: disconnect a socket connection - Input: $fp file pointer -\*======================================================================*/ - - function _disconnect($fp) - { - return(fclose($fp)); - } - - -/*======================================================================*\ - Function: _prepare_post_body - Purpose: Prepare post body according to encoding type - Input: $formvars - form variables - $formfiles - form upload files - Output: post body -\*======================================================================*/ - - function _prepare_post_body($formvars, $formfiles) - { - settype($formvars, "array"); - settype($formfiles, "array"); - - if (count($formvars) == 0 && count($formfiles) == 0) - return; - - switch ($this->_submit_type) { - case "application/x-www-form-urlencoded": - reset($formvars); - while(list($key,$val) = each($formvars)) { - if (is_array($val) || is_object($val)) { - while (list($cur_key, $cur_val) = each($val)) { - $postdata .= urlencode($key)."[]=".urlencode($cur_val)."&"; - } - } else - $postdata .= urlencode($key)."=".urlencode($val)."&"; - } - break; - - case "multipart/form-data": - $this->_mime_boundary = "Snoopy".md5(uniqid(microtime())); - - reset($formvars); - while(list($key,$val) = each($formvars)) { - if (is_array($val) || is_object($val)) { - while (list($cur_key, $cur_val) = each($val)) { - $postdata .= "--".$this->_mime_boundary."\r\n"; - $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n"; - $postdata .= "$cur_val\r\n"; - } - } else { - $postdata .= "--".$this->_mime_boundary."\r\n"; - $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n"; - $postdata .= "$val\r\n"; - } - } - - reset($formfiles); - while (list($field_name, $file_names) = each($formfiles)) { - settype($file_names, "array"); - while (list(, $file_name) = each($file_names)) { - if (!is_readable($file_name)) continue; - - $fp = fopen($file_name, "r"); - $file_content = fread($fp, filesize($file_name)); - fclose($fp); - $base_name = basename($file_name); - - $postdata .= "--".$this->_mime_boundary."\r\n"; - $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n"; - $postdata .= "$file_content\r\n"; - } - } - $postdata .= "--".$this->_mime_boundary."--\r\n"; - break; - } - - return $postdata; - } -} - -?> diff --git a/tools/IRC_Bot/magpierss/rss_cache.inc b/tools/IRC_Bot/magpierss/rss_cache.inc deleted file mode 100644 index fdfa5dd25..000000000 --- a/tools/IRC_Bot/magpierss/rss_cache.inc +++ /dev/null @@ -1,184 +0,0 @@ - - * Version: 0.51 - * License: GPL - * - * The lastest version of MagpieRSS can be obtained from: - * http://magpierss.sourceforge.net - * - * For questions, help, comments, discussion, etc., please join the - * Magpie mailing list: - * http://lists.sourceforge.net/lists/listinfo/magpierss-general - * - */ - -class RSSCache { - var $BASE_CACHE = './cache'; // where the cache files are stored - var $MAX_AGE = 3600; // when are files stale, default one hour - var $ERROR = ""; // accumulate error messages - - function RSSCache ($base='', $age='') { - if ( $base ) { - $this->BASE_CACHE = $base; - } - if ( $age ) { - $this->MAX_AGE = $age; - } - - // attempt to make the cache directory - if ( ! file_exists( $this->BASE_CACHE ) ) { - $status = @mkdir( $this->BASE_CACHE, 0755 ); - - // if make failed - if ( ! $status ) { - $this->error( - "Cache couldn't make dir '" . $this->BASE_CACHE . "'." - ); - } - } - } - -/*=======================================================================*\ - Function: set - Purpose: add an item to the cache, keyed on url - Input: url from wich the rss file was fetched - Output: true on sucess -\*=======================================================================*/ - function set ($url, $rss) { - $this->ERROR = ""; - $cache_file = $this->file_name( $url ); - $fp = @fopen( $cache_file, 'w' ); - - if ( ! $fp ) { - $this->error( - "Cache unable to open file for writing: $cache_file" - ); - return 0; - } - - - $data = $this->serialize( $rss ); - fwrite( $fp, $data ); - fclose( $fp ); - - return $cache_file; - } - -/*=======================================================================*\ - Function: get - Purpose: fetch an item from the cache - Input: url from wich the rss file was fetched - Output: cached object on HIT, false on MISS -\*=======================================================================*/ - function get ($url) { - $this->ERROR = ""; - $cache_file = $this->file_name( $url ); - - if ( ! file_exists( $cache_file ) ) { - $this->debug( - "Cache doesn't contain: $url (cache file: $cache_file)" - ); - return 0; - } - - $fp = @fopen($cache_file, 'r'); - if ( ! $fp ) { - $this->error( - "Failed to open cache file for reading: $cache_file" - ); - return 0; - } - - $data = fread( $fp, filesize($cache_file) ); - $rss = $this->unserialize( $data ); - - return $rss; - } - -/*=======================================================================*\ - Function: check_cache - Purpose: check a url for membership in the cache - and whether the object is older then MAX_AGE (ie. STALE) - Input: url from wich the rss file was fetched - Output: cached object on HIT, false on MISS -\*=======================================================================*/ - function check_cache ( $url ) { - $this->ERROR = ""; - $filename = $this->file_name( $url ); - - if ( file_exists( $filename ) ) { - // find how long ago the file was added to the cache - // and whether that is longer then MAX_AGE - $mtime = filemtime( $filename ); - $age = time() - $mtime; - if ( $this->MAX_AGE > $age ) { - // object exists and is current - return 'HIT'; - } - else { - // object exists but is old - return 'STALE'; - } - } - else { - // object does not exist - return 'MISS'; - } - } - -/*=======================================================================*\ - Function: serialize -\*=======================================================================*/ - function serialize ( $rss ) { - return serialize( $rss ); - } - -/*=======================================================================*\ - Function: unserialize -\*=======================================================================*/ - function unserialize ( $data ) { - return unserialize( $data ); - } - -/*=======================================================================*\ - Function: file_name - Purpose: map url to location in cache - Input: url from wich the rss file was fetched - Output: a file name -\*=======================================================================*/ - function file_name ($url) { - $filename = md5( $url ); - return join( DIRECTORY_SEPARATOR, array( $this->BASE_CACHE, $filename ) ); - } - -/*=======================================================================*\ - Function: error - Purpose: register error -\*=======================================================================*/ - function error ($errormsg, $lvl=E_USER_WARNING) { - // append PHP's error message if track_errors enabled - if ( isset($php_errormsg) ) { - $errormsg .= " ($php_errormsg)"; - } - $this->ERROR = $errormsg; - if ( MAGPIE_DEBUG ) { - trigger_error( $errormsg, $lvl); - } - else { - error_log( $errormsg, 0); - } - } - - function debug ($debugmsg, $lvl=E_USER_NOTICE) { - if ( MAGPIE_DEBUG ) { - $this->error("MagpieRSS [debug] $debugmsg", $lvl); - } - } - -} - -?> diff --git a/tools/IRC_Bot/magpierss/rss_fetch.inc b/tools/IRC_Bot/magpierss/rss_fetch.inc deleted file mode 100644 index c1098d681..000000000 --- a/tools/IRC_Bot/magpierss/rss_fetch.inc +++ /dev/null @@ -1,458 +0,0 @@ - - * License: GPL - * - * The lastest version of MagpieRSS can be obtained from: - * http://magpierss.sourceforge.net - * - * For questions, help, comments, discussion, etc., please join the - * Magpie mailing list: - * magpierss-general@lists.sourceforge.net - * - */ - -// Setup MAGPIE_DIR for use on hosts that don't include -// the current path in include_path. -// with thanks to rajiv and smarty -if (!defined('DIR_SEP')) { - define('DIR_SEP', DIRECTORY_SEPARATOR); -} - -if (!defined('MAGPIE_DIR')) { - define('MAGPIE_DIR', dirname(__FILE__) . DIR_SEP); -} - -require_once( MAGPIE_DIR . 'rss_parse.inc' ); -require_once( MAGPIE_DIR . 'rss_cache.inc' ); - -// for including 3rd party libraries -define('MAGPIE_EXTLIB', MAGPIE_DIR . 'extlib' . DIR_SEP); -require_once( MAGPIE_EXTLIB . 'Snoopy.class.inc'); - - -/* - * CONSTANTS - redefine these in your script to change the - * behaviour of fetch_rss() currently, most options effect the cache - * - * MAGPIE_CACHE_ON - Should Magpie cache parsed RSS objects? - * For me a built in cache was essential to creating a "PHP-like" - * feel to Magpie, see rss_cache.inc for rationale - * - * - * MAGPIE_CACHE_DIR - Where should Magpie cache parsed RSS objects? - * This should be a location that the webserver can write to. If this - * directory does not already exist Mapie will try to be smart and create - * it. This will often fail for permissions reasons. - * - * - * MAGPIE_CACHE_AGE - How long to store cached RSS objects? In seconds. - * - * - * MAGPIE_CACHE_FRESH_ONLY - If remote fetch fails, throw error - * instead of returning stale object? - * - * MAGPIE_DEBUG - Display debugging notices? - * -*/ - - -/*=======================================================================*\ - Function: fetch_rss: - Purpose: return RSS object for the give url - maintain the cache - Input: url of RSS file - Output: parsed RSS object (see rss_parse.inc) - - NOTES ON CACHEING: - If caching is on (MAGPIE_CACHE_ON) fetch_rss will first check the cache. - - NOTES ON RETRIEVING REMOTE FILES: - If conditional gets are on (MAGPIE_CONDITIONAL_GET_ON) fetch_rss will - return a cached object, and touch the cache object upon recieving a - 304. - - NOTES ON FAILED REQUESTS: - If there is an HTTP error while fetching an RSS object, the cached - version will be return, if it exists (and if MAGPIE_CACHE_FRESH_ONLY is off) -\*=======================================================================*/ - -define('MAGPIE_VERSION', '0.7'); - -$MAGPIE_ERROR = ""; - -function fetch_rss ($url) { - // initialize constants - init(); - - if ( !isset($url) ) { - error("fetch_rss called without a url"); - return false; - } - - // if cache is disabled - if ( !MAGPIE_CACHE_ON ) { - // fetch file, and parse it - $resp = _fetch_remote_file( $url ); - if ( is_success( $resp->status ) ) { - return _response_to_rss( $resp ); - } - else { - error("Failed to fetch $url and cache is off"); - return false; - } - } - // else cache is ON - else { - // Flow - // 1. check cache - // 2. if there is a hit, make sure its fresh - // 3. if cached obj fails freshness check, fetch remote - // 4. if remote fails, return stale object, or error - - $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE ); - - if (MAGPIE_DEBUG and $cache->ERROR) { - debug($cache->ERROR, E_USER_WARNING); - } - - - $cache_status = 0; // response of check_cache - $request_headers = array(); // HTTP headers to send with fetch - $rss = 0; // parsed RSS object - $errormsg = 0; // errors, if any - - // store parsed XML by desired output encoding - // as character munging happens at parse time - $cache_key = $url . MAGPIE_OUTPUT_ENCODING; - - if (!$cache->ERROR) { - // return cache HIT, MISS, or STALE - $cache_status = $cache->check_cache( $cache_key); - } - - // if object cached, and cache is fresh, return cached obj - if ( $cache_status == 'HIT' ) { - $rss = $cache->get( $cache_key ); - if ( isset($rss) and $rss ) { - // should be cache age - $rss->from_cache = 1; - if ( MAGPIE_DEBUG > 1) { - debug("MagpieRSS: Cache HIT", E_USER_NOTICE); - } - return $rss; - } - } - - // else attempt a conditional get - - // setup headers - if ( $cache_status == 'STALE' ) { - $rss = $cache->get( $cache_key ); - if ( $rss and $rss->etag and $rss->last_modified ) { - $request_headers['If-None-Match'] = $rss->etag; - $request_headers['If-Last-Modified'] = $rss->last_modified; - } - } - - $resp = _fetch_remote_file( $url, $request_headers ); - - if (isset($resp) and $resp) { - if ($resp->status == '304' ) { - // we have the most current copy - if ( MAGPIE_DEBUG > 1) { - debug("Got 304 for $url"); - } - // reset cache on 304 (at minutillo insistent prodding) - $cache->set($cache_key, $rss); - return $rss; - } - elseif ( is_success( $resp->status ) ) { - $rss = _response_to_rss( $resp ); - if ( $rss ) { - if (MAGPIE_DEBUG > 1) { - debug("Fetch successful"); - } - // add object to cache - $cache->set( $cache_key, $rss ); - return $rss; - } - } - else { - $errormsg = "Failed to fetch $url "; - if ( $resp->status == '-100' ) { - $errormsg .= "(Request timed out after " . MAGPIE_FETCH_TIME_OUT . " seconds)"; - } - elseif ( $resp->error ) { - # compensate for Snoopy's annoying habbit to tacking - # on '\n' - $http_error = substr($resp->error, 0, -2); - $errormsg .= "(HTTP Error: $http_error)"; - } - else { - $errormsg .= "(HTTP Response: " . $resp->response_code .')'; - } - } - } - else { - $errormsg = "Unable to retrieve RSS file for unknown reasons."; - } - - // else fetch failed - - // attempt to return cached object - if ($rss) { - if ( MAGPIE_DEBUG ) { - debug("Returning STALE object for $url"); - } - return $rss; - } - - // else we totally failed - error( $errormsg ); - - return false; - - } // end if ( !MAGPIE_CACHE_ON ) { -} // end fetch_rss() - -/*=======================================================================*\ - Function: error - Purpose: set MAGPIE_ERROR, and trigger error -\*=======================================================================*/ - -function error ($errormsg, $lvl=E_USER_WARNING) { - global $MAGPIE_ERROR; - - // append PHP's error message if track_errors enabled - if ( isset($php_errormsg) ) { - $errormsg .= " ($php_errormsg)"; - } - if ( $errormsg ) { - $errormsg = "MagpieRSS: $errormsg"; - $MAGPIE_ERROR = $errormsg; - trigger_error( $errormsg, $lvl); - } -} - -function debug ($debugmsg, $lvl=E_USER_NOTICE) { - trigger_error("MagpieRSS [debug] $debugmsg", $lvl); -} - -/*=======================================================================*\ - Function: magpie_error - Purpose: accessor for the magpie error variable -\*=======================================================================*/ -function magpie_error ($errormsg="") { - global $MAGPIE_ERROR; - - if ( isset($errormsg) and $errormsg ) { - $MAGPIE_ERROR = $errormsg; - } - - return $MAGPIE_ERROR; -} - -/*=======================================================================*\ - Function: _fetch_remote_file - Purpose: retrieve an arbitrary remote file - Input: url of the remote file - headers to send along with the request (optional) - Output: an HTTP response object (see Snoopy.class.inc) -\*=======================================================================*/ -function _fetch_remote_file ($url, $headers = "" ) { - // Snoopy is an HTTP client in PHP - $client = new Snoopy(); - $client->agent = MAGPIE_USER_AGENT; - $client->read_timeout = MAGPIE_FETCH_TIME_OUT; - $client->use_gzip = MAGPIE_USE_GZIP; - if (is_array($headers) ) { - $client->rawheaders = $headers; - } - - @$client->fetch($url); - return $client; - -} - -/*=======================================================================*\ - Function: _response_to_rss - Purpose: parse an HTTP response object into an RSS object - Input: an HTTP response object (see Snoopy) - Output: parsed RSS object (see rss_parse) -\*=======================================================================*/ -function _response_to_rss ($resp) { - $rss = new MagpieRSS( $resp->results, MAGPIE_OUTPUT_ENCODING, MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING ); - - // if RSS parsed successfully - if ( $rss and !$rss->ERROR) { - - // find Etag, and Last-Modified - foreach($resp->headers as $h) { - // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1" - if (strpos($h, ": ")) { - list($field, $val) = explode(": ", $h, 2); - } - else { - $field = $h; - $val = ""; - } - - if ( $field == 'ETag' ) { - $rss->etag = $val; - } - - if ( $field == 'Last-Modified' ) { - $rss->last_modified = $val; - } - } - - return $rss; - } // else construct error message - else { - $errormsg = "Failed to parse RSS file."; - - if ($rss) { - $errormsg .= " (" . $rss->ERROR . ")"; - } - error($errormsg); - - return false; - } // end if ($rss and !$rss->error) -} - -/*=======================================================================*\ - Function: init - Purpose: setup constants with default values - check for user overrides -\*=======================================================================*/ -function init () { - if ( defined('MAGPIE_INITALIZED') ) { - return; - } - else { - define('MAGPIE_INITALIZED', true); - } - - if ( !defined('MAGPIE_CACHE_ON') ) { - define('MAGPIE_CACHE_ON', true); - } - - if ( !defined('MAGPIE_CACHE_DIR') ) { - define('MAGPIE_CACHE_DIR', './cache'); - } - - if ( !defined('MAGPIE_CACHE_AGE') ) { - define('MAGPIE_CACHE_AGE', 60*60); // one hour - } - - if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) { - define('MAGPIE_CACHE_FRESH_ONLY', false); - } - - if ( !defined('MAGPIE_OUTPUT_ENCODING') ) { - define('MAGPIE_OUTPUT_ENCODING', 'ISO-8859-1'); - } - - if ( !defined('MAGPIE_INPUT_ENCODING') ) { - define('MAGPIE_INPUT_ENCODING', null); - } - - if ( !defined('MAGPIE_DETECT_ENCODING') ) { - define('MAGPIE_DETECT_ENCODING', true); - } - - if ( !defined('MAGPIE_DEBUG') ) { - define('MAGPIE_DEBUG', 0); - } - - if ( !defined('MAGPIE_USER_AGENT') ) { - $ua = 'MagpieRSS/'. MAGPIE_VERSION . ' (+http://magpierss.sf.net'; - - if ( MAGPIE_CACHE_ON ) { - $ua = $ua . ')'; - } - else { - $ua = $ua . '; No cache)'; - } - - define('MAGPIE_USER_AGENT', $ua); - } - - if ( !defined('MAGPIE_FETCH_TIME_OUT') ) { - define('MAGPIE_FETCH_TIME_OUT', 5); // 5 second timeout - } - - // use gzip encoding to fetch rss files if supported? - if ( !defined('MAGPIE_USE_GZIP') ) { - define('MAGPIE_USE_GZIP', true); - } -} - -// NOTE: the following code should really be in Snoopy, or at least -// somewhere other then rss_fetch! - -/*=======================================================================*\ - HTTP STATUS CODE PREDICATES - These functions attempt to classify an HTTP status code - based on RFC 2616 and RFC 2518. - - All of them take an HTTP status code as input, and return true or false - - All this code is adapted from LWP's HTTP::Status. -\*=======================================================================*/ - - -/*=======================================================================*\ - Function: is_info - Purpose: return true if Informational status code -\*=======================================================================*/ -function is_info ($sc) { - return $sc >= 100 && $sc < 200; -} - -/*=======================================================================*\ - Function: is_success - Purpose: return true if Successful status code -\*=======================================================================*/ -function is_success ($sc) { - return $sc >= 200 && $sc < 300; -} - -/*=======================================================================*\ - Function: is_redirect - Purpose: return true if Redirection status code -\*=======================================================================*/ -function is_redirect ($sc) { - return $sc >= 300 && $sc < 400; -} - -/*=======================================================================*\ - Function: is_error - Purpose: return true if Error status code -\*=======================================================================*/ -function is_error ($sc) { - return $sc >= 400 && $sc < 600; -} - -/*=======================================================================*\ - Function: is_client_error - Purpose: return true if Error status code, and its a client error -\*=======================================================================*/ -function is_client_error ($sc) { - return $sc >= 400 && $sc < 500; -} - -/*=======================================================================*\ - Function: is_client_error - Purpose: return true if Error status code, and its a server error -\*=======================================================================*/ -function is_server_error ($sc) { - return $sc >= 500 && $sc < 600; -} - -?> diff --git a/tools/IRC_Bot/magpierss/rss_parse.inc b/tools/IRC_Bot/magpierss/rss_parse.inc deleted file mode 100644 index af4020ebf..000000000 --- a/tools/IRC_Bot/magpierss/rss_parse.inc +++ /dev/null @@ -1,589 +0,0 @@ - -* @version 0.7a -* @license GPL -* -*/ - -define('RSS', 'RSS'); -define('ATOM', 'Atom'); - -require_once (MAGPIE_DIR . 'rss_utils.inc'); - -/** -* Hybrid parser, and object, takes RSS as a string and returns a simple object. -* -* see: rss_fetch.inc for a simpler interface with integrated caching support -* -*/ -class MagpieRSS { - var $parser; - - var $current_item = array(); // item currently being parsed - var $items = array(); // collection of parsed items - var $channel = array(); // hash of channel fields - var $textinput = array(); - var $image = array(); - var $feed_type; - var $feed_version; - var $encoding = ''; // output encoding of parsed rss - - var $_source_encoding = ''; // only set if we have to parse xml prolog - - var $ERROR = ""; - var $WARNING = ""; - - // define some constants - - var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright'); - var $_KNOWN_ENCODINGS = array('UTF-8', 'US-ASCII', 'ISO-8859-1'); - - // parser variables, useless if you're not a parser, treat as private - var $stack = array(); // parser stack - var $inchannel = false; - var $initem = false; - var $incontent = false; // if in Atom field - var $intextinput = false; - var $inimage = false; - var $current_field = ''; - var $current_namespace = false; - - - /** - * Set up XML parser, parse source, and return populated RSS object.. - * - * @param string $source string containing the RSS to be parsed - * - * NOTE: Probably a good idea to leave the encoding options alone unless - * you know what you're doing as PHP's character set support is - * a little weird. - * - * NOTE: A lot of this is unnecessary but harmless with PHP5 - * - * - * @param string $output_encoding output the parsed RSS in this character - * set defaults to ISO-8859-1 as this is PHP's - * default. - * - * NOTE: might be changed to UTF-8 in future - * versions. - * - * @param string $input_encoding the character set of the incoming RSS source. - * Leave blank and Magpie will try to figure it - * out. - * - * - * @param bool $detect_encoding if false Magpie won't attempt to detect - * source encoding. (caveat emptor) - * - */ - function MagpieRSS ($source, $output_encoding='ISO-8859-1', - $input_encoding=null, $detect_encoding=true) - { - # if PHP xml isn't compiled in, die - # - if (!function_exists('xml_parser_create')) { - $this->error( "Failed to load PHP's XML Extension. " . - "http://www.php.net/manual/en/ref.xml.php", - E_USER_ERROR ); - } - - list($parser, $source) = $this->create_parser($source, - $output_encoding, $input_encoding, $detect_encoding); - - - if (!is_resource($parser)) { - $this->error( "Failed to create an instance of PHP's XML parser. " . - "http://www.php.net/manual/en/ref.xml.php", - E_USER_ERROR ); - } - - - $this->parser = $parser; - - # pass in parser, and a reference to this object - # setup handlers - # - xml_set_object( $this->parser, $this ); - xml_set_element_handler($this->parser, - 'feed_start_element', 'feed_end_element' ); - - xml_set_character_data_handler( $this->parser, 'feed_cdata' ); - - $status = xml_parse( $this->parser, $source ); - - if (! $status ) { - $errorcode = xml_get_error_code( $this->parser ); - if ( $errorcode != XML_ERROR_NONE ) { - $xml_error = xml_error_string( $errorcode ); - $error_line = xml_get_current_line_number($this->parser); - $error_col = xml_get_current_column_number($this->parser); - $errormsg = "$xml_error at line $error_line, column $error_col"; - - $this->error( $errormsg ); - } - } - - xml_parser_free( $this->parser ); - - $this->normalize(); - } - - function feed_start_element($p, $element, &$attrs) { - $el = $element = strtolower($element); - $attrs = array_change_key_case($attrs, CASE_LOWER); - - // check for a namespace, and split if found - $ns = false; - if ( strpos( $element, ':' ) ) { - list($ns, $el) = split( ':', $element, 2); - } - if ( $ns and $ns != 'rdf' ) { - $this->current_namespace = $ns; - } - - # if feed type isn't set, then this is first element of feed - # identify feed from root element - # - if (!isset($this->feed_type) ) { - if ( $el == 'rdf' ) { - $this->feed_type = RSS; - $this->feed_version = '1.0'; - } - elseif ( $el == 'rss' ) { - $this->feed_type = RSS; - $this->feed_version = $attrs['version']; - } - elseif ( $el == 'feed' ) { - $this->feed_type = ATOM; - $this->feed_version = $attrs['version']; - $this->inchannel = true; - } - return; - } - - if ( $el == 'channel' ) - { - $this->inchannel = true; - } - elseif ($el == 'item' or $el == 'entry' ) - { - $this->initem = true; - if ( isset($attrs['rdf:about']) ) { - $this->current_item['about'] = $attrs['rdf:about']; - } - } - - // if we're in the default namespace of an RSS feed, - // record textinput or image fields - elseif ( - $this->feed_type == RSS and - $this->current_namespace == '' and - $el == 'textinput' ) - { - $this->intextinput = true; - } - - elseif ( - $this->feed_type == RSS and - $this->current_namespace == '' and - $el == 'image' ) - { - $this->inimage = true; - } - - # handle atom content constructs - elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) - { - // avoid clashing w/ RSS mod_content - if ($el == 'content' ) { - $el = 'atom_content'; - } - - $this->incontent = $el; - - - } - - // if inside an Atom content construct (e.g. content or summary) field treat tags as text - elseif ($this->feed_type == ATOM and $this->incontent ) - { - // if tags are inlined, then flatten - $attrs_str = join(' ', - array_map('map_attrs', - array_keys($attrs), - array_values($attrs) ) ); - - $this->append_content( "<$element $attrs_str>" ); - - array_unshift( $this->stack, $el ); - } - - // Atom support many links per containging element. - // Magpie treats link elements of type rel='alternate' - // as being equivalent to RSS's simple link element. - // - elseif ($this->feed_type == ATOM and $el == 'link' ) - { - if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' ) - { - $link_el = 'link'; - } - else { - $link_el = 'link_' . $attrs['rel']; - } - - $this->append($link_el, $attrs['href']); - } - // set stack[0] to current element - else { - array_unshift($this->stack, $el); - } - } - - - - function feed_cdata ($p, $text) { - - if ($this->feed_type == ATOM and $this->incontent) - { - $this->append_content( $text ); - } - else { - $current_el = join('_', array_reverse($this->stack)); - $this->append($current_el, $text); - } - } - - function feed_end_element ($p, $el) { - $el = strtolower($el); - - if ( $el == 'item' or $el == 'entry' ) - { - $this->items[] = $this->current_item; - $this->current_item = array(); - $this->initem = false; - } - elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) - { - $this->intextinput = false; - } - elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) - { - $this->inimage = false; - } - elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) - { - $this->incontent = false; - } - elseif ($el == 'channel' or $el == 'feed' ) - { - $this->inchannel = false; - } - elseif ($this->feed_type == ATOM and $this->incontent ) { - // balance tags properly - // note: i don't think this is actually neccessary - if ( $this->stack[0] == $el ) - { - $this->append_content(""); - } - else { - $this->append_content("<$el />"); - } - - array_shift( $this->stack ); - } - else { - array_shift( $this->stack ); - } - - $this->current_namespace = false; - } - - function concat (&$str1, $str2="") { - if (!isset($str1) ) { - $str1=""; - } - $str1 .= $str2; - } - - - - function append_content($text) { - if ( $this->initem ) { - $this->concat( $this->current_item[ $this->incontent ], $text ); - } - elseif ( $this->inchannel ) { - $this->concat( $this->channel[ $this->incontent ], $text ); - } - } - - // smart append - field and namespace aware - function append($el, $text) { - if (!$el) { - return; - } - if ( $this->current_namespace ) - { - if ( $this->initem ) { - $this->concat( - $this->current_item[ $this->current_namespace ][ $el ], $text); - } - elseif ($this->inchannel) { - $this->concat( - $this->channel[ $this->current_namespace][ $el ], $text ); - } - elseif ($this->intextinput) { - $this->concat( - $this->textinput[ $this->current_namespace][ $el ], $text ); - } - elseif ($this->inimage) { - $this->concat( - $this->image[ $this->current_namespace ][ $el ], $text ); - } - } - else { - if ( $this->initem ) { - $this->concat( - $this->current_item[ $el ], $text); - } - elseif ($this->intextinput) { - $this->concat( - $this->textinput[ $el ], $text ); - } - elseif ($this->inimage) { - $this->concat( - $this->image[ $el ], $text ); - } - elseif ($this->inchannel) { - $this->concat( - $this->channel[ $el ], $text ); - } - - } - } - - function normalize () { - // if atom populate rss fields - if ( $this->is_atom() ) { - $this->channel['description'] = $this->channel['tagline']; - for ( $i = 0; $i < count($this->items); $i++) { - $item = $this->items[$i]; - if ( isset($item['summary']) ) - $item['description'] = $item['summary']; - if ( isset($item['atom_content'])) - $item['content']['encoded'] = $item['atom_content']; - - $atom_date = (isset($item['issued']) ) ? $item['issued'] : $item['modified']; - if ( $atom_date ) { - $epoch = @parse_w3cdtf($item['modified']); - if ($epoch and $epoch > 0) { - $item['date_timestamp'] = $epoch; - } - } - - $this->items[$i] = $item; - } - } - elseif ( $this->is_rss() ) { - $this->channel['tagline'] = $this->channel['description']; - for ( $i = 0; $i < count($this->items); $i++) { - $item = $this->items[$i]; - if ( isset($item['description'])) - $item['summary'] = $item['description']; - if ( isset($item['content']['encoded'] ) ) - $item['atom_content'] = $item['content']['encoded']; - - if ( $this->is_rss() == '1.0' and isset($item['dc']['date']) ) { - $epoch = @parse_w3cdtf($item['dc']['date']); - if ($epoch and $epoch > 0) { - $item['date_timestamp'] = $epoch; - } - } - elseif ( isset($item['pubdate']) ) { - $epoch = @strtotime($item['pubdate']); - if ($epoch > 0) { - $item['date_timestamp'] = $epoch; - } - } - - $this->items[$i] = $item; - } - } - } - - - function is_rss () { - if ( $this->feed_type == RSS ) { - return $this->feed_version; - } - else { - return false; - } - } - - function is_atom() { - if ( $this->feed_type == ATOM ) { - return $this->feed_version; - } - else { - return false; - } - } - - /** - * return XML parser, and possibly re-encoded source - * - */ - function create_parser($source, $out_enc, $in_enc, $detect) { - if ( substr(phpversion(),0,1) == 5) { - $parser = $this->php5_create_parser($in_enc, $detect); - } - else { - list($parser, $source) = $this->php4_create_parser($source, $in_enc, $detect); - } - if ($out_enc) { - $this->encoding = $out_enc; - xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $out_enc); - } - - return array($parser, $source); - } - - /** - * Instantiate an XML parser under PHP5 - * - * PHP5 will do a fine job of detecting input encoding - * if passed an empty string as the encoding. - * - * All hail libxml2! - * - */ - function php5_create_parser($in_enc, $detect) { - // by default php5 does a fine job of detecting input encodings - if(!$detect && $in_enc) { - return xml_parser_create($in_enc); - } - else { - return xml_parser_create(''); - } - } - - /** - * Instaniate an XML parser under PHP4 - * - * Unfortunately PHP4's support for character encodings - * and especially XML and character encodings sucks. As - * long as the documents you parse only contain characters - * from the ISO-8859-1 character set (a superset of ASCII, - * and a subset of UTF-8) you're fine. However once you - * step out of that comfy little world things get mad, bad, - * and dangerous to know. - * - * The following code is based on SJM's work with FoF - * @see http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss - * - */ - function php4_create_parser($source, $in_enc, $detect) { - if ( !$detect ) { - return array(xml_parser_create($in_enc), $source); - } - - if (!$in_enc) { - if (preg_match('//m', $source, $m)) { - $in_enc = strtoupper($m[1]); - $this->source_encoding = $in_enc; - } - else { - $in_enc = 'UTF-8'; - } - } - - if ($this->known_encoding($in_enc)) { - return array(xml_parser_create($in_enc), $source); - } - - // the dectected encoding is not one of the simple encodings PHP knows - - // attempt to use the iconv extension to - // cast the XML to a known encoding - // @see http://php.net/iconv - - if (function_exists('iconv')) { - $encoded_source = iconv($in_enc,'UTF-8', $source); - if ($encoded_source) { - return array(xml_parser_create('UTF-8'), $encoded_source); - } - } - - // iconv didn't work, try mb_convert_encoding - // @see http://php.net/mbstring - if(function_exists('mb_convert_encoding')) { - $encoded_source = mb_convert_encoding($source, 'UTF-8', $in_enc ); - if ($encoded_source) { - return array(xml_parser_create('UTF-8'), $encoded_source); - } - } - - // else - $this->error("Feed is in an unsupported character encoding. ($in_enc) " . - "You may see strange artifacts, and mangled characters.", - E_USER_NOTICE); - - return array(xml_parser_create(), $source); - } - - function known_encoding($enc) { - $enc = strtoupper($enc); - if ( in_array($enc, $this->_KNOWN_ENCODINGS) ) { - return $enc; - } - else { - return false; - } - } - - function error ($errormsg, $lvl=E_USER_WARNING) { - // append PHP's error message if track_errors enabled - if ( $php_errormsg ) { - $errormsg .= " ($php_errormsg)"; - } - if ( MAGPIE_DEBUG ) { - trigger_error( $errormsg, $lvl); - } - else { - error_log( $errormsg, 0); - } - - $notices = E_USER_NOTICE|E_NOTICE; - if ( $lvl&$notices ) { - $this->WARNING = $errormsg; - } else { - $this->ERROR = $errormsg; - } - } - - -} // end class RSS - -function map_attrs($k, $v) { - return "$k=\"$v\""; -} - - -?> diff --git a/tools/IRC_Bot/magpierss/rss_utils.inc b/tools/IRC_Bot/magpierss/rss_utils.inc deleted file mode 100644 index 2a29e72a9..000000000 --- a/tools/IRC_Bot/magpierss/rss_utils.inc +++ /dev/null @@ -1,67 +0,0 @@ - - * Version: 0.51 - * License: GPL - * - * The lastest version of MagpieRSS can be obtained from: - * http://magpierss.sourceforge.net - * - * For questions, help, comments, discussion, etc., please join the - * Magpie mailing list: - * magpierss-general@lists.sourceforge.net - */ - - -/*======================================================================*\ - Function: parse_w3cdtf - Purpose: parse a W3CDTF date into unix epoch - - NOTE: http://www.w3.org/TR/NOTE-datetime -\*======================================================================*/ - -function parse_w3cdtf ( $date_str ) { - - # regex to match wc3dtf - $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/"; - - if ( preg_match( $pat, $date_str, $match ) ) { - list( $year, $month, $day, $hours, $minutes, $seconds) = - array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[6]); - - # calc epoch for current date assuming GMT - $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year); - - $offset = 0; - if ( $match[10] == 'Z' ) { - # zulu time, aka GMT - } - else { - list( $tz_mod, $tz_hour, $tz_min ) = - array( $match[8], $match[9], $match[10]); - - # zero out the variables - if ( ! $tz_hour ) { $tz_hour = 0; } - if ( ! $tz_min ) { $tz_min = 0; } - - $offset_secs = (($tz_hour*60)+$tz_min)*60; - - # is timezone ahead of GMT? then subtract offset - # - if ( $tz_mod == '+' ) { - $offset_secs = $offset_secs * -1; - } - - $offset = $offset_secs; - } - $epoch = $epoch + $offset; - return $epoch; - } - else { - return -1; - } -} - -?> diff --git a/tools/LevelConverter/Makefile b/tools/LevelConverter/Makefile deleted file mode 100644 index 23b8a1106..000000000 --- a/tools/LevelConverter/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -# Makfile for SRB2 Level Converter -# by Alam Arias et al. - -SRC=levelconverter.c -OBJ=$(SRC:.c=.o)# replaces the .c from SRC with .o -EXE=LevelConverter - -.PHONY : all # .PHONY ignores files named all -all: $(EXE) # all is dependent on $(BIN) to be complete - -$(EXE): $(OBJ) # $(EXE) is dependent on all of the files in $(OBJ) to exist - $(CC) $(OBJ) $(LDFLAGS) -o $@ - -.PHONY : clean # .PHONY ignores files named clean -clean: - -$(RM) $(OBJ) $(EXE) diff --git a/tools/LevelConverter/levelconverter.c b/tools/LevelConverter/levelconverter.c deleted file mode 100644 index 7c84ac510..000000000 --- a/tools/LevelConverter/levelconverter.c +++ /dev/null @@ -1,1061 +0,0 @@ -// -// Level Converter -// -// Converts thing types from 1.09.4 to 1.1 -// -// By A.J. Freda -// -// Modified from Graue's "Heightedit" -// and uses Graue's "LumpMod" utility. -// - -#include -#include -#include - -//#define STARPOSTS_ONLY - -#define TABLE_SIZE 16384 -int conversion[TABLE_SIZE]; // Conversion table. -FILE *lvlconvfile; - -static inline void InitializeThingConversionTable(void) -{ - memset(conversion, 0, sizeof(conversion)); - - // Player starts - conversion[1] = 1; - conversion[2] = 2; - conversion[3] = 3; - conversion[4] = 4; - conversion[4001] = 5; - conversion[4002] = 6; - conversion[4003] = 7; - conversion[4004] = 8; - conversion[4005] = 9; - conversion[4006] = 10; - conversion[4007] = 11; - conversion[4008] = 12; - conversion[4009] = 13; - conversion[4010] = 14; - conversion[4011] = 15; - conversion[4012] = 16; - conversion[4013] = 17; - conversion[4014] = 18; - conversion[4015] = 19; - conversion[4016] = 20; - conversion[4017] = 21; - conversion[4018] = 22; - conversion[4019] = 23; - conversion[4020] = 24; - conversion[4021] = 25; - conversion[4022] = 26; - conversion[4023] = 27; - conversion[4024] = 28; - conversion[4025] = 29; - conversion[4026] = 30; - conversion[4027] = 31; - conversion[4028] = 32; - conversion[11] = 33; - conversion[87] = 34; - conversion[89] = 35; - - // Enemies - conversion[3004] = 100; - conversion[9] = 101; - conversion[58] = 102; - conversion[5005] = 103; - conversion[5006] = 104; - conversion[3005] = 105; - conversion[22] = 106; - conversion[21] = 107; - conversion[71] = 108; - conversion[56] = 109; - conversion[2004] = 110; - conversion[42] = 111; - - // Bosses - conversion[16] = 200; - conversion[2008] = 201; - conversion[17] = 290; - conversion[2049] = 291; - - // Collectibles - conversion[2014] = 300; - conversion[69] = 301; - conversion[3003] = 302; - conversion[80] = 303; - conversion[26] = 304; - conversion[54] = 305; - conversion[31] = 310; - conversion[34] = 311; - conversion[2013] = 312; - conversion[420] = 313; - conversion[421] = 314; - conversion[422] = 315; - conversion[423] = 316; - conversion[424] = 317; - conversion[425] = 318; - conversion[426] = 319; - conversion[64] = 320; - conversion[3002] = 320; - conversion[3001] = 320; - - // Boxes - conversion[2011] = 400; - conversion[2012] = 400; - conversion[48] = 402; - conversion[2002] = 403; - conversion[2018] = 404; - conversion[35] = 405; - conversion[2028] = 406; - conversion[25] = 407; - conversion[2022] = 408; - conversion[41] = 409; - conversion[2005] = 410; - conversion[78] = 411; - conversion[3000] = 412; - - // Interactive Objects - conversion[33] = 500; - conversion[86] = 501; - conversion[3006] = 502; -// conversion[?] = 520; - conversion[23] = 521; - conversion[67] = 522; - conversion[68] = 523; - conversion[32] = 540; - conversion[30] = 541; - conversion[28] = 550; - conversion[79] = 551; - conversion[5004] = 552; - conversion[65] = 553; - conversion[66] = 554; - conversion[2015] = 555; - conversion[38] = 556; - conversion[20] = 557; - conversion[39] = 558; - - // Special Placement Patterns - conversion[84] = 600; - conversion[44] = 601; - conversion[76] = 602; - conversion[77] = 603; - conversion[47] = 604; - conversion[2007] = 605; - conversion[2048] = 606; - conversion[2010] = 607; - conversion[2046] = 608; - conversion[2047] = 609; - - // Powerup Indicators/Environmental Effects/Miscellany - conversion[2026] = 700; - conversion[2024] = 701; - conversion[2023] = 702; - conversion[2045] = 703; - conversion[83] = 704; - conversion[2019] = 705; - conversion[2025] = 706; - conversion[27] = 707; - conversion[14] = 708; - conversion[43] = 709; - conversion[8] = 750; - conversion[5003] = 751; - conversion[5007] = 752; - conversion[18] = 753; - conversion[5001] = 754; - conversion[5002] = 755; - conversion[2003] = 756; - - // Greenflower Scenery - conversion[36] = 800; - conversion[70] = 801; - conversion[73] = 802; - conversion[74] = 804; - conversion[75] = 805; - - // Techno Hill Scenery - conversion[2035] = 900; - conversion[2006] = 901; - - // Deep Sea Scenery - conversion[81] = 1000; - - // Castle Eggman Scenery - conversion[49] = 1100; - conversion[24] = 1101; - conversion[52] = 1102; - conversion[2001] = 1103; - - // NiGHTS Items - conversion[72] = 1700; - conversion[61] = 1701; - conversion[46] = 1702; - conversion[60] = 1703; - conversion[82] = 1704; - conversion[57] = 1705; - conversion[37] = 1706; - conversion[3007] = 1707; - conversion[3008] = 1708; - conversion[3009] = 1709; - conversion[40] = 1710; - - // Mario Items - conversion[10005] = 1800; - conversion[10000] = 1801; - conversion[10001] = 1802; - conversion[50] = 1803; - conversion[10] = 1804; - conversion[29] = 1805; - conversion[19] = 1806; - conversion[12] = 1807; - conversion[10002] = 1808; - conversion[10003] = 1809; - conversion[10004] = 1810; - - // Christmas Items - conversion[5] = 1850; - conversion[13] = 1851; - conversion[6] = 1852; -} - -static inline void InitializeSectorConversionTable(void) -{ - memset(conversion, 0, sizeof(conversion)); - - // Player starts - conversion[690] = -1; - conversion[691] = -1; - conversion[692] = -1; - conversion[693] = -1; - conversion[694] = -1; - conversion[695] = -1; - conversion[696] = -1; - conversion[697] = -1; - conversion[698] = -1; - conversion[699] = -1; - conversion[700] = -1; - conversion[701] = -1; - conversion[702] = -1; - conversion[703] = -1; - conversion[704] = -1; - conversion[705] = -1; - conversion[706] = -1; - conversion[707] = -1; - conversion[708] = -1; - conversion[709] = -1; - conversion[710] = -1; - conversion[711] = -1; - conversion[981] = -1; - conversion[986] = -1; - conversion[8] = -1; - conversion[17] = -1; - conversion[519] = 3 + (512 << 8); - conversion[984] = 2 + (512 << 8); - - // Section 1 - conversion[11] = 1; - conversion[983] = 2; - conversion[7] = 3; - conversion[18] = 4; - conversion[4] = 5; - conversion[16] = 6; - conversion[5] = 7; - conversion[10] = 8; - conversion[978] = 9; - conversion[980] = 10; - conversion[9] = 11; - conversion[6] = 12; - conversion[992] = 13; - conversion[996] = 14; - conversion[14] = 15; - - // Section 2 - conversion[971] = 1 << 4; - conversion[972] = 2 << 4; - conversion[973] = 3 << 4; - conversion[974] = 4 << 4; - conversion[975] = 5 << 4; - conversion[967] = 6 << 4; - conversion[968] = 7 << 4; - conversion[970] = 8 << 4; - conversion[666] = 9 << 4; - conversion[990] = 10 << 4; - conversion[991] = 11 << 4; - - // Section 3 - conversion[256] = 1 << 8; - conversion[512] = 2 << 8; - conversion[768] = 3 << 8; - conversion[985] = 4 << 8; - conversion[976] = 5 << 8; - conversion[977] = 6 << 8; - conversion[1500] = 7 << 8; - conversion[1501] = 8 << 8; - conversion[1502] = 9 << 8; - conversion[1503] = 10 << 8; - conversion[1504] = 11 << 8; - conversion[1505] = 12 << 8; - conversion[1506] = 13 << 8; - conversion[1507] = 14 << 8; - conversion[1508] = 15 << 8; - - // Section 4 - conversion[993] = 1 << 12; - conversion[33] = 2 << 12; - conversion[982] = 2 << 12; - conversion[987] = 2 << 12; - conversion[995] = 2 << 12; - conversion[988] = 3 << 12; - conversion[989] = 4 << 12; - conversion[997] = 5 << 12; - conversion[969] = 6 << 12; - conversion[979] = 7 << 12; - conversion[998] = 8 << 12; - conversion[999] = 9 << 12; - conversion[994] = 10 << 12; -} - -static inline void InitializeLinedefConversionTable(void) -{ - memset(conversion, 0, sizeof(conversion)); - - // Old Water Removed - conversion[14] = -1; - - // Level Parameters/Misc: - conversion[64] = 1; - conversion[71] = 2; - conversion[18] = 3; - conversion[65] = 4; - conversion[63] = 5; - conversion[73] = 6; - conversion[66] = 7; - - // Level-Load Effects: - conversion[26] = 50; - conversion[24] = 51; - conversion[88] = 52; - conversion[2] = 53; - conversion[3] = 54; - conversion[4] = 55; - conversion[6] = 56; - conversion[7] = 57; - conversion[8] = 58; - conversion[232] = 59; - conversion[233] = 60; - conversion[43] = 61; - conversion[50] = 62; - conversion[242] = 63; - - // Floor-Over-Floors: - conversion[25] = 100; - conversion[33] = 101; - conversion[44] = 102; - conversion[69] = 103; - conversion[51] = 104; - conversion[57] = 105; - conversion[48] = 120; - conversion[45] = 121; - conversion[75] = 122; - conversion[74] = 123; - conversion[59] = 140; - conversion[81] = 141; - conversion[77] = 142; - conversion[38] = 150; - conversion[68] = 151; - conversion[72] = 152; - conversion[34] = 160; - conversion[36] = 170; - conversion[35] = 171; - conversion[79] = 172; - conversion[80] = 173; - conversion[82] = 174; - conversion[83] = 175; - conversion[39] = 176; - conversion[1] = 177; - conversion[37] = 178; - conversion[42] = 179; - conversion[40] = 180; - conversion[89] = 190; - conversion[90] = 191; - conversion[91] = 192; - conversion[94] = 193; - conversion[92] = 194; - conversion[93] = 195; - conversion[49] = 200; - conversion[47] = 201; - conversion[46] = 202; - conversion[62] = 220; - conversion[52] = 221; - conversion[67] = 222; - conversion[58] = 223; - conversion[41] = 250; - conversion[54] = 251; - conversion[76] = 252; - conversion[86] = 253; - conversion[55] = 254; - conversion[78] = 255; - conversion[84] = 256; - conversion[56] = 257; - conversion[53] = 258; - conversion[87] = 259; - - // Linedef Executor Triggers: - conversion[96] = 300; - conversion[97] = 301; - conversion[98] = 302; - conversion[95] = 303; - conversion[99] = 304; - conversion[19] = 305; - conversion[20] = 306; - conversion[21] = 307; - conversion[9] = 308; - conversion[10] = 309; - conversion[11] = 310; - conversion[12] = 311; - conversion[13] = 312; - conversion[15] = 313; - - // Linedef Executor Options: - conversion[101] = 400; - conversion[102] = 401; - conversion[103] = 402; - conversion[106] = 403; - conversion[107] = 404; - conversion[108] = 405; - conversion[109] = 406; - conversion[110] = 407; - conversion[111] = 408; - conversion[112] = 409; - conversion[114] = 410; - conversion[116] = 411; - conversion[104] = 412; - conversion[105] = 413; - conversion[115] = 414; - conversion[113] = 415; - conversion[119] = 416; - conversion[120] = 417; - conversion[117] = 420; - conversion[118] = 421; - conversion[121] = 422; - conversion[123] = 423; - conversion[124] = 424; - conversion[125] = 425; - conversion[122] = 426; - conversion[126] = 427; - conversion[127] = 428; - - // Scrollers/Pushers - conversion[100] = 500; - conversion[85] = 501; - conversion[254] = 502; - conversion[218] = 503; - conversion[249] = 504; - conversion[255] = 505; - conversion[251] = 510; - conversion[215] = 511; - conversion[246] = 512; - conversion[250] = 513; - conversion[214] = 514; - conversion[245] = 515; - conversion[252] = 520; - conversion[216] = 521; - conversion[247] = 522; - conversion[203] = 523; - conversion[205] = 524; - conversion[201] = 525; - conversion[253] = 530; - conversion[217] = 531; - conversion[248] = 532; - conversion[202] = 533; - conversion[204] = 534; - conversion[200] = 535; - conversion[223] = 540; - conversion[224] = 541; - conversion[229] = 542; - conversion[230] = 543; - conversion[225] = 544; - conversion[227] = 545; - conversion[228] = 546; - conversion[226] = 547; - - // Lighting - conversion[213] = 600; - - conversion[5] = 601; - conversion[60] = 602; - conversion[61] = 603; - conversion[16] = 606; - - // Translucency - conversion[284] = 900; - conversion[285] = 901; - conversion[286] = 902; - conversion[287] = 903; - conversion[288] = 904; - conversion[283] = 905; - - // Extended numbers - conversion[281] = conversion[25]; - conversion[289] = conversion[33]; - conversion[282] = conversion[26]; -} - -#ifndef _WIN32 -#include -static inline const char* _strupr(char *n) -{ - const char *m = n; - while (*n != '\0') - { - *n = toupper(*n); - n++; - } - return m; -} -#define strupr _strupr -#endif - -static inline int ConvertStarposts(char *argv[]) -{ - char syscmd[100]; - InitializeThingConversionTable(); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - short x, y, angle, type, options; - - fseek(lvlconvfile, 1, SEEK_CUR); - fseek(lvlconvfile, -1, SEEK_CUR); - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&x, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE X"); - return EXIT_FAILURE; - } - if(fread(&y, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE Y"); - return EXIT_FAILURE; - } - if(fread(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE ANGLE"); - return EXIT_FAILURE; - } - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE TYPE"); - return EXIT_FAILURE; - } - if(fread(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE FLAGS"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -6, SEEK_CUR); - - /* CHECK FOR MATCH */ - if(type == 502) - { - int numpost = options & 31; - angle %= 360; - angle += numpost * 360; - options = 0; - } - - if(fwrite(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE ANGLE"); - return EXIT_FAILURE; - } - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - if (fwrite(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE FLAGS"); - return EXIT_FAILURE; - } - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -static inline int ConvertThings(char *argv[]) -{ - char syscmd[100]; - InitializeThingConversionTable(); - - printf("NOTE: Skill settings not supported in 1.1. All of your objects\nhave been converted to appear regardless of skill level.\n"); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - short x, y, angle, type, options; - - fseek(lvlconvfile, 1, SEEK_CUR); - fseek(lvlconvfile, -1, SEEK_CUR); - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&x, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE X"); - return EXIT_FAILURE; - } - if(fread(&y, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE Y"); - return EXIT_FAILURE; - } - if(fread(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE ANGLE"); - return EXIT_FAILURE; - } - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE TYPE"); - return EXIT_FAILURE; - } - if(fread(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE FLAGS"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -6, SEEK_CUR); - - /* CHECK FOR MATCH */ - if(type != 32000 && type != 32001) // !@#$%^ Doom Builder... - { - if(type < TABLE_SIZE && conversion[type] < 0) - printf("\nThing type %d no longer supported. You will have to manually change this.", type); - else if(type < TABLE_SIZE && conversion[type] != 0) - type = conversion[type]; - else - printf("\nUnknown thing type %d!", type); - - if (type != 502 && type != 1700 && type != 1701 && type != 1702 && type != 1703 && type != 1704 && type != 1705) - { - if (options == 1 || options == 4) - { - printf("\nThing type %d on Easy or Hard only, renamed to thing type 4242.", type); - type = 4242; - } - - options &= ~7; // Strip skill settings - } - } - - if (type == 502) - { - int numpost = options & 31; - angle %= 360; - angle += numpost * 360; - options = 0; - } - - if(fwrite(&angle, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE ANGLE"); - return EXIT_FAILURE; - } - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - if (fwrite(&options, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE FLAGS"); - return EXIT_FAILURE; - } - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s THINGS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -static void ConvertFlat(char *garbage) -{ - /* CHECK FOR MATCH */ - if(!memcmp(garbage, "FLOOR0_3\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR01\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR0_6\0\0\0", 8)) - strncpy(garbage, "GFZFLR02\0\0\0", 8); - else if(!memcmp(garbage, "CEIL3_3\0\0\0\0\0", 8) || !memcmp(garbage, "GATE1\0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR03\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CEIL3_4\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR04\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR1_1\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR05\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR1_7\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR06\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR5_3\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "OLDROCK\0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SFLR5_0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR09\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SFLR6_1\0\0\0\0\0", 8) - || !memcmp(garbage, "SFLR6_4\0\0\0\0\0", 8) - || !memcmp(garbage, "SFLR7_1\0\0\0\0\0", 8) - || !memcmp(garbage, "SFLR7_4\0\0\0\0\0", 8)) - { - printf("Flat pic %s no longer supported. Use GFZFLR09 with\r\nlinedef special #7 to achieve same effect.\r\nFlat converted to GFZFLR09 for your convenience.\r\n", garbage); - strncpy(garbage, "GFZFLR09\0\0\0\0\0\0", 8); - } - else if(!memcmp(garbage, "DEM1_4\0\0\0\0\0\0", 8)) - strncpy(garbage, "GFZFLR10\0\0\0\0", 8); - - else if(!memcmp(garbage, "FLOOR3_3\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR30\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR4_5\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR31\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "OTHZW1\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR32\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "OTHZW2\0\0\0\0\0", 8)) - strncpy(garbage, "THZFLR33\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "BLOOD1\0\0", 8)) - strncpy(garbage, "LITER1\0\0", 8); - else if(!memcmp(garbage, "BLOOD2\0\0", 8)) - strncpy(garbage, "LITER2\0\0", 8); - else if(!memcmp(garbage, "BLOOD3\0\0", 8)) - strncpy(garbage, "LITER3\0\0", 8); - - else if(!memcmp(garbage, "BLUE1\0\0\0", 8)) - strncpy(garbage, "LITEB1\0\0", 8); - else if(!memcmp(garbage, "BLUE2\0\0\0", 8)) - strncpy(garbage, "LITEB2\0\0", 8); - else if(!memcmp(garbage, "BLUE3\0\0\0", 8)) - strncpy(garbage, "LITEB3\0\0", 8); - - else if(!memcmp(garbage, "GREY1\0\0\0", 8)) - strncpy(garbage, "LITEN1\0\0", 8); - else if(!memcmp(garbage, "GREY2\0\0\0", 8)) - strncpy(garbage, "LITEN2\0\0", 8); - else if(!memcmp(garbage, "GREY3\0\0\0", 8)) - strncpy(garbage, "LITEN3\0\0", 8); - - else if(!memcmp(garbage, "NUKAGE1\0\0\0", 8)) - strncpy(garbage, "LITEY1\0\0", 8); - else if(!memcmp(garbage, "NUKAGE2\0\0\0", 8)) - strncpy(garbage, "LITEY2\0\0", 8); - else if(!memcmp(garbage, "NUKAGE3\0\0\0", 8)) - strncpy(garbage, "LITEY3\0\0", 8); - - else if(!memcmp(garbage, "CEIL1_3\0\0\0\0\0", 8)) - strncpy(garbage, "CEZFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CEIL1_1\0\0\0\0\0", 8)) - strncpy(garbage, "CEZFLR10\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CEIL1_2\0\0\0\0\0", 8)) - strncpy(garbage, "CEZFLR11\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "CONS1_1\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CONS1_5\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "CONS1_7\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR0_5\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR10\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR0_7\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR11\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR1_6\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR12\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME01\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR13\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME02\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR14\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME03\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR15\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME04\0\0\0\0\0", 8)) - strncpy(garbage, "SFLR12\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "DCFLR1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR01\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCCEIL1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR02\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCPAVE\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR03\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCMANHO\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR04\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR05\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX2\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR06\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX3\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCTEX4\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCWHITE\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DCYELLOW\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR10\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DENTFLR\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR11\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DENTMETL\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR12\0\0\0\0\0\0\0", 8); // Intentionally - else if(!memcmp(garbage, "FLAT14\0\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR12\0\0\0\0\0", 8); // The same! - else if(!memcmp(garbage, "MFLR8_1\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR13\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "STEP2\0\0\0\0\0", 8)) - strncpy(garbage, "DCZFLR14\0\0\0\0\0", 8); - - - else if(!memcmp(garbage, "DEEPSEA2\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR04\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DEEPSEA3\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR05\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "DEEPSEA4\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR06\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLOOR4_6\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR07\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME14\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR08\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME15\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR09\0\0\0\0\0\0\0", 8); - else if(!memcmp(garbage, "SLIME16\0\0\0\0\0", 8)) - strncpy(garbage, "DSZFLR10\0\0\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "ERROCK\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR01\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT18\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR02\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT20\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR03\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT22\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR04\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT23\0\0\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR05\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT5_4\0\0\0\0", 8)) - strncpy(garbage, "ERZFLR06\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "FLAT10\0\0\0\0\0\0", 8)) - strncpy(garbage, "REDFLR\0\0\0\0\0", 8); - else if(!memcmp(garbage, "FLAT5\0\0\0\0\0\0", 8)) - strncpy(garbage, "ORGFLR\0\0\0\0\0", 8); - - else if(!memcmp(garbage, "MFLR8_2\0\0\0\0\0\0", 8)) - strncpy(garbage, "GREYFLR\0\0\0\0\0", 8); - else if(!memcmp(garbage, "MFLR8_4\0\0\0\0\0\0", 8)) - strncpy(garbage, "GREYFLR\0\0\0\0\0", 8); -} - -static inline int ConvertSectors(char *argv[]) -{ - char syscmd[100]; - InitializeSectorConversionTable(); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s SECTORS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - char garbage[11]; - short type; - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&garbage, sizeof(short)*2, 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE DATA BEFORE SECTOR FLATS"); - return EXIT_FAILURE; - } - - // Read floor flat first. - if(fread(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE SECTOR FLOOR FLAT"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -8, SEEK_CUR); - - garbage[8] = 0; - - ConvertFlat(garbage); - - if(fwrite(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE FLOOR FLAT"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, 0, SEEK_CUR); - - memset(garbage, 0, sizeof(garbage)); - - // Now do ceiling flat. - if(fread(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE SECTOR CEILING FLAT"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -8, SEEK_CUR); - - garbage[8] = 0; - ConvertFlat(garbage); - - if(fwrite(&garbage, 8, 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE CEILING FLAT"); - return EXIT_FAILURE; - } - - // Skip lightlevel - fseek(lvlconvfile, 1 * sizeof(short), SEEK_CUR); - - // Now do sector special. - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE SECTOR SPECIAL"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -1 * (int)sizeof(short), SEEK_CUR); - - /* CHECK FOR MATCH */ - if(conversion[type] < 0) - printf("\nSector type %d no longer supported. You will have to manually change this.", type); - else if(conversion[type] != 0) - type = conversion[type]; - else if (type != 0) - printf("\nUnknown sector type %d!", type); - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - /* skip 1 short of TOTAL CRAP */ - fseek(lvlconvfile, 1 * sizeof(short), SEEK_CUR); - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting back into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s SECTORS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -static inline int ConvertLinedefs(char *argv[]) -{ - char syscmd[100]; - InitializeLinedefConversionTable(); - - sprintf(syscmd, "lumpmod %s extract -s MAP%s LINEDEFS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - - lvlconvfile = fopen("lvlconv.tmp", "r+b"); - if(lvlconvfile == NULL) { - puts("Failed to open lvlconv.tmp."); - return EXIT_FAILURE; - } - for(;;) { - int c; - short garbage[3], type; - - c = fgetc(lvlconvfile); - if(c == EOF) break; - - fseek(lvlconvfile, -1, SEEK_CUR); - if(fread(&garbage, sizeof(short)*3, 1, lvlconvfile) < 1) { - puts("I CANNOT READ THE DATA BEFORE THE LINEDEF SPECIAL"); - return EXIT_FAILURE; - } - if(fread(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CAN'T READ THE LINEDEF TYPE"); - return EXIT_FAILURE; - } - - fseek(lvlconvfile, -1 * (int)sizeof(short), SEEK_CUR); - - /* CHECK FOR MATCH */ - if(conversion[type] < 0) - printf("\nLinedef type %d no longer supported. You will have to manually change this.", type); - else if(conversion[type] != 0) - { - if(type == 65) - printf("\nThis level contains a speed pad linedef. You will have to flip the direction of the line for it to work properly."); - - type = conversion[type]; - } - else if (type != 0) - printf("\nUnknown linedef type %d!", type); - - if(fwrite(&type, sizeof(short), 1, lvlconvfile) < 1) { - puts("I CANNOT WRITE THE TYPE"); - return EXIT_FAILURE; - } - - /* skip 3 shorts of TOTAL CRAP */ - fseek(lvlconvfile, 3 * sizeof(short), SEEK_CUR); - } - fclose(lvlconvfile); - puts("DONE, Man!.. Inserting back into WAD.\n"); - sprintf(syscmd, "lumpmod %s update -s MAP%s LINEDEFS lvlconv.tmp", - argv[1], strupr(argv[2])); - system(syscmd); - remove("lvlconv.tmp"); - return 1; -} - -int main(int argc, char *argv[]) { - if(argc != 3) { - puts("Usage: lvlconv [filename] [mapnumber]"); - puts("Example: lvlconv wadfile.wad 01"); - return EXIT_FAILURE; /* YOU FAIL IT! */ - } - - if(strlen(argv[2]) != 2 || strlen(argv[1]) > 32) { - puts("nonono you screwed it up"); - return EXIT_FAILURE; /* YOU LIKEWISE FAIL IT! */ - } -#ifdef STARPOSTS_ONLY - ConvertStarposts(argv); -#else - puts("\nConverting Things..."); - ConvertThings(argv); - puts("\nConverting Sectors..."); - ConvertSectors(argv); - puts("\nConverting Linedefs..."); - ConvertLinedefs(argv); -#endif - - puts("\nOkay, DONE!! Enjoy the NEWLY MODIFIED WAD FILE!!! HAVE A GOOD DAY!"); - return EXIT_SUCCESS; /* YOU SUCCEED AT IT! :) */ -} diff --git a/tools/LevelConverter/levelconverter.dsp b/tools/LevelConverter/levelconverter.dsp deleted file mode 100644 index 655cc3799..000000000 --- a/tools/LevelConverter/levelconverter.dsp +++ /dev/null @@ -1,88 +0,0 @@ -# Microsoft Developer Studio Project File - Name="levelconverter" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=levelconverter - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "levelconverter.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "levelconverter.mak" CFG="levelconverter - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "levelconverter - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "levelconverter - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "levelconverter - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 - -!ELSEIF "$(CFG)" == "levelconverter - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept - -!ENDIF - -# Begin Target - -# Name "levelconverter - Win32 Release" -# Name "levelconverter - Win32 Debug" -# Begin Source File - -SOURCE=.\levelconverter.c -# End Source File -# End Target -# End Project diff --git a/tools/LevelConverter/levelconverter.dsw b/tools/LevelConverter/levelconverter.dsw deleted file mode 100644 index 51a840c28..000000000 --- a/tools/LevelConverter/levelconverter.dsw +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "levelconverter"=.\levelconverter.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/tools/MSDfile b/tools/MSDfile deleted file mode 100644 index 287c31354..000000000 --- a/tools/MSDfile +++ /dev/null @@ -1,235 +0,0 @@ -# Doxyfile 1.4.3 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = "SRB2 MasterServer" -PROJECT_NUMBER = -OUTPUT_DIRECTORY = ../doc/MasterServer -CREATE_SUBDIRS = YES -OUTPUT_LANGUAGE = English -USE_WINDOWS_ENCODING = YES -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -DETAILS_AT_TOP = NO -INHERIT_DOCS = YES -DISTRIBUTE_GROUP_DOC = NO -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 8 -ALIASES = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -SUBGROUPING = YES -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_STATIC = YES -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = NO -HIDE_SCOPE_NAMES = NO -SHOW_INCLUDE_FILES = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_BY_SCOPE_NAME = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_DIRECTORIES = YES -FILE_VERSION_FILTER = -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = ./masterserver -FILE_PATTERNS = *.cpp \ - *.h -RECURSIVE = NO -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = * -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = YES -INLINE_SOURCES = YES -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -USE_HTAGS = NO -VERBATIM_HEADERS = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = NO -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = YES -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = YES -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = C:/Dev/include -INCLUDE_FILE_PATTERNS = -PREDEFINED = HWRENDER \ - DIRECTFULLSCREEN \ - HW3SOUND -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = NO -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -DOT_PATH = -DOTFILE_DIRS = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -MAX_DOT_GRAPH_DEPTH = 1000 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO diff --git a/tools/PHPD b/tools/PHPD deleted file mode 100644 index d2877f4e3..000000000 --- a/tools/PHPD +++ /dev/null @@ -1,239 +0,0 @@ -# Doxyfile 1.4.3 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = "SRB2 MasterServer IRC Bot and PHP stuff" -PROJECT_NUMBER = -OUTPUT_DIRECTORY = ../doc/IRC_Bot -CREATE_SUBDIRS = YES -OUTPUT_LANGUAGE = English -USE_WINDOWS_ENCODING = YES -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -DETAILS_AT_TOP = NO -INHERIT_DOCS = YES -DISTRIBUTE_GROUP_DOC = NO -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 8 -ALIASES = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -SUBGROUPING = YES -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_STATIC = YES -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = NO -HIDE_SCOPE_NAMES = NO -SHOW_INCLUDE_FILES = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_BY_SCOPE_NAME = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_DIRECTORIES = YES -FILE_VERSION_FILTER = -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = ./ -FILE_PATTERNS = *.php \ - *.php3 \ - *.inc \ - *.dox -RECURSIVE = YES -EXCLUDE = ./IRC_Bot/SmartIRC.php -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = */IRC_Bot/magpierss/* \ - */IRC_Bot/SmartIRC/* \ - */IRC_Bot/*SRB2MS_Pass.php -EXAMPLE_PATH = -EXAMPLE_PATTERNS = * -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = YES -INLINE_SOURCES = YES -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -USE_HTAGS = NO -VERBATIM_HEADERS = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = NO -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = YES -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_LINKS = YES -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = C:/Dev/include -INCLUDE_FILE_PATTERNS = -PREDEFINED = HWRENDER \ - DIRECTFULLSCREEN \ - HW3SOUND -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = NO -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -DOT_PATH = -DOTFILE_DIRS = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -MAX_DOT_GRAPH_DEPTH = 1000 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::additions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO diff --git a/tools/anglechk.c b/tools/anglechk.c deleted file mode 100644 index 7f56abff7..000000000 --- a/tools/anglechk.c +++ /dev/null @@ -1,364 +0,0 @@ -/* - * anglechk.c - * - * Copyright 2007 Alam Arias - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include -#ifdef _MSC_VER -#include -#endif -#include "../src/tables.h" -#define NO_M -#include "../src/m_fixed.c" -#define FIXEDPOINTCONV - -// With angle_t, -// 360 deg = 2^32 -// 45 deg = 2^29 -// 1 deg = 2^29 / 45 -// To convert an angle to a fixed-point number of degrees, then, use -// fixed = angle * FRACUNIT / ((1<<29) / 45) -// But, done literally like that, this will overflow. -// It's mathematically equivalent to -// fixed = angle * (1<>(29-FRACBITS)) -// fixed = (angle>>(29-FRACBITS)) * 45 - -#define ANGLE_TO_FIXED(a) (fixed_t)(((a)>>(29-FRACBITS))*45) -#define FIXED_TO_ANGLE(x) (angle_t)(((x)/45)<<(29-FRACBITS)) - -/* -Old code that failed if FRACBITS was not 16. -In particular, the use of FRACUNIT in the definition of ANGLE_F is completely -wrong. The value wanted actually happens to be 65536 due to the definition -of angle_t (it's specified so that 360 degrees = 2^32, to take advantage of -modular arithmetic). That 65536 has nothing whatsoever to do with the setting -of FRACUNIT. - -#define ANGF_D 8192 -#define ANGF_N 45 -#define ANGLE_F (ANGF_N*FRACUNIT/ANGF_D) -#define FIXED_TO_ANGLE(x) (angle_t)FixedDiv(x, ANGLE_F) // angle_t = FixedDiv(fixed_t, ANGLE_F) -#define ANGLE_TO_FIXED(x) FixedMul((fixed_t)(x), ANGLE_F) // fixed_t = FixedMul(angle_t, ANGLE_F) -*/ - -static fixed_t AngleFixed204(angle_t af) -{ - const fixed_t cfn = 180*FRACUNIT; - if (af == 0) - return 0; - else if (af > ANGLE_180) - return cfn + ANGLE_TO_FIXED(af - ANGLE_180); - else if (af < ANGLE_180) - return ANGLE_TO_FIXED(af); - else return cfn; -} - -static inline angle_t FixedAngleC204(fixed_t fa, fixed_t factor) -{ -#if 0 //FixedMod off? - const boolean neqda = da < 0, neqfa = fa < 0; - const fixed_t afactor = abs(factor); - angle_t ra = ANGLE_180; - - if (factor == 0) - return FixedAngle204(fa); - else if (fa == 0) - return 0; - - if (neqfactor) - { - const fixed_t maf = FixedDiv(afactor, ANGLE_F); - const fixed_t cfn = FixedMul(360*FRACUNIT, afactor), hcfn = (cfn/2); - const fixed_t fam = FixedMod(fa, cfn); - - if (fam > hcfn) - ra = ANGLE_180 + (angle_t)FixedMul(fam - hcfn, maf); - else if (fam < hcfn) - ra = (angle_t)FixedMul(fam, maf); - } - else - { - const fixed_t maf = FixedMul(afactor, ANGLE_F); - const fixed_t cfn = FixedDiv(360*FRACUNIT, afactor), hcfn = (cfn/2); - const fixed_t fam = FixedMod(fa, cfn); - - if (fam > hcfn) - ra = ANGLE_180 + (angle_t)FixedDiv(fam - hcfn, maf); - else if (fam < hcfn) - ra = (angle_t)FixedDiv(fam, maf); - } - - if (neqfa) - ra = ANGLE_MAX-ra; - - return ra; -#else - if (factor == 0) - return FixedAngle(fa); - else if (factor > 0) - return (angle_t)((FIXED_TO_FLOAT(fa)/FIXED_TO_FLOAT(factor))*(ANGLE_45/45)); - else - return (angle_t)((FIXED_TO_FLOAT(fa)*FIXED_TO_FLOAT(-factor))*(ANGLE_45/45)); -#endif -} - -angle_t FixedAngle(fixed_t fa) -{ -#if 0 //FixedMod off? - const boolean neqfa = fa < 0; - const fixed_t cfn = 180*FRACUNIT; - const fixed_t fam = FixedMod(fa, 360*FRACUNIT); - angle_t ra = ANGLE_180; - - if (fa == 0) - return 0; - - if (fam > cfn) - ra = ANGLE_180+FIXED_TO_ANGLE(fam-cfn); - else if (fam < cfn) - ra = FIXED_TO_ANGLE(fam); - - if (neqfa) - ra = ANGLE_MAX-ra; - - return ra; -#else - return (angle_t)(FIXED_TO_FLOAT(fa)*(ANGLE_45/45)); -#endif -} - -fixed_t AngleFixed205(angle_t af) -{ -#ifdef FIXEDPOINTCONV - angle_t wa = ANGLE_180; - fixed_t wf = 180*FRACUNIT; - fixed_t rf = 0*FRACUNIT; - //const angle_t adj = 0x2000; - - //if (af < adj) // too small to notice - //return rf; - - while (af) - { - while (af < wa) - { - wa /= 2; - wf /= 2; - } - rf += wf; - af -= wa; - } - - return rf; -#else - const fixed_t cfn = 180*FRACUNIT; - if (af == 0) - return 0; - else if (af > ANGLE_180) - return cfn + ANGLE_TO_FIXED(af - ANGLE_180); - else if (af < ANGLE_180) - return ANGLE_TO_FIXED(af); - else return cfn; -#endif -} - -#ifdef FIXEDPOINTCONV -static FUNCMATH angle_t AngleAdj(const fixed_t fa, const fixed_t wf, - angle_t ra) -{ - const angle_t adj = 0x77; - const boolean fan = fa < 0; - const fixed_t sl = FixedDiv(fa, wf*2); - const fixed_t lb = FixedRem(fa, wf*2); - const fixed_t lo = (wf*2)-lb; - - if (ra == 0) - { - if (lb == 0) - { - ra = FixedMul(FRACUNIT/512, sl); - if (ra > FRACUNIT/64) - return ANGLE_MAX-ra+1; - return ra; - } - else if (lb > 0) - return ANGLE_MAX-FixedMul(lo*FRACUNIT, adj)+1; - else - return ANGLE_MAX-FixedMul(lo*FRACUNIT, adj)+1; - } - - if (fan) - return ANGLE_MAX-ra+1; - else - return ra; -} -#endif - -angle_t FixedAngleC205(fixed_t fa, fixed_t factor) -{ -#ifdef FIXEDPOINTCONV - angle_t wa = ANGLE_180; - fixed_t wf = 180*FRACUNIT; - angle_t ra = 0; - const fixed_t cfa = fa; - fixed_t cwf = wf; - - if (fa == 0) - return 0; - - if (factor == 0) - return FixedAngle(fa); - else if (factor > 0) - cwf = wf = FixedMul(wf, factor); - else if (factor < 0) - cwf = wf = FixedDiv(wf, -factor); - - fa = abs(fa); - - while (fa) - { - while (fa < wf) - { - wa /= 2; - wf /= 2; - } - ra = ra + wa; - fa = fa - wf; - } - - return AngleAdj(cfa, cwf, ra); -#else - if (factor == 0) - return FixedAngle(fa); - - //fa = FixedMod(fa, 360*FRACUNIT); - - if (factor > 0) - return (angle_t)((FIXED_TO_FLOAT(fa)/FIXED_TO_FLOAT(factor))*(ANGLE_45/45)); - else - return (angle_t)((FIXED_TO_FLOAT(fa)*FIXED_TO_FLOAT(-factor))*(ANGLE_45/45)); -#endif -} - -angle_t FixedAngle205(fixed_t fa) -{ -#ifdef FIXEDPOINTCONV - angle_t wa = ANGLE_180; - fixed_t wf = 180*FRACUNIT; - angle_t ra = 0; - const fixed_t cfa = fa; - const fixed_t cwf = wf; - - if (fa == 0) - return 0; - - fa = abs(fa); - - while (fa) - { - while (fa < wf) - { - wa /= 2; - wf /= 2; - } - ra = ra + wa; - fa = fa - wf; - } - - return AngleAdj(cfa, cwf, ra); -#else - //fa = FixedMod(fa, 360*FRACUNIT); - - if (fa == 0) - return 0; - - return (angle_t)(FIXED_TO_FLOAT(fa)*(ANGLE_45/45)); -#endif -} - -int main(int argc, char** argv) -{ - fixed_t f, f204, f205; - INT64 a; - angle_t a204, a205; - fixed_t CF = 40*FRACUNIT; - int err = 0; - (void)argc; - (void)argv; - - err = 0x29; //41 - - if (1) - for (a = 0; a < ANGLE_MAX; a += 0x1) - { - f204 = AngleFixed204((angle_t)a); - f205 = AngleFixed205((angle_t)a); - if (f204 != f205 && (abs(f204-f205) > err || f204 == 0 || f205 == 0)) - { - printf("Angle: %u, %d, %d, %d\n", (angle_t)a, f204, f205, f204-f205); - //err = abs(f204-f205); - } - } - - //err = FixedDiv(FRACUNIT, 120*FRACUNIT); // 547 - err = FixedDiv(FRACUNIT, 62*FRACUNIT); //1059 - - if (1) - for (f = FRACUNIT*-720; f < FRACUNIT*720; f += 1) - { - a204 = FixedAngle(f); - a205 = FixedAngle205(f); - if (a204 != a205 && (abs(a204-a205) > err || a204 == 0 || a205 == 0)) - { - printf("Fixed: %f, %u, %u, %d\n", FIXED_TO_FLOAT(f), a204, a205, a204-a205); - err = abs(a204-a205); - } - } - - //err = FixedDiv(FRACUNIT, 316*FRACUNIT); //207 - err = FixedDiv(FRACUNIT, 125*FRACUNIT); //526 - - if (1) - for (f = FixedMul(FRACUNIT*-720, CF); f < FixedMul(FRACUNIT*720, CF); f += FRACUNIT/16) - { - a204 = FixedAngleC204(f, CF); - a205 = FixedAngleC205(f, CF); - if (a204 != a205 && (abs(a204-a205) > err || a204 == 0 || a205 == 0)) - { - printf("FixedC: %f, %u, %u, %d\n", FIXED_TO_FLOAT(f), a204, a205, a204-a205); - //err = abs(a204-a205); - } - } - - return 0; -} - -static void *cpu_cpy(void *dest, const void *src, size_t n) -{ - return memcpy(dest, src, n); -} - -void *(*M_Memcpy)(void* dest, const void* src, size_t n) = cpu_cpy; - -void I_Error(const char *error, ...) -{ - (void)error; - exit(-1); -} diff --git a/tools/convert.c b/tools/convert.c deleted file mode 100644 index 0ab0cb132..000000000 --- a/tools/convert.c +++ /dev/null @@ -1,35 +0,0 @@ -// convert corona.raw in a pic_t as corona2.raw - -#include - -typedef struct -{ - short width; - char reserved0; // set to 0 - char mode; // see pic_mode_t above - short height; - short reserved1; // set to 0 -} pic_t; - -void main(int argc, char *argv[]) -{ - int i, j, k; - char buf1[256][256], buf2[256][256][2]; - pic_t pic = {256, 0, 2, 256, 0}; - FILE *g; - - FILE *f = fopen("corona.raw", "rb"); - fread(buf1, 256*256, 1, f); - fclose(f); - - g = fopen("corona2.raw", "wb"); - for (i = 0; i < 256; i++) - for (j = 0; j < 256; j++) - { - buf2[i][j][0] = buf1[i][j]; - buf2[i][j][1] = buf1[i][j]; - } - fwrite(&pic, sizeof (pic_t), 1, g); - fwrite(buf2, sizeof (buf2), 1, g); - fclose(g); -} diff --git a/tools/dircomp2.c b/tools/dircomp2.c deleted file mode 100644 index 96a55f36f..000000000 --- a/tools/dircomp2.c +++ /dev/null @@ -1,1028 +0,0 @@ -//----------------------------------------------------------------------------- -// -// Copyright (C) 1998-2000 by Boris Pereira. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include"keys.h" - - -#define true 1 -#define false 0 - -#define MAXLINE 32768 -#define MAXLENLINE 4096 -#define SCREENWIDTH 80 - -typedef struct { - int lines; - char *line[MAXLINE]; -} textfile_t; - -char tempfilename[255],editor[128]="c:\\program files\\ultraedit\\uedit32.exe"; -int sameline=3,tab1=8,tab2=8; -int screenline=25; -textfile_t f1,f2; -int nonewfile = false; -int compspace = false; - -unsigned short colornormal = ( BLACK<<4) + LIGHTGRAY; -unsigned short colortitle = ( BLACK<<4) + WHITE; -unsigned short colortext = ( BLACK<<4) + DARKGRAY; -unsigned short colordiff = ( BLACK<<4) + LIGHTRED; -unsigned short colorkeys = ( BLACK<<4) + LIGHTCYAN; - - -// compare directorys -void CompareDir(char *dir1,char *dir2); - -// compare directorys this one check only for missing file -void CompareDir2(char *dir1,char *dir2); - -// compare files -void CompareFile(char *filename1,char *filename2); - -// copy a file -void fcopy(char *filename1,char *filename2); - -// recursive delete a dir -void dirunlink(char *dirname); - -// recursive copy a dir -void copydir(char *dirname1,char *dirname2); - -void Quit(char *f,...) -{ - va_list argptr; - - // put message to stderr - va_start (argptr,f); - fprintf (stderr, "Error: "); - vfprintf (stderr,f,argptr); - va_end (argptr); - - fflush( stderr ); - exit(-1); -} - -int CheckParm(int argc, char *argv[], char *param ) -{ - int i; - for(i=1;i []\n\n" - " Options\n" - " -------\n" - " -t1 n : change tab size for directory 1 (default 8)\n" - " -t2 n : change tab size for directory 2 (default 8)\n" - " -l n : use n same line to resynchronize (default 3)\n" - " -e : use spesified editor\n" - " -nonew: don't prompt to copy/delete file\n" - " -w compress space and tab"); - - if(findfirst(argv[1],&dir,FA_DIREC)) - Quit("Error can't find %s\n",argv[1]); - - if(findfirst(argv[2],&dir,FA_DIREC)) - Quit("Error can't find %s\n",argv[2]); - - if(argc>2) - { - i=CheckParm(argc,argv,"-t1"); - if(i) tab1=atoi(argv[i+1]); - i=CheckParm(argc,argv,"-t2"); - if(i) tab2=atoi(argv[i+1]); - i=CheckParm(argc,argv,"-l"); - if(i) sameline=atoi(argv[i+1]); - i=CheckParm(argc,argv,"-e"); - if(i) strcpy(editor,argv[i+1]); - nonewfile=CheckParm(argc,argv,"-nonew"); - compspace=CheckParm(argc,argv,"-w"); - } - - _set_screen_lines(50); - screenline=50; - // desable blink color so we can use darkcolor for background - //outportb(0x3b8,5); - intensevideo(); - - tmp=getenv("temp"); - if(!tmp) - tmp=getenv("TEMP"); - if(!tmp) - tmp=getenv("tmp"); - if(!tmp) - tmp=getenv("TMP"); - if(tmp) - { - strcpy(tempfilename,tmp); - if(tempfilename[strlen(tempfilename)]!='\\') - strcat(tempfilename,"\\"); - } - else - tempfilename[0]='\0'; - strcat(tempfilename,"dircmp$$.tmp"); - - CompareDir(argv[1],argv[2]); - - if(!nonewfile) - // just for file in the directory 2 and not in the 1 - CompareDir2(argv[1],argv[2]); - - return 0; -} - -char *fileextension(char *filename) -{ - static char nullextension=0; - int i; - i = strlen(filename)-1; - while(i>0 && filename[i]!='.') i--; - if( filename[i]=='.' ) - return filename+i+1; - // else - return &nullextension; -} - -void CompareDir(char *dirname1,char *dirname2) -{ - struct ffblk dir; - char filter[20]="\\*.*"; - char tempstr[255]; - int finish; - - strcpy(tempstr,dirname1); - strcat(tempstr,filter); - - printf("Comparing %s and %s\n",dirname2,dirname1); - - // enter in directorys first - finish=findfirst(tempstr,&dir,FA_DIREC); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - - if(dir.ff_attrib & FA_DIREC) - { - if(dir.ff_name[0]!='.' && strcmp(dir.ff_name,"CVS")!=0) - { - int check,choice; - check=access(tempstr3,F_OK); - if( check ) - { - printf("\nDirectory missing : %s\n" - "Delete %s ? (Y/N)\n",tempstr3,tempstr2); - do { - choice=getch(); - } while(choice!='y' && choice!='n' - && choice!='Y' && choice!='N'); - - if( choice=='y' || choice=='Y' ) - dirunlink(tempstr2); - } - else - CompareDir(tempstr2,tempstr3); - } - } - finish=findnext(&dir); - } - - finish=findfirst(tempstr,&dir,0); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - if((dir.ff_attrib & FA_DIREC)==0) - { - int check; - char *ext; - - ext = fileextension(dir.ff_name); - if( !(stricmp(ext,"dsp")==0 || - stricmp(ext,"dep")==0 || - stricmp(ext,"dsw")==0 || - stricmp(ext,"ncb")==0 || - stricmp(ext,"bmp")==0 || - stricmp(ext,"opt")==0 || - stricmp(ext,"plg")==0 || - stricmp(ext,"ico")==0 || - stricmp(ext,"rc" )==0 || - stricmp(ext,"o" )==0 || - stricmp(ext,"bat")==0 || - stricmp(ext,"obj")==0 )) - { - printf("Comparing %s and %s\n",tempstr2,tempstr3); - check=access(tempstr3,F_OK); - - if(check) - { - // seconde file not found - int choice; - if(!nonewfile) - { - printf("\nFile missing : %s\n" - "Delete %s ? (Y/N)\n",tempstr3,tempstr2); - do { - choice=getch(); - } while(choice!='y' && choice!='n' - && choice!='Y' && choice!='N'); - - if(choice=='y' || choice=='Y') - unlink(tempstr2); - } - } - else - { - struct stat fs1,fs2; - stat(tempstr2,&fs1); - stat(tempstr3,&fs2); - - if(fs1.st_atime!=fs2.st_atime || fs1.st_size!=fs2.st_size) - CompareFile(tempstr2,tempstr3); - } - printf("\n"); - } - } - finish=findnext(&dir); - } -} - -// find file in dir2 but not in dir1 -void CompareDir2(char *dirname1,char *dirname2) -{ - struct ffblk dir; - char filter[20]="\\*.*"; - char tempstr[255]; - int finish; - - strcpy(tempstr,dirname2); - strcat(tempstr,filter); - - printf("Comparing %s and %s\n",dirname1,dirname2); - - finish=findfirst(tempstr,&dir,FA_DIREC); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - - if(dir.ff_attrib & FA_DIREC) - { - if(dir.ff_name[0]!='.' && strcmp(dir.ff_name,"CVS")!=0) - { - int check,choice; - check=access(tempstr3,F_OK); - if( check ) - { - printf("\nDirectory missing : %s\n" - "Copy %s ? (Y/N)\n",tempstr3,tempstr2); - do { - choice=getch(); - } while(choice!='y' && choice!='n' - && choice!='Y' && choice!='N'); - - if( choice=='y' || choice=='Y' ) - copydir(tempstr2,tempstr3); - } - else - CompareDir2(tempstr2,tempstr3); - } - } - finish=findnext(&dir); - } - - finish=findfirst(tempstr,&dir,FA_DIREC); - while(!finish) - { - char tempstr2[255],tempstr3[255]; - - strcpy(tempstr2,dirname1); - strcat(tempstr2,"\\"); - strcat(tempstr2,dir.ff_name); - - strcpy(tempstr3,dirname2); - strcat(tempstr3,"\\"); - strcat(tempstr3,dir.ff_name); - - if((dir.ff_attrib & FA_DIREC)==0) - { - char *ext = fileextension(dir.ff_name); - if( !(stricmp(ext,"dsp")==0 || - stricmp(ext,"dep")==0 || - stricmp(ext,"dsw")==0 || - stricmp(ext,"ncb")==0 || - stricmp(ext,"bmp")==0 || - stricmp(ext,"opt")==0 || - stricmp(ext,"plg")==0 || - stricmp(ext,"ico")==0 || - stricmp(ext,"rc" )==0 || - stricmp(ext,"o" )==0 || - stricmp(ext,"bat")==0 || - stricmp(ext,"obj")==0 ) && - // check if file exist in dir1 - access(tempstr2,F_OK)) - { - int choice; - - printf("File %s found in %s but not in %s\n" - "Copy it ? (y/n)\n",tempstr3,dirname2,dirname1); - do { - choice=getch(); - } while(choice!='y' && choice!='n'); - - if(choice=='y') - fcopy(tempstr2,tempstr3); - - return; - - - } - } - finish=findnext(&dir); - } -} - -// convert tab to space -char *tabconv(char *c,int tabsize) -{ - static char buf[MAXLENLINE]; - int i=0,j=0; - - while(c[i]) - { - if(c[i]=='\t') - { - do { - buf[j++]=' '; - } while(j % tabsize); - } - else - buf[j++]=c[i]; - i++; - } - -/* - if(j>maxline) - { - buf[maxline-1]='\n'; // trunc - j=maxline; - } -*/ - buf[j]=0; - - return buf; -} - -void tabconv2(textfile_t *f,int start,int stop) -{ - static char buf[MAXLENLINE]; - char *c; - int i,j,k; - - for(k=start;k<=stop;k++) - { - c=f->line[k]; - i=j=0; - while(c[i]) - { - if(c[i]=='\t' && c[i+1]=='\t') - { - buf[j++]='\t'; - } - else - if(c[i]=='\t') - do { buf[j++]=' '; } while(j & 3); - else - buf[j++]=c[i]; - i++; - } - buf[j]=0; - free(f->line[k]); - f->line[k]=(char *)malloc(j); - strcpy(f->line[k],buf); - } -} - -int c; - -void initmyfgets( FILE *stream ) -{ - c = fgetc(stream); -} - -// convert any f*** format to the good one -char *myfgets( char *string, int n, FILE *stream ) -{ - int i=0; - char *s=string; - if( c==EOF ) - return NULL; - while( i=MAXLINE) - Quit("File %s too big, more than %d lines\n",filename,MAXLINE); - if(!myfgets(buf,MAXLENLINE,f)) - break; - if( convtab ) - strcpy(buf,tabconv(buf,tabsize)); - file->line[i]=(char *)malloc(strlen(buf)+1); - strcpy(file->line[i],buf); - i++; - } - fclose(f); - - file->lines=i; - - for(;iline[i]=eofline; -} - -void FreeTextFile(textfile_t *file) -{ - int i; - - for(i=0;ilines;i++) - free(file->line[i]); - - file->lines = 0; -} - -// afficher une partie de fichier en partant de startline jusqu'a stop line -// affiche les ligne redbeg jusqua redstop en rouge -// decale le text vers la droite de offset caractere -void PrintfBlock(textfile_t *f,int start,int redbeg,int redstop,int stop, int offset) -{ - int i,l; - char save80,save81,*p; - - if(start<0) - start=0; - - for(i=start;i<=stop;i++) - { - if(i>=redbeg && i<=redstop) - textattr(colordiff); - else - textattr(colortext); - if( f->line[i] ) - l=strlen(f->line[i]); - else - l=0; - if(l<=offset) - { - cprintf("\n\r"); - continue; - } - p=&(f->line[i][offset]); - l-=offset; - if( l>SCREENWIDTH-1) - { - save80=p[SCREENWIDTH-2]; - save81=p[SCREENWIDTH-1]; - if( p[SCREENWIDTH-2]!='\0') - p[SCREENWIDTH-2]='\n'; - p[SCREENWIDTH-1]='\0'; - cprintf("%s\r",p); - p[SCREENWIDTH-2]=save80; - p[SCREENWIDTH-1]=save81; - } - else - cprintf("%s\r",p); - } -} - -// copy only the syntax, compress all spacing in 1 space -char *delspace(char *s) -{ -static char buf[MAXLENLINE]; - int i=0,j=0; - - if( !compspace ) - { - // remove just trailing space - strcpy(buf, s); - for(i = strlen(buf)-1;(buf[i]==' ' || buf[i]=='\n' || buf[i]=='\r') && i>=0;i--) - buf[i]='\0'; - buf[i+1]='\n'; - buf[i+2]='\0'; - return buf; - } - - while(s[i]!='\n' && s[i]) - { - if(s[i]==' ') - { - while(s[i]==' ' && s[i]!='\n' && s[i]) { i++; } - if(s[i]!='\n' && s[i]) - buf[j++]=' '; - } - else - buf[j++]=s[i++]; - } - buf[j++]='\n'; - buf[j]='\0'; - - return buf; -} - -int LineCmp(char **a1,char **a2,int linetocmp) -{ - char buf[MAXLENLINE]; - char buf2[MAXLENLINE]; - int i; - - for(i=0;iline[line1+i-j] - ,&f2->line[line2+j],sameline)) - { - *ri=i-j; - *rj=j; - - return; - } - animcount++; - animcount&=0xF; - // not to mush printf this slowdown a lot - if( (animcount&3)==0 ) - cprintf("\b%c",anim[animcount>>2]); - } - Quit("Too mush difference between the files\n"); -} - -void cnprintf(char *s,int n) -{ - int i; - for(i=0;i%c%c] [-]%d lines[+] [u]ndo [e]dit [c]ompress space",27,26,sameline); - fflush(stdout); - textattr(colornormal); -} - -// copy file date of source to dest -void CopyFileDate(char *dest,char *source) -{ - struct stat fs1; - struct utimbuf fs2; - - stat(source,&fs1); - fs2.actime = fs1.st_mtime; - fs2.modtime = fs1.st_mtime; - - utime(dest,&fs2); -} - -void CompareFile(char *filename1,char *filename2) -{ - int i,j,choice,k,l; - int line1,line2; - FILE *outfile; - int maxlines,always,enterline=0,column=0; - int oneselected=false,twoselected=false; - - LoadTextFile(filename1,&f1,tab1); - LoadTextFile(filename2,&f2,tab2); - outfile=fopen(tempfilename,"wt"); - if( !outfile ) - Quit("Error: No way to open %s\n",tempfilename); - line1=0; - line2=0; - always=0; - maxlines=f1.lines+f2.lines+1; - -// if(maxlines1 ) { - sameline--; - Resynchronize(&f1,line1,&f2,line2,&i,&j,maxlines,sameline); - } - break; - case 'c' : - compspace = !compspace; - Resynchronize(&f1,line1,&f2,line2,&i,&j,maxlines,sameline); - break; -/* - case 't' : - tabconv2(&f1,line1,line1+i-1); - Resynchronize(&f1,line1,&f2,line2,&i,&j,maxlines,sameline); - break; -*/ - case 'p' : always=1;break; - case 'd' : always=2;break; - case 'u' : - fclose(outfile); - FreeTextFile(&f1); - FreeTextFile(&f2); - - // remove the temp file - unlink(tempfilename); - - CompareFile(filename1,filename2); - - return; - case 'e' : - { - char params[256]; - fclose(outfile); - FreeTextFile(&f1); - FreeTextFile(&f2); - - // remove the temp file - unlink(tempfilename); - - sprintf(params,"\"%s/%d\" \"%s/%d\"",filename1,line1,filename2,line2); - - spawnlp(P_WAIT,editor,params,params,NULL); - printf("\n\nHit Enter to continue\n"); - getchar(); - - CompareFile(filename1,filename2); - return; - } - } - - } while(choice!='3' && choice!='9' && always==0); - } - printf("\n"); - - if(choice=='9'|| always==1) - { - int blankline; - for(blankline=0;blankline /dev/null 2>&1 - -$(RM) $@ - $(FOR) f in $(SRC); do \ - $(SHCC) $(CPPFLAGS) $(CFLAGS) -MM $$f >> $@; \ - done --include $@ - -%.o: %.c -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ - -$(BIN): $(OBJ) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(LDFLAGS) -o $@ $(OBJ) $(LIB) - -$(STABIN): $(OBJ) -ifndef V - $(ECHO) " $(PRAR)$@" -endif - $(AR) rcs $@ $(OBJ) - -install: all install-libs install-headers - -install-libs: - $(MKDIR) $(LIBDIR) -ifndef V - $(FOR) f in $(LIBS); do \ - $(SHECHO) " $(PRINSTALL)$$f"; \ - $(SHINSTALL) $$f $(LIBDIR); \ - done -else - $(FOR) f in $(LIBS); do \ - $(SHINSTALL) $$f $(LIBDIR); \ - done -endif - $(LDCONFIG) - -install-headers: - $(MKDIR) $(INCLUDE) -ifndef V - $(FOR) f in $(HEADERS); do \ - $(SHECHO) " $(PRINSTALL)$$f"; \ - $(SHINSTALL) $$f $(INCLUDE); \ - done -else - $(FOR) f in $(HEADERS); do \ - $(SHINSTALL) $$f $(INCLUDE); \ - done -endif - -clean: -ifndef V - $(ECHO) " $(PRCLEAN)$(OBJ) $(LIBS)" -endif - -$(RM) $(OBJ) $(LIBS) - -distclean: -ifndef V - $(ECHO) " $(PRCLEAN)$(BINDIR)" -endif - -$(RM) $(BINDIR) - - -.PHONY : all install install-libs install-headers clean diff --git a/tools/libwad/examples/wadexample/Makefile b/tools/libwad/examples/wadexample/Makefile deleted file mode 100644 index 773733b06..000000000 --- a/tools/libwad/examples/wadexample/Makefile +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env make -f - -## wadexample: libwad example program. -## Copyright (C) 2011 by Callum Dickinson. -# -## This program is free software; you can redistribute it and/or -## modify it under the terms of the GNU General Public License -## as published by the Free Software Foundation; either version 2 -## of the License, or (at your option) any later version. -# -## This program is distributed in the hope that it will be useful, -## but WITHOUT ANY WARRANTY; without even the implied warranty of -## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -## GNU General Public License for more details. - -# Program name. -PRONAME = wadexample -# Program version. -PROVER = 1.0.0 - -# Program default options. -CPPFLAGS += -DPRONAME="$(PRONAME)" -DPROVER="$(PROVER)" - -# Source files and directory. -SRC = wadexample.c - -# Required libraries. -LIB = -lwad - -# -## Variables that shouldn't be edited unless -## you know what you are doing start here. -# - -# Makefile pretty text output variables. -PRCC = CC -PRINSTALL=INSTALL -PRCLEAN = CLEAN - -# Library name prefix. -LIBPFX = lib - -# Library installation directory. -PREFIX ?= /usr/local -LIBDIR := $(PREFIX)/lib -INCLUDE := $(PREFIX)/include - -# Variables created during compilation. -OBJ = $(SRC:.c=.o) -DEP = $(PRONAME).d -ifdef MINGW -BIN = $(PRONAME).exe -else -BIN = $(PRONAME) -endif - -# Compilation programs. -ECHO := echo -RM := $(RM) -r -FIND := find -GREP := grep -INSTALLX:= install -m 755 -MKDIR := mkdir -p -FOR := for -SED := sed -CC := $(CROSS_COMPILE)$(CC) - -# Shell programs. -SHECHO := $(ECHO) -SHFIND := $(FIND) -SHGREP := $(GREP) -SHINSTALL:= $(INSTALL) -SHSED := $(SED) -SHCC := $(CC) - -# Quiet compiling programs during pretty text output. -NULL := /dev/null 2>&1 -ECHO := @$(ECHO) -ifndef V -RM := @$(RM) -LDCONFIG:= @$(LDCONFIG) -FIND := @$(FIND) -GREP := @$(GREP) -INSTALL := @$(INSTALL) -MKDIR := @$(MKDIR) -FOR := @$(FOR) -SED := @$(SED) -CC := @$(CC) -endif - -# Compiler default flags. -ifdef DEBUG -CFLAGS += -g -O0 -Wall -W -endif - -# Linker flags. -#LDFLAGS += - -# -## Makefile targets. -# - -all: $(DEP) $(BIN) - -$(DEP): $(SRC) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - -$(RM) $@ - $(FOR) f in $(SRC); do \ - $(SHCC) $(CPPFLAGS) $(CFLAGS) -MM $$f >> $@; \ - done --include $@ - -%.o: %.c -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ - -$(BIN): $(OBJ) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(LDFLAGS) -o $@ $(OBJ) $(LIB) - -install: all -ifndef V - $(SHECHO) " $(PRINSTALL)$(BIN)" -endif - $(INSTALLX) $(BIN) $(INSTALLDIR) - -clean: -ifndef V - $(ECHO) " $(PRCLEAN)$(OBJ) $(DEP)" -endif - -$(RM) $(OBJ) $(DEP) - -.PHONY : all install clean diff --git a/tools/libwad/examples/wadexample/wadexample.c b/tools/libwad/examples/wadexample/wadexample.c deleted file mode 100644 index 5e35a1e4d..000000000 --- a/tools/libwad/examples/wadexample/wadexample.c +++ /dev/null @@ -1,64 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// wadexample: libwad example program. -// Copyright (C) 2011 by Callum Dickinson. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file wadconv.c -/// \brief Converts wads made for version 2.0 to 2.1. - -#include -#include -#include -#include -#include "wad.h" - -int main(int argc, char **argv) -{ - wad_uint32_t i; - - wad_t *w; - lump_t *l; - - if (argc < 2) - { - puts("Usage: wadexample [filename] [..]"); - puts("Example: example wadfile.wad wadfile2.wad"); - return EXIT_FAILURE; - } - - // Open the WAD files. - puts("Opening WADs..."); - for (i = 1; i < (unsigned)argc; i++) - { - if (!WAD_OpenWAD(argv[i])) - { - printf("Error opening WAD %s: %s\n", argv[i], WAD_Error()); - return 1; - } - } - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - { - w = WAD_WADByNum(i); - printf("List of lumps inside wad %s:\n", WAD_BaseName(w->filename)); - for (l = w->lumps; l; l = l->next) - printf("Lump #%i: %s\n", l->num, l->name); - } - - puts("Closing WADs..."); - for (i = 0; i < wad_numwads; i++) - WAD_CloseWADByNum(i); - - return EXIT_SUCCESS; -} diff --git a/tools/libwad/include/wad.h b/tools/libwad/include/wad.h deleted file mode 100644 index 298a478b7..000000000 --- a/tools/libwad/include/wad.h +++ /dev/null @@ -1,227 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file wad.h -/// \brief WAD file manipulation library. - -#ifndef __WAD_H__ -#define __WAD_H__ - -#ifdef __cplusplus -extern "C" -{ -#endif - -// -// Exact-width integer types. -// -#ifdef _MSC_VER -typedef signed __int8 wad_int8_t; -typedef unsigned __int8 wad_uint8_t; - -typedef __int16 wad_int16_t; -typedef unsigned __int16 wad_uint16_t; - -typedef __int32 wad_int32_t; -typedef unsigned __int32 wad_uint32_t; - -typedef __int64 wad_int64_t; -typedef unsigned __int64 wad_uint64_t; - -// Older Visual C++ headers don't have the Win64-compatible typedefs... -#if ((_MSC_VER <= 1200) && (!defined(DWORD_PTR))) -#define DWORD_PTR DWORD -#endif - -#if ((_MSC_VER <= 1200) && (!defined(PDWORD_PTR))) -#define PDWORD_PTR PDWORD -#endif - -#elif defined (_arch_dreamcast) -#include - -typedef signed char wad_int8_t; -typedef unsigned char wad_uint8_t; - -typedef int16 wad_int16_t; -typedef uint16 wad_uint16_t; - -typedef int wad_int32_t; -typedef unsigned int wad_uint32_t; - -typedef int64 wad_int64_t; -typedef uint64 wad_uint64_t; -#elif defined (__DJGPP__) -typedef signed char wad_int8_t; -typedef unsigned char wad_uint8_t; - -typedef signed short int wad_int16_t; -typedef unsigned short int wad_uint16_t; - -typedef signed long wad_int32_t; -typedef unsigned long wad_uint32_t; - -typedef signed long long wad_int64_t; -typedef unsigned long long wad_uint64_t; -#else -#define __STDC_LIMIT_MACROS -#include - -typedef int8_t wad_int8_t; -typedef uint8_t wad_uint8_t; - -typedef int16_t wad_int16_t; -typedef uint16_t wad_uint16_t; - -typedef int32_t wad_int32_t; -typedef uint32_t wad_uint32_t; - -typedef int64_t wad_int64_t; -typedef uint64_t wad_uint64_t; -#endif - -typedef enum -{ - false, - true -} wad_boolean_t; - -typedef struct -{ - char id[4]; // The WAD header's 4-character ID. - wad_uint32_t numlumps; // The number of lumps the WAD has. - wad_uint32_t lumpdir; // The pointer to the lump directory. -} wadheader_t; - -typedef struct wad_s -{ - char *filename; // The filename of the open WAD. - - wadheader_t *header; // The WAD's header. - wad_boolean_t compressed; - - struct lump_s *lumps; // The WAD's lumps buffer. -} wad_t; - -typedef struct lump_s -{ - wad_t *wad; // The WAD the lump belongs to. - - char name[9]; // The name of the lump. - - wad_uint64_t disksize; // The size of the lump on disk. - size_t size; // The real (uncompressed) size of the lump. - - wad_boolean_t compressed; - - void *data; // The actual lump data. - - wad_uint32_t num; // The lump number in the WAD. - struct lump_s *prev; // The previous node in the tree. - struct lump_s *next; // The next node in the tree. -} lump_t; - -// a raw entry of the wad directory -typedef struct -{ - wad_uint32_t position; // The position of the lump in the WAD file. - wad_uint32_t size; // Size of the lump. - char name[8]; // The lump's name. -} lumpdir_t; - -// -// wad_static.c -// Static file for internal libwad operations. -// -extern char *WAD_Error(void); -extern char *WAD_BaseName(char *path); -extern char *WAD_VA(const char *format, ...); - -extern inline wad_int16_t WAD_INT16_Endianness(wad_int16_t x); -extern inline wad_int32_t WAD_INT32_Endianness(wad_int32_t x); - -// -// wad.c -// WAD interface functionality. -// -extern wad_uint32_t wad_numwads; - -extern wad_uint32_t WAD_WADLoopAdvance(wad_uint32_t i); - -extern wad_t *WAD_WADByNum(wad_uint16_t num); -extern wad_t *WAD_WADByFileName(const char *filename); - -extern wad_t *WAD_OpenWAD(const char *filename); - -extern wad_int32_t WAD_SaveWAD(wad_t *wad); -extern inline wad_int32_t WAD_SaveWADByNum(wad_uint16_t num); -extern inline wad_int32_t WAD_SaveWADByFileName(const char *filename); - -extern inline wad_int32_t WAD_SaveCloseWAD(wad_t *wad); -extern inline wad_int32_t WAD_SaveCloseWADByNum(wad_uint16_t num); -extern inline wad_int32_t WAD_SaveCloseWADByFileName(const char *filename); - -extern void WAD_CloseWAD(wad_t *wad); -extern inline void WAD_CloseWADByNum(wad_uint16_t num); -extern inline void WAD_CloseWADByFileName(const char *filename); - -// -// lump.c -// Lump interface functionality. -// -extern char *WAD_LumpNameFromFileName(char *path); -extern lump_t *WAD_LumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern lump_t *WAD_LumpInWADByName(wad_t *wad, const char *name); -extern lump_t *WAD_LumpByName(const char *name); - -extern inline wad_uint32_t WAD_LumpNum(lump_t *lump); -extern inline wad_uint32_t WAD_LumpNumInWADByName(wad_t *wad, const char *name); -extern inline wad_uint32_t WAD_LumpNumByName(const char *name); - -extern inline size_t WAD_LumpSize(lump_t *lump); -extern inline size_t WAD_LumpSizeInWADByName(wad_t *wad, const char *name); -extern inline size_t WAD_LumpSizeByName(const char *name); - -extern lump_t *WAD_AddLump(wad_t *wad, lump_t *destlump, const char *name, const char *filename); -extern inline lump_t *WAD_AddLumpInWADByNum(wad_t *wad, wad_uint32_t num, const char *name, const char *filename); -extern inline lump_t *WAD_AddLumpInWADByName(wad_t *wad, const char *destname, const char *name, const char *filename); -extern inline lump_t *WAD_AddLumpByName(const char *destname, const char *name, const char *filename); - -extern lump_t *WAD_CacheLump(lump_t *lump); -extern inline lump_t *WAD_CacheLumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern inline lump_t *WAD_CacheLumpInWADByName(wad_t *wad, const char *name); -extern inline lump_t *WAD_CacheLumpByName(const char *name); - -extern lump_t *WAD_MoveLump(lump_t *lump, lump_t *destlump); -extern inline lump_t *WAD_MoveLumpInWADByNum(wad_t *wad, wad_uint32_t num, wad_t *destwad, wad_uint32_t destnum); -extern inline lump_t *WAD_MoveLumpInWADByName(wad_t *wad, const char *name, wad_t *destwad, const char *destname); -extern inline lump_t *WAD_MoveLumpByName(const char *name, const char *destname); - -extern void WAD_UncacheLump(lump_t *lump); -extern inline void WAD_UncacheLumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern inline void WAD_UncacheLumpInWADByName(wad_t *wad, const char *name); -extern inline void WAD_UncacheLumpByName(const char *name); - -extern void WAD_RemoveLump(lump_t *lump); -extern inline void WAD_RemoveLumpInWADByNum(wad_t *wad, wad_uint32_t num); -extern inline void WAD_RemoveLumpInWADByName(wad_t *wad, const char *name); -extern inline void WAD_RemoveLumpByName(const char *name); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // __WAD_H__ diff --git a/tools/libwad/src/lump.c b/tools/libwad/src/lump.c deleted file mode 100644 index a1f4c97fc..000000000 --- a/tools/libwad/src/lump.c +++ /dev/null @@ -1,392 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file lump.c -/// \brief Lump interface functionality. - -#include "wad_static.h" - -// -// Create a lump name from the file name -// of a lump. Used for when no name for -// a lump was given. -// -char *WAD_LumpNameFromFileName(char *path) -{ - wad_int32_t i; - char *name, *tempname, *file = WAD_BaseName(path); - - if (!file) - return NULL; - - // - // Process the filename for a suitable lump name. - // - // Get rid of any hidden file period. - if (file[0] == '.') - { - if (!(tempname = malloc(sizeof(*file) * strlen(&file[1])))) - { - free(file); - return NULL; - } - strcpy(tempname, &file[1]); - free(file); - } - else - tempname = file; - - // Get rid of any extensions. - for (i = 0; tempname[i] != '.' && tempname[i] != '\0'; i++); - - // Then, take the first eight characters of - // the resulting filename to get the lump name. - if (i > 8) - i = 8; - - if (!(name = malloc(sizeof(*name) * (i+1)))) - { - free(tempname); - return NULL; - } - - strncpy(name, tempname, i); - name[i+1] = '\0'; - - // - // Done processing lump name. - // - free(tempname); - return name; -} - -lump_t *WAD_LumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - lump_t *lump; - - if (!wad || !num) - return NULL; - - for (lump = wad->lumps; lump; lump = lump->next) - if (num == lump->num) - return lump; - - return NULL; -} - -lump_t *WAD_LumpInWADByName(wad_t *wad, const char *name) -{ - lump_t *lump; - - if (!wad || !name) - return NULL; - - for (lump = wad->lumps; lump; lump = lump->next) - if (!strcmp(name, lump->name)) - return lump; - - return NULL; -} - -lump_t *WAD_LumpByName(const char *name) -{ - wad_uint32_t i; - lump_t *lump; - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - if ((lump = WAD_LumpInWADByName(WAD_WADByNum(i), name))) - return lump; - - return NULL; -} - -inline wad_uint32_t WAD_LumpNum(lump_t *lump) -{ - return lump->num; -} - -inline wad_uint32_t WAD_LumpNumInWADByName(wad_t *wad, const char *name) -{ - return WAD_LumpNum(WAD_LumpInWADByName(wad, name)); -} - -inline wad_uint32_t WAD_LumpNumByName(const char *name) -{ - return WAD_LumpNum(WAD_LumpByName(name)); -} - -inline size_t WAD_LumpSize(lump_t *lump) -{ - return lump->size; -} - -inline size_t WAD_LumpSizeInWADByName(wad_t *wad, const char *name) -{ - return WAD_LumpSize(WAD_LumpInWADByName(wad, name)); -} - -inline size_t WAD_LumpSizeByName(const char *name) -{ - return WAD_LumpSize(WAD_LumpByName(name)); -} - -static void WAD_AddLumpToTree(lump_t *lump, lump_t *destlump) -{ - lump_t *l; - - if (destlump) - { - lump->wad = destlump->wad; - lump->num = destlump->num; - for (l = destlump; l; l = l->next) - l->num++; - if (destlump->prev) - destlump->prev->next = lump; - lump->prev = destlump->prev; - destlump->prev = lump; - lump->next = destlump; - } - else - { - for (l = lump->wad->lumps; l; l = l->next) - if (!l->next) - break; - lump->num = lump->wad->header->numlumps; - l->next = lump; - lump->prev = l; - lump->next = NULL; - } - lump->wad->header->numlumps++; -} - -lump_t *WAD_AddLump(wad_t *wad, lump_t *destlump, const char *name, const char *filename) -{ - // The open lump file. - FILE *file = NULL; - // Pointer to the lump. - lump_t *lump; - // Lump structure. - wad_uint64_t disksize; // lump->disksize - size_t size; // lump->size - wad_boolean_t compressed;// lump->compressed - void *data; // lump->data - - if (!wad) - return NULL; - - if (!name && !filename) - return NULL; - - if (filename) - { - if (!(file = fopen(filename, "rb"))) - return NULL; - - fseek(file, 0, SEEK_END); - disksize = size = (unsigned)ftell(file); - compressed = false; - - - if (!(data = malloc(size))) - { - fclose(file); - return NULL; - } - - fseek(file, 0, SEEK_SET); - if (fread(data, disksize, 1, file) < 1) - return NULL; - fclose(file); - } - else - { - disksize = size = 0; - compressed = false; - data = NULL; - } - - - if (!(lump = malloc(sizeof(*lump)))) - { - WAD_FreeMemory(NULL, NULL, NULL, lump, NULL); - return NULL; - } - - lump->wad = wad; - if (!strcpy(lump->name, (name) ? name : WAD_LumpNameFromFileName((char *)filename))) - { - WAD_FreeMemory(NULL, NULL, NULL, lump, NULL); - return NULL; - } - lump->disksize = disksize; - lump->size = size; - lump->compressed = compressed; - - lump->data = data; - - WAD_AddLumpToTree(lump, destlump); - - return lump; -} - -inline lump_t *WAD_AddLumpInWADByNum(wad_t *wad, wad_uint32_t num, const char *name, const char *filename) -{ - return WAD_AddLump(wad, WAD_LumpInWADByNum(wad, num), name, filename); -} - -inline lump_t *WAD_AddLumpInWADByName(wad_t *wad, const char *destname, const char *name, const char *filename) -{ - return WAD_AddLump(wad, WAD_LumpInWADByName(wad, destname), name, filename); -} - -inline lump_t *WAD_AddLumpByName(const char *destname, const char *name, const char *filename) -{ - lump_t *l = WAD_LumpByName(destname); - return WAD_AddLump(l->wad, l, name, filename); -} - -lump_t *WAD_CacheLump(lump_t *lump) -{ - return lump; // TODO: WAD_CacheLump, dynamic lump loading. -} - -inline lump_t *WAD_CacheLumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - return WAD_CacheLump(WAD_LumpInWADByNum(wad, num)); -} - -inline lump_t *WAD_CacheLumpInWADByName(wad_t *wad, const char *name) -{ - return WAD_CacheLump(WAD_LumpInWADByName(wad, name)); -} - -inline lump_t *WAD_CacheLumpByName(const char *name) -{ - return WAD_CacheLump(WAD_LumpByName(name)); -} - -lump_t *WAD_MoveLump(lump_t *lump, lump_t *destlump) -{ - lump_t *l; - - if (!destlump) - return NULL; - - // - // Link the previous and next nodes in the WAD tree with each other. - // - if (lump->next) - { - lump->next->prev = lump->prev; - for (l = lump->next; l; l = l->next) - l->num--; - } - if (lump->prev) - lump->prev->next = lump->next; - lump->wad->header->numlumps--; - - // - WAD_AddLumpToTree(lump, destlump); - - return lump; -} - -inline lump_t *WAD_MoveLumpInWADByNum(wad_t *wad, wad_uint32_t num, wad_t *destwad, wad_uint32_t destnum) -{ - return WAD_MoveLump(WAD_LumpInWADByNum(wad, num), WAD_LumpInWADByNum(destwad, destnum)); -} - -inline lump_t *WAD_MoveLumpInWADByName(wad_t *wad, const char *name, wad_t *destwad, const char *destname) -{ - return WAD_MoveLump(WAD_LumpInWADByName(wad, name), WAD_LumpInWADByName(destwad, destname)); -} - -inline lump_t *WAD_MoveLumpByName(const char *name, const char *destname) -{ - return WAD_MoveLump(WAD_LumpByName(name), WAD_LumpByName(destname)); -} - -void WAD_UncacheLump(lump_t *lump) -{ - (void)lump; // TODO: WAD_UncacheLump, dynamic lump loading. -} - -inline void WAD_UncacheLumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - WAD_UncacheLump(WAD_LumpInWADByNum(wad, num)); -} - -inline void WAD_UncacheLumpInWADByName(wad_t *wad, const char *name) -{ - WAD_UncacheLump(WAD_LumpInWADByName(wad, name)); -} - -inline void WAD_UncacheLumpByName(const char *name) -{ - WAD_UncacheLump(WAD_LumpByName(name)); -} - -void WAD_RemoveLump(lump_t *lump) -{ - lump_t *l; - - if (!lump) - return; - - // - // Link the previous and next nodes in the WAD tree with each other. - // - lump->next->prev = lump->prev; - lump->prev->next = lump->next; - - // - // Modify the lump numbers for all the subsequent lumps, - // and the total lumps in the WAD. - // - lump->wad->header->numlumps--; - - if (lump->num == 0) - lump->wad->lumps = lump->next; - - for (l = lump->next; l; l = l->next) - l->num--; - - // - // While, at the same time, blanking the references - // to these nodes so they don't get removed. - // - lump->next = NULL; - - // - // Free this lump's memory. - // - WAD_FreeMemory(NULL, NULL, NULL, lump, NULL); -} - -inline void WAD_RemoveLumpInWADByNum(wad_t *wad, wad_uint32_t num) -{ - WAD_RemoveLump(WAD_LumpInWADByNum(wad, num)); -} - -inline void WAD_RemoveLumpInWADByName(wad_t *wad, const char *name) -{ - WAD_RemoveLump(WAD_LumpInWADByName(wad, name)); -} - -inline void WAD_RemoveLumpByName(const char *name) -{ - WAD_RemoveLump(WAD_LumpByName(name)); -} diff --git a/tools/libwad/src/wad.c b/tools/libwad/src/wad.c deleted file mode 100644 index ab8099b47..000000000 --- a/tools/libwad/src/wad.c +++ /dev/null @@ -1,412 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file wad.c -/// \brief WAD interface functionality. - -#include "wad_static.h" - -// -// Offset for the first lump's data is always 12 bytes. -// -#define LUMPOFFSET 12 - -// -// Maximum of wad files used at the same time. -// (There is a max of simultaneous open files anyway, and this should be plenty.) -// -#define MAX_WADFILES 48 - -wad_t *wads[MAX_WADFILES]; -wad_uint32_t wad_numwads; - -wad_uint32_t wad_oldnumwads; -wad_uint32_t wad_removednum; - -static inline void WAD_ChangeWADNum(wad_int32_t i, wad_t *wad) -{ - wads[i] = wad; -} - -static inline void WAD_CacheWAD(wad_t *wad) -{ - WAD_ChangeWADNum(wad_numwads, wad); - wad_oldnumwads = wad_numwads; - wad_numwads++; -} - -static void WAD_UncacheWAD(wad_t *wad) -{ - wad_uint32_t i; - - for (i = 0; i < wad_numwads; i++) - if (WAD_WADByNum(i) == wad) - break; - - WAD_ChangeWADNum(i, NULL); - wad_removednum = i; - - for (; i < wad_numwads; i++) - { - if (WAD_WADByNum(i+1)) - { - WAD_ChangeWADNum(i, WAD_WADByNum(i+1)); - WAD_ChangeWADNum(i+1, NULL); - } - } - - wad_oldnumwads = wad_numwads; - wad_numwads--; -} - -wad_uint32_t WAD_WADLoopAdvance(wad_uint32_t i) -{ - wad_uint32_t o; - - o = wad_oldnumwads; - wad_oldnumwads = wad_numwads; - - return (o > wad_numwads && i <= wad_removednum) ? i : i + 1; -} - -wad_t *WAD_WADByNum(wad_uint16_t num) -{ - return (wads[num]) ? (wad_t *)wads[num] : NULL; -} - -wad_t *WAD_WADByFileName(const char *filename) -{ - wad_uint32_t i; - wad_t *w; - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - { - w = WAD_WADByNum(i); - if (!strcmp(filename, w->filename)) - return w; - } - - return NULL; -} - -// -// Allocate a wadfile, setup the lumpinfo (directory) and -// lumpcache, add the wadfile to the current active wadfiles -// -// 1: Reached the maximum WAD number. -// 2: Cannot open the file. -// 3: Cannot read the WAD file's header. -// 4: Invalid WAD ID. -// 5: WAD's lump directory is corrupt. -// 6: Corrupt compressed WAD. -// -wad_t *WAD_OpenWAD(const char *filename) -{ - size_t i; - // Pointer to the WAD. - wad_t *wad = NULL; - // WAD file structure information. - // wad->filename is the function's argument. - FILE *file; // wad->file - wadheader_t *header; // wad->header - lump_t *l, *lumps = NULL; // wad->lumps - // Temporary lump information. - wad_uint64_t position; - lumpdir_t *lumpdir; - lump_t *ln = NULL; - - // - // Check if the limit of maximum WAD files has been - // reached or not. - // - if (wad_numwads >= MAX_WADFILES) - return NULL; - - // - // Open the WAD file. - // - if (!(file = fopen(filename, "rb"))) - return NULL; - - // - // Read the WAD file's header. - // - header = malloc(sizeof(*header)); - if (fread(header, 1, sizeof(*header), file) < sizeof(*header)) - return NULL; - - // Check if the ID is valid. - if (memcmp(header->id, "IWAD", 4) && memcmp(header->id, "PWAD", 4) && memcmp(header->id, "SDLL", 4)) - { - WAD_FreeMemory(file, header, NULL, NULL, NULL); - return NULL; - } - - // Check the rest of the header for type. - header->numlumps = WAD_INT32_Endianness(header->numlumps); - header->lumpdir = WAD_INT32_Endianness(header->lumpdir); - - // - // Read the WAD file's lump directory. - // - i = header->numlumps * sizeof(*lumpdir); - lumpdir = malloc(i); - - if (fseek(file, header->lumpdir, SEEK_SET) < 0 || fread(lumpdir, i, 1, file) < 1) - { - WAD_FreeMemory(file, header, lumpdir, NULL, NULL); - return NULL; - } - - // - // Fill lump information structure. - // - for (i = 0; i < header->numlumps; i++, lumpdir++) - { - if (!(l = malloc(sizeof(*l)))) - { - WAD_FreeMemory(file, header, lumpdir, lumps, NULL); - return NULL; - } - - position = WAD_INT32_Endianness(lumpdir->position); - - strncpy(l->name, lumpdir->name, 8); - l->size = l->disksize = WAD_INT32_Endianness(lumpdir->size); - l->compressed = false; // TODO: Compressed WAD support. - - if (l->disksize) - { - fseek(file, position, SEEK_SET); - if (!(l->data = malloc(l->disksize)) || fread(l->data, l->disksize, 1, file) < 1) - { - WAD_FreeMemory(file, header, lumpdir, lumps, NULL); - - if (!l->data) - return NULL; - else - return NULL; - } - } - - l->num = i; - l->next = NULL; - if (!lumps) - { - l->prev = NULL; - ln = lumps = l; - } - else - { - l->prev = ln; - ln = ln->next = l; - } - } - //free(lumpdir); - - // - // Allocate and fill WAD entry. - // - if (!(wad = malloc(sizeof(*wad)))) - { - WAD_FreeMemory(file, header, NULL, lumps, NULL); - return NULL; - } - wad->filename = (char *)filename; - - wad->header = header; - wad->compressed = false; - - wad->lumps = lumps; - - for (l = wad->lumps; l; l = l->next) - l->wad = wad; - - fclose(file); - - // - // Add the WAD to the wadfiles buffer and wad_numwads number. - // - WAD_CacheWAD(wad); - - // - // Done, loaded the WAD file. - // - return wad; -} - -// 1: Invalid wad number. -// 2: Unable to open file for writing. -// 3: Unable to write wad ID to the header. -// 4: Unable to write number of lumps to the header. -// 5: Unable to write temporary data to the header. -// 6: Unable to write lump data. -// 7: Unable to write position of lump data. -// 8: Unable to Write size of lump data. -// 9: Unable to write lump name. -// 9: Unable to write directory position. -wad_int32_t WAD_SaveWAD(wad_t *wad) -{ - lump_t *l; - FILE *file; - char *newfilename; - wad_int64_t diroffset, lumpoffset; - - if (!wad) - return 1; - - newfilename = WAD_VA("%s%s", wad->filename, ".bak"); - - remove(newfilename); - rename(wad->filename, newfilename); - - if (!(file = fopen(wad->filename, "wb"))) - return 2; - - // - // Write four-character WAD ID. - // - if(fwrite(wad->header->id, 4, 1, file) < 1) - return 3; - - // - // Write number of lumps. - // - if (fwrite(&wad->header->numlumps, 4, 1, file) < 1) - return 4; - - // - // Offset of directory is not known yet. For now, write number of lumps - // again, just to fill the space. - // - if (fwrite(&wad->header->numlumps, 4, 1, file) < 1) - return 5; - - // - // Loop through lump list, writing lump data. - // - for (l = wad->lumps; l; l = l->next) - { - // Don't write anything for the head of the lump list or for lumps of - // zero length. - if (!l->data) - continue; - - // Write the data. - if (fwrite(l->data, l->disksize, 1, file) < 1) - return 6; - } - - // - // Current position is where directory will start. - // - diroffset = ftell(file); - - // - // Pointer to the offset for the first lump's data. - // - lumpoffset = LUMPOFFSET; - - // - // Loop through lump list again, this time writing directory entries. - // - for (l = wad->lumps; l; l = l->next) - { - // Write position of lump data. - if (fwrite(&lumpoffset, 4, 1, file) < 1) - return 7; - - // Write size of lump data. - if (fwrite(&(l->disksize), 4, 1, file) < 1) - return 8; - - // Write lump name. - if (fwrite(&(l->name), 8, 1, file) < 1) - return 9; - - // Increment lumpoffset variable as appropriate. - lumpoffset += l->disksize; - } - - // - // Go back to header and write the proper directory position. - // - fseek(file, 8, SEEK_SET); - if (fwrite(&diroffset, 4, 1, file) < 1) - return 10; - - // - // Done, saved the WAD file. - // - return 0; -} - -inline wad_int32_t WAD_SaveWADByNum(wad_uint16_t num) -{ - return WAD_SaveWAD(WAD_WADByNum(num)); -} - -inline wad_int32_t WAD_SaveWADByFileName(const char *filename) -{ - return WAD_SaveWAD(WAD_WADByFileName(filename)); -} - -inline wad_int32_t WAD_SaveCloseWAD(wad_t *wad) -{ - wad_int32_t ret; - - if (!(ret = WAD_SaveWAD(wad))) - return ret; - - WAD_CloseWAD(wad); - return ret; -} - -inline wad_int32_t WAD_SaveCloseWADByNum(wad_uint16_t num) -{ - return WAD_SaveCloseWAD(WAD_WADByNum(num)); -} - -inline wad_int32_t WAD_SaveCloseWADByFileName(const char *filename) -{ - return WAD_SaveCloseWAD(WAD_WADByFileName(filename)); -} - -void WAD_CloseWAD(wad_t *wad) -{ - if (!wad) - return; - - // - // Free memory used by the WAD. - // - WAD_FreeMemory(NULL, wad->header, NULL, wad->lumps, wad); - - // - // Remove references to the WAD. - // - WAD_UncacheWAD(wad); -} - -inline void WAD_CloseWADByNum(wad_uint16_t num) -{ - WAD_CloseWAD(WAD_WADByNum(num)); -} - -inline void WAD_CloseWADByFileName(const char *name) -{ - WAD_CloseWAD(WAD_WADByFileName(name)); -} diff --git a/tools/libwad/src/wad_static.c b/tools/libwad/src/wad_static.c deleted file mode 100644 index dd631a5ba..000000000 --- a/tools/libwad/src/wad_static.c +++ /dev/null @@ -1,116 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file wad_static.c -/// \brief Static functions for internal libwad operations. - -#include "wad_static.h" - -#define WAD_MAXERROR 1024 -static char wad_error[WAD_MAXERROR]; - -void WAD_ErrorSet(const char *text) -{ - strncpy(wad_error, text, WAD_MAXERROR); - wad_error[WAD_MAXERROR] = '\0'; -} - -inline void WAD_FreeMemory(FILE *file, wadheader_t *header, void *lumpdir, lump_t *lumps, wad_t *wad) -{ - lump_t *l, *ln = NULL; - - if (file) - fclose(file); - if (header) - free(header); - if (lumpdir) - free(lumpdir); - - if (lumps) - { - for (l = lumps; l; l = ln) - { - ln = l->next; - free(l->data); - free(l); - } - } - - if (wad) - { - if (wad->filename) - free(wad->filename); - - free(wad); - } -} - -char *WAD_Error(void) -{ - return wad_error; -} - -char *WAD_BaseName(char *path) -{ - wad_int32_t i; - - // - // Check if there is no text to check. - // - if (!path || path[0] == '\0') - return NULL; - - // - // Find the buffer entry where the actual filename begins. - // - for (i = strlen(path) - 1; i >= 0 && path[i] != '/'; i--); - - return (i >= 0) ? &path[i+1] : path; -} - -char *WAD_VA(const char *format, ...) -{ - va_list argptr; - static char string[1024]; - - va_start(argptr, format); - vsprintf(string, format, argptr); - va_end(argptr); - - return string; -} - -inline wad_int16_t WAD_INT16_Endianness(wad_int16_t x) -{ -#ifdef _BIG_ENDIAN - return ((wad_int16_t)((((wad_uint16_t)(x) & (wad_uint16_t)0x00ffU) << 8) | (((wad_uint16_t)(x) & (wad_uint16_t)0xff00U) >> 8))); -#else - return (wad_int16_t)x; -#endif -} - -inline wad_int32_t WAD_INT32_Endianness(wad_int32_t x) -{ -#ifdef _BIG_ENDIAN - return ((wad_int32_t)(\ - (((wad_uint32_t)(x) & (wad_uint32_t)0x000000ffUL) << 24) |\ - (((wad_uint32_t)(x) & (wad_uint32_t)0x0000ff00UL) << 8) |\ - (((wad_uint32_t)(x) & (wad_uint32_t)0x00ff0000UL) >> 8) |\ - (((wad_uint32_t)(x) & (wad_uint32_t)0xff000000UL) >> 24))); -#else - return (wad_int32_t)x; -#endif -} diff --git a/tools/libwad/src/wad_static.h b/tools/libwad/src/wad_static.h deleted file mode 100644 index 04d367bbd..000000000 --- a/tools/libwad/src/wad_static.h +++ /dev/null @@ -1,34 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// libwad: Doom WAD format interface library. -// Copyright (C) 2011 by Callum Dickinson. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file wad_static.h -/// \brief Static header for internal libwad operations. - -#ifndef __WAD_STATIC_H__ -#define __WAD_STATIC_H__ - -#include -#include -#include -#include -#include -#include "../include/wad.h" - -void WAD_ErrorSet(const char *text); - -inline void WAD_FreeMemory(FILE *file, wadheader_t *header, void *lumpdir, lump_t *lumps, wad_t *wad); - -#endif // __WAD_STATIC_H__ diff --git a/tools/makefile b/tools/makefile deleted file mode 100644 index f4b377a26..000000000 --- a/tools/makefile +++ /dev/null @@ -1,24 +0,0 @@ - -default: dircomp2.c - gcc -O6 -mpentium -Wall -s dircomp2.c -o dircomp2.exe - -asm: - gcc -O6 -mpentium -Wall -g dircomp2.c -o tmp.exe - objdump -dS tmp.exe --debugging --no-show-raw-insn > dircomp2.s - del tmp.exe - -h2d: h2d.c - gcc -O6 -mpentium -Wall -s h2d.c -o h2d.exe - -dckconv: dckconv.c - gcc -O6 -mpentium -Wall -s dckconv.c -o dckconv.exe - -dckconv2: dckconv2.c - gcc -O6 -mpentium -Wall -s dckconv2.c -o dckconv2.exe - -dckcomp: dckcomp.c - gcc -O6 -mpentium -Wall -s dckcomp.c -o dckcomp.exe - -convert: convert.c - gcc -O6 -mpentium -Wall -s convert.c -o convert.exe - diff --git a/tools/masterserver/.gitignore b/tools/masterserver/.gitignore deleted file mode 100644 index 9f45745a3..000000000 --- a/tools/masterserver/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/client -/server -/server.log -/*.o diff --git a/tools/masterserver/Makefile b/tools/masterserver/Makefile deleted file mode 100644 index 7e66ab210..000000000 --- a/tools/masterserver/Makefile +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (C) 2000 by DooM Legacy Team. -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# DESCRIPTION: -# Makefile for DooM Legacy Master Server -# Created on 06/23/2000 by Thierry Van Elsuwe -# e-mail: hurdler@newdoom.com -# -#----------------------------------------------------------------------------- - -PORT=28900 -#PORT=7896 - -#*******************************************************************# - -CCFILES=common.cpp ipcs.cpp crypt.cpp md5.cpp -Main_CCFILES=server.cpp #client.cpp - -#******************************************************************# - -MYSQL_CONFIG?= mysql_config -MYSQL_CFLAGS?=$(shell $(MYSQL_CONFIG) --cflags) -MYSQL_LIBS?=$(shell $(MYSQL_CONFIG) --libs) - -CXXFLAGS+=-Wall -O3 -Wextra -ifdef MINGW -LIBS+=-lws2_32 -else -LIBS+=-lm -endif - -CXXFLAGS+=$(MYSQL_CFLAGS) -LIBS+=$(MYSQL_LIBS) - -ifdef DEBUG -CXXFLAGS+=-g -D__DEBUG__ -endif - -SRCS=$(CCFILES) $(Main_CCFILES) -OFILES=$(CCFILES:.cpp=.o) -Main_OFILES=$(Main_CCFILES:.cpp=.o) -EXEFILE=$(Main_CCFILES:.cpp=) - -##################################################################### - -.SUFFIXES: .cpp .h - -default: init $(EXEFILE) end - -init: - @echo - @echo "Compiling options:" - @echo " CXX : $(CXX)" - @echo " LDFLAGS : $(LDFLAGS)" - @echo " LIBS : $(LIBS)" - @echo " CXXFLAGS: $(CXXFLAGS)" - @echo - @echo "Files:" - @echo " SRCS : $(SRCS)" - @echo " OFILES : $(OFILES) $(Main_OFILES)" - @echo " EXEFILE : $(EXEFILE)" - @echo - -end: - @echo - @echo "*** Makefile ended successfully ***" - @echo - -##################################################################### - -$(EXEFILE): $(OFILES) $(Main_OFILES) - @echo Linking ... - @$(CXX) $(LDFLAGS) $(OFILES) $@.o -o $@ $(LIBS) -ifndef CYGWIN -ifndef MINGW - @chmod 755 $@ -endif -endif - @echo File $@ has been created - -##################################################################### - -.cpp.o: - @echo Compiling $< -\> $@ - @$(CXX) $(CXXFLAGS) $(INCS) -c $< -o $@ - -##################################################################### - -debug: debug_ -debug_: - @make "CXXFLAGS = $(CXXFLAGS) -D__DEBUG__" - @echo - -clean: clean_ -clean_: - @echo - @echo Removing obejcts files, executable files and eventually core file... - @rm -f $(OFILES) $(Main_OFILES) $(EXEFILE) core - @echo - -realclean: clean - @echo Removing backup files... - @rm -f *~ *.bak - @echo - -depend: dep -dep: - @echo - @echo Make dependencies... - @makedepend -- $(CXXFLAGS) -- $(Main_CCFILES) $(CCFILES) 2> /dev/null - @rm -f Makefile.bak - @echo - -BAKFILE = ../SRB2MasterServer -backup: bak -bak: clean - @echo Copy files to $(BAKFILE).tgz... - @tar cvf $(BAKFILE).tar * > /dev/null - @gzip $(BAKFILE).tar - @mv $(BAKFILE).tar.gz $(BAKFILE).tgz - @echo Removing backup files... - @rm -f *~ *.bak - @echo - -#mrproper: dep clean default -mrproper: clean default - -install: mrproper - @echo "Launching the server, port $(PORT)..." - @./server $(PORT) - @echo diff --git a/tools/masterserver/Master.dsp b/tools/masterserver/Master.dsp deleted file mode 100644 index 6bb0c13ed..000000000 --- a/tools/masterserver/Master.dsp +++ /dev/null @@ -1,230 +0,0 @@ -# Microsoft Developer Studio Project File - Name="MasterServer" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=MasterServer - Win32 Client Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "Master.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "Master.mak" CFG="MasterServer - Win32 Client Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "MasterServer - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "MasterServer - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE "MasterServer - Win32 Client Debug" (based on "Win32 (x86) Console Application") -!MESSAGE "MasterServer - Win32 Client Release" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "MasterServer - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "../../bin/VC/Release/MasterServer" -# PROP Intermediate_Dir "../../objs/VC/Release/MasterServer" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W4 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterServer.exe" - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "../../bin/VC/Debug/MasterServer" -# PROP Intermediate_Dir "../../objs/VC/Debug/MasterServer" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W4 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WIN32" /D "__DEBUG__" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterServer.exe" /pdbtype:sept - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "MasterServer___Win32_Client_Debug" -# PROP BASE Intermediate_Dir "MasterServer___Win32_Client_Debug" -# PROP BASE Ignore_Export_Lib 0 -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "../../bin/VC/Debug/MasterClient" -# PROP Intermediate_Dir "../../objs/VC/Debug/MasterClient" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W4 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "_WIN32" /D "__STDC__" /YX /FD /GZ /c -# ADD CPP /nologo /W4 /Gm /GX /ZI /Od /D "_DEBUG" /D "_WIN32" /D "__DEBUG__" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterServer.exe" /pdbtype:sept -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /debug /machine:I386 /out:"../../bin/VC/Debug/MasterClient.exe" /pdbtype:sept - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "MasterServer___Win32_Client_Release" -# PROP BASE Intermediate_Dir "MasterServer___Win32_Client_Release" -# PROP BASE Ignore_Export_Lib 0 -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "../../bin/VC/Release/MasterClient" -# PROP Intermediate_Dir "../../objs/VC/Release/MasterClient" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W4 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W4 /GX /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__STDC__" /D "_POSIX_" /FR /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterServer.exe" -# ADD LINK32 kernel32.lib wsock32.lib /nologo /subsystem:console /machine:I386 /out:"../../bin/VC/Release/MasterClient.exe" - -!ENDIF - -# Begin Target - -# Name "MasterServer - Win32 Release" -# Name "MasterServer - Win32 Debug" -# Name "MasterServer - Win32 Client Debug" -# Name "MasterServer - Win32 Client Release" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\client.cpp - -!IF "$(CFG)" == "MasterServer - Win32 Release" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug" - -# PROP BASE Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release" - -# PROP BASE Exclude_From_Build 1 - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\common.cpp -# End Source File -# Begin Source File - -SOURCE=.\crypt.cpp -# End Source File -# Begin Source File - -SOURCE=.\ipcs.cpp -# End Source File -# Begin Source File - -SOURCE=.\server.cpp - -!IF "$(CFG)" == "MasterServer - Win32 Release" - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Debug" - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Debug" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "MasterServer - Win32 Client Release" - -# PROP Exclude_From_Build 1 - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\srvlist.cpp -# End Source File -# Begin Source File - -SOURCE=.\stats.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\common.h -# End Source File -# Begin Source File - -SOURCE=.\ipcs.h -# End Source File -# Begin Source File - -SOURCE=.\srvlist.h -# End Source File -# Begin Source File - -SOURCE=.\stats.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project diff --git a/tools/masterserver/Master.sln b/tools/masterserver/Master.sln deleted file mode 100644 index 129814c76..000000000 --- a/tools/masterserver/Master.sln +++ /dev/null @@ -1,38 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C++ Express 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MasterServer", "Master.vcproj", "{6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Client Debug|Win32 = Client Debug|Win32 - Client Debug|x64 = Client Debug|x64 - Client Release|Win32 = Client Release|Win32 - Client Release|x64 = Client Release|x64 - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|Win32.ActiveCfg = Client Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|Win32.Build.0 = Client Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|x64.ActiveCfg = Client Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Debug|x64.Build.0 = Client Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|Win32.ActiveCfg = Client Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|Win32.Build.0 = Client Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|x64.ActiveCfg = Client Release|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Client Release|x64.Build.0 = Client Release|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|Win32.ActiveCfg = Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|Win32.Build.0 = Debug|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|x64.ActiveCfg = Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Debug|x64.Build.0 = Debug|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|Win32.ActiveCfg = Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|Win32.Build.0 = Release|Win32 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|x64.ActiveCfg = Release|x64 - {6AEBAD84-BCB1-4302-A453-7AAD1DF006DA}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/tools/masterserver/Master.vcproj b/tools/masterserver/Master.vcproj deleted file mode 100644 index 364094dd4..000000000 --- a/tools/masterserver/Master.vcproj +++ /dev/null @@ -1,1063 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/masterserver/MasterClient.dev b/tools/masterserver/MasterClient.dev deleted file mode 100644 index 035bb0bff..000000000 --- a/tools/masterserver/MasterClient.dev +++ /dev/null @@ -1,159 +0,0 @@ -[Project] -FileName=MasterClient.dev -Name=MasterClient -UnitCount=7 -Type=1 -Ver=1 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler=-Wall_@@_ -CppCompiler=-Wall_@@_ -Linker=-lwsock32_@@_ -IsCpp=1 -Icon= -ExeOutput=..\..\bin -ObjectOutput=..\..\objs\MasterClient -OverrideOutput=0 -OverrideOutputName=MasterServer.exe -HostApplication= -Folders=Client,Common -CommandLine= -UseCustomMakefile=0 -CustomMakefile= -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0000000010001001001010 - -[Unit1] -FileName=common.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1 -OverrideBuildCmd=0 -BuildCmd= - -[Unit2] -FileName=ipcs.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=2 -OverrideBuildCmd=0 -BuildCmd= - -[Unit7] -FileName=Makefile -CompileCpp=1 -Folder= -Compile=0 -Link=0 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit8] -FileName=stats.h -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= -CompileCpp=1 - -[Unit9] -FileName=common.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit11] -FileName=Makefile -CompileCpp=1 -Folder= -Compile=0 -Link=0 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit12] -FileName=srvlist.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[VersionInfo] -Major=0 -Minor=1 -Release=1 -Build=1 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 - -[Unit3] -FileName=crypt.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=4 -OverrideBuildCmd=0 -BuildCmd= - -[Unit4] -FileName=client.cpp -CompileCpp=1 -Folder=Client -Compile=1 -Link=1 -Priority=7 -OverrideBuildCmd=0 -BuildCmd=$(CPP) -c client.cpp -o ../../../objs/MasterServer/client.o $(CXXFLAGS) - -[Unit5] -FileName=common.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit6] -FileName=ipcs.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - diff --git a/tools/masterserver/MasterServer.dev b/tools/masterserver/MasterServer.dev deleted file mode 100644 index bc089ccd5..000000000 --- a/tools/masterserver/MasterServer.dev +++ /dev/null @@ -1,169 +0,0 @@ -[Project] -FileName=MasterServer.dev -Name=MasterServer -UnitCount=11 -Type=1 -Ver=1 -ObjFiles= -Includes= -Libs= -PrivateResource= -ResourceIncludes= -MakeIncludes= -Compiler=-Wall_@@_-DDEBUG_@@_ -CppCompiler=-Wall_@@_-DDEBUG_@@_ -Linker=-lwsock32_@@_-lmysql_@@_ -IsCpp=1 -Icon= -ExeOutput=..\..\bin -ObjectOutput=..\..\objs\MasterServer -OverrideOutput=0 -OverrideOutputName=MasterServer.exe -HostApplication= -Folders=Common,Server -CommandLine=28900 -UseCustomMakefile=0 -CustomMakefile= -IncludeVersionInfo=0 -SupportXPThemes=0 -CompilerSet=0 -CompilerSettings=0000000011001001001010 - -[Unit1] -FileName=common.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1 -OverrideBuildCmd=0 -BuildCmd= - -[Unit2] -FileName=ipcs.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=2 -OverrideBuildCmd=0 -BuildCmd= - -[Unit3] -FileName=srvlist.cpp -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=3 -OverrideBuildCmd=0 -BuildCmd= - -[Unit4] -FileName=crypt.cpp -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=4 -OverrideBuildCmd=0 -BuildCmd= - -[Unit5] -FileName=stats.cpp -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=5 -OverrideBuildCmd=0 -BuildCmd= - -[Unit6] -FileName=server.cpp -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=6 -OverrideBuildCmd=0 -BuildCmd= - -[Unit8] -FileName=common.h -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= -CompileCpp=1 - -[Unit9] -FileName=ipcs.h -CompileCpp=1 -Folder=Common -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit10] -FileName=Makefile -CompileCpp=1 -Folder= -Compile=0 -Link=0 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit11] -FileName=srvlist.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[VersionInfo] -Major=0 -Minor=1 -Release=1 -Build=1 -LanguageID=1033 -CharsetID=1252 -CompanyName= -FileVersion= -FileDescription=Developed using the Dev-C++ IDE -InternalName= -LegalCopyright= -LegalTrademarks= -OriginalFilename= -ProductName= -ProductVersion= -AutoIncBuildNr=0 - -[Unit7] -FileName=stats.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - -[Unit13] -FileName=LIVE_MySQL.h -CompileCpp=1 -Folder=Server -Compile=1 -Link=1 -Priority=1000 -OverrideBuildCmd=0 -BuildCmd= - diff --git a/tools/masterserver/client.cpp b/tools/masterserver/client.cpp deleted file mode 100644 index 8eba3f1a2..000000000 --- a/tools/masterserver/client.cpp +++ /dev/null @@ -1,133 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#include -#include -#include "ipcs.h" -#include "common.h" - -//============================================================================= - -static CClientSocket client_socket; -//static msg_t msg; -FILE *logfile; - -//============================================================================= - -static msg_t *getData(int argc, char *argv[]) -{ - static msg_t msg; - msg_server_t *info = (msg_server_t *)msg.buffer; - -#if defined (_WIN32) - strcpy(info->header.buffer, ""); -#else - strcpy(info->header.buffer, getpass("Enter password: ")); -#endif - - // default values if one of the param is not entered - strcpy(info->ip, "88.86.106.169"); - strcpy(info->port, "5029"); - strcpy(info->name, "Cueball's Dedicated Server"); - strcpy(info->version, "1.09.4"); - msg.type = ADD_PSERVER_MSG; - msg.length = sizeof (msg_server_t); - - for (int i = 0; i < argc; i++) - { - // first: extra parameters (must be after all -param) - if (!strcasecmp(argv[i], "get")) - { - msg.type = GET_SERVER_MSG; - msg.length = 0; - } - else if (!strcasecmp(argv[i], "log")) - { - msg.type = GET_LOGFILE_MSG; - msg.length = sizeof (msg_server_t); - } - else if (!strcasecmp(argv[i], "erase")) - { - msg.type = ERASE_LOGFILE_MSG; - msg.length = sizeof (msg_server_t); - } - else if (!strcasecmp(argv[i], "remove")) - { - msg.type = REMOVE_PSERVER_MSG; - msg.length = sizeof (msg_server_t); - } - - if (i >= argc-1) - continue; - - // second: parameter requiring extra parameters - if (strcasecmp(argv[i], "-ip") == 0) - strcpy(info->ip, argv[i+1]); - else if (strcasecmp(argv[i], "-port") == 0) - strcpy(info->port, argv[i+1]); - else if (strcasecmp(argv[i], "-hostname") == 0) - strcpy(info->name, argv[i+1]); - else if (strcasecmp(argv[i], "-version") == 0) - strcpy(info->version, argv[i+1]); - else if (strcasecmp(argv[i], "-pass") == 0) - strcpy(info->header.buffer, argv[i+1]); - } - return &msg; -} - -int main(int argc, char *argv[]) -{ - if (argc == 2) - { - printf("encrypt: %s\n", pCrypt(argv[1], "04")); - return 0; - } - else if (argc > 2) - { - if (client_socket.connect(argv[1], argv[2]) < 0) - { - conPrintf(RED, "Connect failed.\n"); - return -1; - } - - msg_t *msg = getData(argc, argv); - - if (client_socket.write(msg) < 0) - { - dbgPrintf(RED, "Write failed.\n"); - return -1; - } - - switch (ntohl(msg->type)) - { - case GET_SERVER_MSG: - case GET_LOGFILE_MSG: - while (client_socket.read(msg) >= 0) - { - if (ntohl(msg->length) == 0) - break; - printf("%s", msg->buffer); - } - break; - - case REMOVE_PSERVER_MSG: - default: - break; - } - } - return 0; -} diff --git a/tools/masterserver/common.cpp b/tools/masterserver/common.cpp deleted file mode 100644 index b9795bd0f..000000000 --- a/tools/masterserver/common.cpp +++ /dev/null @@ -1,207 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#include -#include -#include -#include "common.h" - -// ================================== GLOBALS ================================= - -static const char *fatal_error_msg[NUM_FATAL_ERROR] = -{ - "Error: signal()", - "Error: select()", - "Error: read()", - "Error: write()", -}; - -// used by xxxPrintf() functions as temporary variable -static char str[1024] =""; -static va_list arglist; -#ifdef _WIN32 -static size_t len = 0; -static HANDLE co = INVALID_HANDLE_VALUE; -static DWORD bytesWritten = 0; -static CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo; -#endif - -// ================================= FUNCTIONS ================================ - -/* - * clearScreen(): - */ -void clearScreen() -{ -#ifdef _WIN32 -#else - printf("\033[0m \033[2J \033[0;0H"); -#endif -} - -/* - * fatalError(): - */ -void fatalError(fatal_error_t num) -{ - clearScreen(); - printf("\n"); - perror(fatal_error_msg[num]); - printf("\n"); - exit(-1); -} - - -/* - * dbgPrintf(): - */ -#ifdef _WIN32 -void dbgPrintf(DWORDLONG col, const char *lpFmt, ...) -#else -void dbgPrintf(const char *col, const char *lpFmt, ...) -#endif -{ -#if defined (__DEBUG__) - va_start(arglist, lpFmt); - vsnprintf(str, sizeof str, lpFmt, arglist); - va_end(arglist); - -#ifdef _WIN32 - len = strlen(str); - co = GetStdHandle(STD_OUTPUT_HANDLE); - - if (co == INVALID_HANDLE_VALUE) - return; - - if (col == DEFCOL) - { - if (!GetConsoleScreenBufferInfo(co, &ConsoleScreenBufferInfo)) - ConsoleScreenBufferInfo.wAttributes = - FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE; - - SetConsoleTextAttribute(co, (WORD)col); - } - - if (GetFileType(co) == FILE_TYPE_CHAR) - WriteConsoleA(co, str, (DWORD)len, &bytesWritten, NULL); - else - WriteFile(co, str, (DWORD)len, &bytesWritten, NULL); - - if (col != DEFCOL) - SetConsoleTextAttribute(co, - ConsoleScreenBufferInfo.wAttributes); -#else - printf("%s%s", col, str); - fflush(stdout); -#endif -#else - (void)col; - (void)lpFmt; -#endif -} - -/* - * conPrintf() - */ -#ifdef _WIN32 -void conPrintf(DWORDLONG col, const char *lpFmt, ...) -#else -void conPrintf(const char *col, const char *lpFmt, ...) -#endif -{ - va_start(arglist, lpFmt); - vsnprintf(str, sizeof str, lpFmt, arglist); - va_end(arglist); - -#ifdef _WIN32 - len = strlen(str); - co = GetStdHandle(STD_OUTPUT_HANDLE); - - if (col == DEFCOL) - { - if (!GetConsoleScreenBufferInfo(co, &ConsoleScreenBufferInfo)) - ConsoleScreenBufferInfo.wAttributes = - FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE; - - SetConsoleTextAttribute(co, (WORD)col); - } - - if (co == INVALID_HANDLE_VALUE) - return; - - if (GetFileType(co) == FILE_TYPE_CHAR) - WriteConsoleA(co, str, (DWORD)len, &bytesWritten, NULL); - else - WriteFile(co, str, (DWORD)len, &bytesWritten, NULL); - - if (col != DEFCOL) - SetConsoleTextAttribute(co, - ConsoleScreenBufferInfo.wAttributes); -#else - printf("%s%s", col, str); - fflush(stdout); -#endif -} - -/* - * logPrintf(): - */ -void logPrintf(FILE *f, const char *lpFmt, ...) -{ - char *ct; - time_t t; - - va_start(arglist, lpFmt); - vsnprintf(str, sizeof str, lpFmt, arglist); - va_end(arglist); - - t = time(NULL); - ct = ctime(&t); - ct[strlen(ct)-1] = '\0'; - fprintf(f, "%s: %s", ct, str); - fflush(f); -#if defined (__DEBUG__) -#ifdef _WIN32 - len = strlen(str); - printf("%s", str); -#else - printf("%s%s", DEFCOL, str); -#endif - fflush(stdout); -#endif -} - -/* - * openFile(): - */ -FILE *openFile(const char *filename) -{ - return fopen(filename, "a+t"); -} - -void strrand(char *s, const int len) { - static const char alphanum[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - - for (int i = 0; i < len; ++i) { - s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; - } - - s[len] = 0; -} diff --git a/tools/masterserver/common.h b/tools/masterserver/common.h deleted file mode 100644 index cb935572d..000000000 --- a/tools/masterserver/common.h +++ /dev/null @@ -1,151 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#ifndef _COMMON_H_ -#define _COMMON_H_ - -#ifdef __GNUC__ -#include -#include - -#define UINT8 uint8_t -#define SINT8 int8_t - -#define UINT16 uint16_t -#define INT16 int16_t - -#define INT32 int32_t -#define UINT32 uint32_t -#define INT64 int64_t -#define UINT64 uint64_t -#define ATTRPACK __attribute__ ((packed)) -#elif defined ( _MSC_VER) -#include -#define UINT8 unsigned __int8 -#define SINT8 signed __int8 - -#define UINT16 unsigned __int16 -#define INT16 __int16 - -#define INT32 __int32 -#define UINT32 unsigned __int32 - -#define INT64 __int64 -#define UINT64 unsigned __int64 - -typedef long ssize_t; -#endif - -#ifndef ATTRPACK -#define ATTRPACK -#endif - -#include -#include -#include -#include - -#if defined (_WIN32) || defined (__OS2__) -#ifdef __GNUC__ -#define strcasecmp stricmp -#elif defined (_MSC_VER) -#define snprintf _snprintf -#define vsnprintf _vsnprintf -#define strcasecmp _stricmp -#pragma warning(disable : 4244) -#endif -#endif - -// ================================ DEFINITIONS =============================== - - -#ifdef _WIN32 -#ifdef __GNUC__ -#include -#include -#include -#include -#endif -#define DEFCOL 0xD0E0F0C0 // codes couleurs ANSI -#define BLACK 0 -#define RED FOREGROUND_RED -#define GREEN FOREGROUND_GREEN -#define BROWN FOREGROUND_GREEN|FOREGROUND_RED -#define BLUE FOREGROUND_BLUE -#define PURPLE FOREGROUND_RED|FOREGROUND_BLUE -#define CYAN FOREGROUND_BLUE|FOREGROUND_GREEN -#define LIGHTGRAY FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED -#define DARKGRAY FOREGROUND_INTENSITY -#define LIGHTRED FOREGROUND_RED|FOREGROUND_INTENSITY -#define LIGHTGREEN FOREGROUND_GREEN|FOREGROUND_INTENSITY -#define YELLOW FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY -#define LIGHTBLUE FOREGROUND_BLUE|FOREGROUND_INTENSITY -#define MAGENTA FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_INTENSITY -#define LIGHTCYAN FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY -#define WHITE FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY - -#else - -#define DEFCOL "\033[0m" // codes couleurs ANSI -#define BLACK "\033[0;30m" -#define RED "\033[0;31m" -#define GREEN "\033[0;32m" -#define BROWN "\033[0;33m" -#define BLUE "\033[0;34m" -#define PURPLE "\033[0;35m" -#define CYAN "\033[0;36m" -#define LIGHTGRAY "\033[0;37m" -#define DARKGRAY "\033[1;30m" -#define LIGHTRED "\033[1;31m" -#define LIGHTGREEN "\033[1;32m" -#define YELLOW "\033[1;33m" -#define LIGHTBLUE "\033[1;34m" -#define MAGENTA "\033[1;35m" -#define LIGHTCYAN "\033[1;36m" -#define WHITE "\033[1;37m" - -#endif - -typedef enum -{ - FE_SIGNAL_ERR, - FE_SELECT_ERR, - FE_READ_ERR, - FE_WRITE_ERR, - NUM_FATAL_ERROR -} fatal_error_t; - -// ================================== PROTOS ================================== - -void clearScreen(); -void fatalError(fatal_error_t); -void logPrintf(FILE *, const char *, ...); -#ifdef _WIN32 -void dbgPrintf(DWORDLONG col, const char *lpFmt, ...); -void conPrintf(DWORDLONG col, const char *lpFmt, ...); -#else -void dbgPrintf(const char *col, const char *lpFmt, ...); -void conPrintf(const char *col, const char *lpFmt, ...); -#endif -FILE *openFile(const char *filename); -const char *pCrypt(const char *pw, const char *salt); - -// ================================== STRINGS ================================= -void strrand(char *s, const int len); - -// ================================== EXTERNS ================================= -#endif diff --git a/tools/masterserver/crypt.cpp b/tools/masterserver/crypt.cpp deleted file mode 100644 index 4f15d3c89..000000000 --- a/tools/masterserver/crypt.cpp +++ /dev/null @@ -1,278 +0,0 @@ -#include "common.h" - -static SINT8 IP[] = -{ - 58,50,42,34,26,18,10, 2, - 60,52,44,36,28,20,12, 4, - 62,54,46,38,30,22,14, 6, - 64,56,48,40,32,24,16, 8, - 57,49,41,33,25,17, 9, 1, - 59,51,43,35,27,19,11, 3, - 61,53,45,37,29,21,13, 5, - 63,55,47,39,31,23,15, 7, -}; -static SINT8 FP[] = -{ - 40, 8,48,16,56,24,64,32, - 39, 7,47,15,55,23,63,31, - 38, 6,46,14,54,22,62,30, - 37, 5,45,13,53,21,61,29, - 36, 4,44,12,52,20,60,28, - 35, 3,43,11,51,19,59,27, - 34, 2,42,10,50,18,58,26, - 33, 1,41, 9,49,17,57,25, -}; -static SINT8 PC1_C[] = -{ - 57,49,41,33,25,17, 9, - 1,58,50,42,34,26,18, - 10, 2,59,51,43,35,27, - 19,11, 3,60,52,44,36, -}; -static SINT8 PC1_D[] = -{ - 63,55,47,39,31,23,15, - 7,62,54,46,38,30,22, - 14, 6,61,53,45,37,29, - 21,13, 5,28,20,12, 4, -}; -static SINT8 shifts[] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1}; -static SINT8 PC2_C[] = -{ - 14,17,11,24, 1, 5, - 3,28,15, 6,21,10, - 23,19,12, 4,26, 8, - 16, 7,27,20,13, 2, -}; -static SINT8 PC2_D[] = -{ - 41,52,31,37,47,55, - 30,40,51,45,33,48, - 44,49,39,56,34,53, - 46,42,50,36,29,32, -}; -static SINT8 C[28]; -static SINT8 D[28]; -static SINT8 KS[16][48]; -static SINT8 E[48]; -static SINT8 e2[] = -{ - 32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9,10,11,12,13, - 12,13,14,15,16,17, - 16,17,18,19,20,21, - 20,21,22,23,24,25, - 24,25,26,27,28,29, - 28,29,30,31,32, 1, -}; -static SINT8 S[8][64] = -{ - { - 14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7, - 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8, - 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0, - 15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13, - }, - { - 15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10, - 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5, - 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15, - 13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9, - }, - { - 10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8, - 13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1, - 13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7, - 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12, - }, - { - 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15, - 13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9, - 10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4, - 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14, - }, - { - 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9, - 14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6, - 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14, - 11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3, - }, - { - 12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11, - 10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8, - 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6, - 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13, - }, - { - 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1, - 13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6, - 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2, - 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12, - }, - { - 13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7, - 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2, - 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8, - 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11, - } -}; -static SINT8 P[] = -{ - 16, 7,20,21, - 29,12,28,17, - 1,15,23,26, - 5,18,31,10, - 2, 8,24,14, - 32,27, 3, 9, - 19,13,30, 6, - 22,11, 4,25, -}; -static SINT8 L[64], *R = L + 32; -static SINT8 tempL[32]; -static SINT8 f[32]; -static SINT8 preS[48]; - -//======================================================================= - -static void setKey(const SINT8 *key) -{ - register INT32 i, j, k; - INT32 t; - - for (i = 0; i < 28; i++) - { - C[i] = key[PC1_C[i]-1]; - D[i] = key[PC1_D[i]-1]; - } - for (i = 0; i < 16; i++) - { - for (k = 0; k < shifts[i]; k++) - { - t = C[0]; - for (j = 0; j < 28-1; j++) - C[j] = C[j+1]; - C[27] = t; - t = D[0]; - for (j = 0; j < 28-1; j++) - D[j] = D[j+1]; - D[27] = t; - } - for (j = 0; j < 24; j++) - { - KS[i][j] = C[PC2_C[j]-1]; - KS[i][j+24] = D[PC2_D[j]-28-1]; - } - } - for (i = 0; i < 48; i++) - E[i] = e2[i]; -} - -void enCrypt(SINT8 *block) -{ - INT32 i, ii; - register INT32 t, j, k; - - for (j = 0; j < 64; j++) - L[j] = block[IP[j]-1]; - for (ii = 0; ii < 16; ii++) - { - i = ii; - for (j = 0; j < 32; j++) - tempL[j] = R[j]; - for (j = 0; j < 48; j++) - preS[j] = R[E[j]-1] ^ KS[i][j]; - for (j = 0; j < 8; j++) - { - t = 6*j; - k = S[j][(preS[t+0]<<5)+ - (preS[t+1]<<3)+ - (preS[t+2]<<2)+ - (preS[t+3]<<1)+ - (preS[t+4]<<0)+ - (preS[t+5]<<4)]; - t = 4*j; - f[t+0] = (k>>3)&01; - f[t+1] = (k>>2)&01; - f[t+2] = (k>>1)&01; - f[t+3] = (k>>0)&01; - } - for (j = 0; j < 32; j++) - R[j] = L[j] ^ f[P[j]-1]; - for (j = 0; j < 32; j++) - L[j] = tempL[j]; - } - for (j = 0; j < 32; j++) - { - t = L[j]; - L[j] = R[j]; - R[j] = t; - } - for (j = 0; j < 64; j++) - block[j] = L[FP[j]-1]; -} - -const char *pCrypt(const char *pw, const char *salt) -{ - register INT32 i, j, c; - INT32 temp; - static SINT8 block[66]; - static char iobuf[16]; - - for (i = 0; i < 66; i++) - block[i] = 0; - for (i = 0; (c = *pw) != '\0' && i < 64; pw++) - { - for (j = 0; j < 7; j++, i++) - block[i] = (c>>(6-j)) & 01; - i++; - } - - setKey(block); - - for (i = 0; i < 66; i++) - block[i] = 0; - - for (i = 0; i < 2; i++) - { - c = *salt++; - iobuf[i] = c; - if (c > 'Z') - c -= 6; - if (c > '9') - c -= 7; - c -= '.'; - for (j = 0; j < 6; j++) - { - if ((c>>j) & 01) - { - temp = E[6*i+j]; - E[6*i+j] = E[6*i+j+24]; - E[6*i+j+24] = temp; - } - } - } - - for (i = 0; i < 25; i++) - enCrypt(block); - - for (i = 0; i < 11; i++) - { - c = 0; - for (j = 0; j < 6; j++) - { - c <<= 1; - c |= block[6*i+j]; - } - c += '.'; - if (c > '9') - c += 7; - if (c > 'Z') - c += 6; - iobuf[i+2] = c; - } - iobuf[i+2] = 0; - if (iobuf[1] == 0) - iobuf[1] = iobuf[0]; - return(iobuf); -} diff --git a/tools/masterserver/ipcs.cpp b/tools/masterserver/ipcs.cpp deleted file mode 100644 index 4c3c6de74..000000000 --- a/tools/masterserver/ipcs.cpp +++ /dev/null @@ -1,595 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#ifdef __GNUC__ -#include -#endif - -#ifdef _WIN32 -//#include -#else -#include // socket(),... -#include // socket(),... -#endif -#include // atoi(),... -#include // signal(),... -#ifndef _WIN32 -#include // gethostbyname(),... -#endif -#ifdef _WIN32 -#include -#else -#include // timeval,... (TIMEOUT) -#endif -#include // memset(),... -#include "ipcs.h" -#include "common.h" - -typedef void Sigfunc(int); - -#ifndef _WIN32 -static void sigHandler(int signr); -static Sigfunc *mySignal(int signo, Sigfunc *func); -#endif - -#ifdef _MSC_VER -#pragma warning(disable : 4127) -#endif -//============================================================================= - -#if defined (_WIN32) || defined (__OS2__) -// it seems windows doesn't define that... maybe some other OS? OS/2 -static int inet_aton(const char *hostname, struct in_addr *addr) -{ - return ((addr->s_addr=inet_addr(hostname)) != INADDR_NONE); -} -#endif - -/* -** CSocket() -*/ -CSocket::CSocket() -{ - dbgPrintf(DEFCOL, "Initializing socket... "); -#ifdef _WIN32 -//#warning SIGPIPE needed - WSADATA winsockdata; - if (WSAStartup(MAKEWORD(1, 1), &winsockdata)) - conPrintf(RED,"No TCP/IP driver detected"); -#else - signal(SIGPIPE, sigHandler); -#endif - FD_ZERO(&rset); - memset(&addr, 0, sizeof (addr)); - addr.sin_family = AF_INET; - dbgPrintf(DEFCOL, "DONE1.\n"); -} - -/* -** ~CSocket() -*/ -CSocket::~CSocket() -{ - dbgPrintf(DEFCOL, "Freeing socket... "); -#ifdef _WIN32 - WSACleanup(); -#endif - dbgPrintf(DEFCOL, "DONE2.\n"); -} - -/* -** getIP() -*/ -int CSocket::getIP(const char *ip_addr) -{ - struct hostent *host_ent; - - dbgPrintf(DEFCOL, "get IP for %s... ", ip_addr); - if (!inet_aton(ip_addr, &addr.sin_addr)) - { - host_ent = gethostbyname(ip_addr); - if (host_ent == NULL) - return GETHOSTBYNAME_ERROR; - memcpy(&addr.sin_addr, host_ent->h_addr_list[0], - sizeof (struct in_addr)); - } - dbgPrintf(DEFCOL, "got %s. ", inet_ntoa(addr.sin_addr)); - dbgPrintf(DEFCOL, "DONE3.\n"); - return 0; -} - -/* -** CClientSocket() -*/ -CClientSocket::CClientSocket() -{ - dbgPrintf(DEFCOL, "Initializing client socket... "); - socket_fd = (SOCKET)-1; - dbgPrintf(DEFCOL, "DONE4.\n"); -} - -/* -** ~CClientSocket() -*/ -CClientSocket::~CClientSocket() -{ - dbgPrintf(DEFCOL, "Freeing client socket... "); - if (socket_fd != (SOCKET)-1) - close(socket_fd); - dbgPrintf(DEFCOL, "DONE5.\n"); -} - -/* -** connect() -*/ -int CClientSocket::connect(const char *ip_addr, const char *str_port) -{ - dbgPrintf(DEFCOL, "Connect to %s %s...\n", ip_addr, str_port); - - // put that in the constructor? - if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == (SOCKET)-1) - return SOCKET_ERROR; - - if (getIP(ip_addr) == GETHOSTBYNAME_ERROR) - return GETHOSTBYNAME_ERROR; - addr.sin_port = htons(atoi(str_port)); - - if (::connect(socket_fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) - return CONNECT_ERROR; - - FD_SET(socket_fd, &rset); - - dbgPrintf(DEFCOL, "DONE6.\n"); - - return 0; -} - -/* - * write() - */ -int CClientSocket::write(msg_t *msg) -{ - int len; - - if (msg->length < 0) - msg->length = (INT32)strlen(msg->buffer); - if (msg->length > PACKET_SIZE) - return WRITE_ERROR; // too big - len = msg->length + HEADER_SIZE; - - msg->id = htonl(msg->id); - msg->type = htonl(msg->type); - msg->length = htonl(msg->length); - msg->room = htonl(msg->room); - - dbgPrintf(DEFCOL, "Write a message %d (%s)... ", len, msg->buffer); - - if (send(socket_fd, (const char *)msg, len, 0) != len) - return WRITE_ERROR; - - dbgPrintf(DEFCOL, "DONE7.\n"); - - return 0; -} - -/* - * read() - */ -int CClientSocket::read(msg_t *msg) -{ - struct timeval timeout; - fd_set tset; - - dbgPrintf(DEFCOL, "Waiting a message... "); - - timeout.tv_sec = 60, timeout.tv_usec = 0; - memcpy(&tset, &rset, sizeof (tset)); - if ((select(255, &tset, NULL, NULL, &timeout)) <= 0) - return TIMEOUT_ERROR; - - if (!FD_ISSET(socket_fd, &tset)) - return READ_ERROR; - - dbgPrintf(DEFCOL, "Reading a message.\n"); - - if (recv(socket_fd, (char *)msg, HEADER_SIZE, 0) != HEADER_SIZE) - return READ_ERROR; - - msg->id = ntohl(msg->id); - msg->type = ntohl(msg->type); - msg->length = ntohl(msg->length); - msg->room = ntohl(msg->room); - - if (!msg->length) // work around a bug in Windows 2000 - return 0; - - if (msg->length > PACKET_SIZE) - return READ_ERROR; // packet too big - - if (recv(socket_fd, msg->buffer, msg->length, 0) != msg->length) - return READ_ERROR; - - dbgPrintf(DEFCOL, "DONE8.\n"); - - return 0; -} - -/* -** CServerSocket() -*/ -CServerSocket::CServerSocket() -{ - size_t id; - dbgPrintf(DEFCOL, "Initializing server socket... "); - num_clients = 0; - accept_fd = udp_fd = (SOCKET)-1; - for (id = 0; id < MAX_CLIENT; id++) - client_fd[id] = (SOCKET)-1; - udp_addr.sin_family = AF_INET; - dbgPrintf(DEFCOL, "DONE9.\n"); -} - -/* -** ~CServerSocket() -*/ -CServerSocket::~CServerSocket() -{ - size_t id; - dbgPrintf(DEFCOL, "Freeing server socket... "); - if (udp_fd != (SOCKET)-1) - close(udp_fd); - if (accept_fd != (SOCKET)-1) - close(accept_fd); - for (id = 0; id < num_clients || id < MAX_CLIENT; id++) - if (client_fd[id] != (SOCKET)-1) - close(client_fd[id]); - dbgPrintf(DEFCOL, "DONE10.\n"); -} - -/* -** listen() -*/ -int CServerSocket::listen(const char *str_port) -{ - dbgPrintf(DEFCOL, "Listen on %s... ", str_port); - // Init TCP socket - if ((accept_fd = socket(AF_INET, SOCK_STREAM, 0)) == (SOCKET)-1) - return SOCKET_ERROR; - int one = 1; setsockopt(accept_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&one, sizeof(int)); - - addr.sin_addr.s_addr = htonl(INADDR_ANY); - addr.sin_port = htons(atoi(str_port)); - - if (bind(accept_fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) - return BIND_ERROR; - - if (::listen(accept_fd, 5) < 0) - return LISTEN_ERROR; - - FD_SET(accept_fd, &rset); - - // Init UDP socket - if ((udp_fd = socket(AF_INET, SOCK_DGRAM, 0)) == (SOCKET)-1) - return SOCKET_ERROR; - - udp_addr.sin_addr.s_addr = htonl(INADDR_ANY); - udp_addr.sin_port = htons(atoi(str_port)+1); - - if (bind(udp_fd, (struct sockaddr *) &udp_addr, sizeof (udp_addr)) < 0) - return BIND_ERROR; - - FD_SET(udp_fd, &rset); - - dbgPrintf(DEFCOL, "DONE11.\n"); - - return 0; -} - -/* - * deleteClient(): - */ -int CServerSocket::deleteClient(size_t id) -{ - dbgPrintf(DEFCOL, "Deleting (client %u) of %u... ", id+1, num_clients); - FD_CLR(client_fd[id], &rset); - close(client_fd[id]); - if (num_clients != 0) - num_clients--; - client_fd[id] = client_fd[num_clients]; // move the top socket into this now empty space - memmove(&client_addr[id], &client_addr[num_clients], sizeof (client_addr[num_clients])); - client_fd[num_clients] = (SOCKET)-1; // now empty the top socket - memset(&client_addr[num_clients], 0 , sizeof (client_addr[num_clients])); - - dbgPrintf(DEFCOL, "DONE12.\n"); - - return 0; -} - -/* - * getUdpIP() - */ -const char *CServerSocket::getUdpIP(void) -{ - return inet_ntoa(udp_in_addr.sin_addr); -} - -/* - * getUdpPort() - */ -const char *CServerSocket::getUdpPort(bool offset) -{ - static char buffer[8]; - UINT16 port = htons(udp_in_addr.sin_port); - if (offset) - port--; - snprintf(buffer, sizeof buffer, "%d", port); - return buffer; -} - -/* - * read(): wait message on a socket, if it's an accept, call the accept method, - * otherwise read the message and update msg->id to the right value - * (client cannot put valid entry in msg->id) - */ -int CServerSocket::read(msg_t *msg) -{ - struct timeval timeout; - fd_set tset; - UINT32 id; - socklen_t lg = sizeof (addr); - - timeout.tv_sec = 20, timeout.tv_usec = 0; - memcpy(&tset, &rset, sizeof (tset)); - if ((select(255, &tset, NULL, NULL, &timeout)) <= 0) - { - msg->type = TIMEOUT_MSG; - return TIMEOUT_ERROR; - } - - if (FD_ISSET(udp_fd, &tset)) - { - msg->type = UDP_RECV_MSG; // This is a UDP packet - msg->length = recvfrom(udp_fd, msg->buffer, PACKET_SIZE, 0, (struct sockaddr *)&udp_in_addr, &lg); - return 0; - } - - if (FD_ISSET(accept_fd, &tset)) - { - msg->type = ACCEPT_MSG; - return this->accept(); - } - - id = 0; - while (!FD_ISSET(client_fd[id], &tset) && id < MAX_CLIENT) - id++; - - // paranoia - if ( (id >= num_clients) || (id >= MAX_CLIENT) ) - { - dbgPrintf(DEFCOL, "This should never happen\n"); - return READ_ERROR; - } - - dbgPrintf(DEFCOL, "Reading a message from (socket %u) for (client %u)... ", client_fd[id], id+1); - - if (recv(client_fd[id], (char *)msg, HEADER_SIZE, 0) != HEADER_SIZE) - { - deleteClient(id); // the connection is not good with the client, kick him - return READ_ERROR; - } - - //msg->id = ntohl(msg->id); // see comment above - msg->type = ntohl(msg->type); - msg->length = ntohl(msg->length); - msg->room = ntohl(msg->room); - - if ((0 < msg->length) && (msg->length < PACKET_SIZE)) - { - timeout.tv_sec = 0, timeout.tv_usec = 0; // the info should be already in the socket, so don't wait - memcpy(&tset, &rset, sizeof (tset)); - if ((select(255, &tset, NULL, NULL, &timeout)) <= 0) - { - deleteClient(id); - return READ_ERROR; - } - - if (!FD_ISSET(client_fd[id], &tset)) - { - deleteClient(id); - return READ_ERROR; - } - if (recv(client_fd[id], msg->buffer, msg->length, 0) != msg->length) - { - deleteClient(id); - return READ_ERROR; - } - } - - msg->id = id; - - dbgPrintf(DEFCOL, "DONE13.\n"); - - return 0; -} - -/* - * write(): - */ -int CServerSocket::write(msg_t *msg) -{ - struct timeval timeout; - fd_set tset; - int len; - - dbgPrintf(DEFCOL, "Write a message... "); - FD_ZERO(&tset); - /* - * Be sure the msg->id is still valid; we cannot do - * a delete between a read and a write. Should we - * use a readpending set in read method, so we know - * that we are still waiting for writing? For now, - * it's the responsibility of server code. - */ - FD_SET(client_fd[msg->id], &tset); - timeout.tv_sec = 0, timeout.tv_usec = 0; - if ((select(255, NULL, &tset, NULL, &timeout)) <= 0) - { - deleteClient(msg->id); // this shouldn't happen if the net connection is good - return TIMEOUT_ERROR; - } - if (msg->length < 0) - msg->length = (INT32)strlen(msg->buffer); - if (msg->length > PACKET_SIZE) - return WRITE_ERROR; // too big - len = msg->length+HEADER_SIZE; - //msg->id = htonl(msg->id); // same comment as for read - msg->type = htonl(msg->type); - msg->length = htonl(msg->length); - if (send(client_fd[msg->id], (const char *)msg, len, 0) != len) - { - deleteClient(msg->id); - return WRITE_ERROR; - } - - dbgPrintf(DEFCOL, "DONE14.\n"); - - return 0; -} - -/* - * writeUDP() - */ -int CServerSocket::writeUDP(const char *data, size_t length, const char *ip, UINT16 port) -{ - sockaddr_in sin; - struct timeval timeout; - fd_set tset; - - FD_ZERO(&tset); - FD_SET(udp_fd, &tset); - - if ((select(255, NULL, &tset, NULL, &timeout)) <= 0) - { - return TIMEOUT_ERROR; - } - - sin.sin_family = AF_INET; - inet_aton(ip, &sin.sin_addr); - sin.sin_port = htons(port); - - sendto(udp_fd, data, (int)length, 0, (sockaddr*)&sin, sizeof(sin)); - - return 0; -} - - -/* - * accept() - */ -int CServerSocket::accept() -{ - socklen_t lg = sizeof (addr); - - dbgPrintf(DEFCOL, "Accepting on (socket %u)... ", accept_fd); - - if ((client_fd[num_clients] = ::accept(accept_fd, (struct sockaddr *) &addr, &lg)) == (SOCKET)-1) - { - //client_fd[num_clients] = (SOCKET)-1; // we haven't accepted the client, so set it at default value - return ACCEPT_ERROR; - } - - if (num_clients < MAX_CLIENT-1) - { - extern FILE *sockfile; - - logPrintf(sockfile, "Accepting on socket %u for client %u (%s:%i)\n", - client_fd[num_clients], num_clients+1, inet_ntoa(addr.sin_addr), htons(addr.sin_port)); - memcpy(&client_addr[num_clients], &addr, sizeof (addr)); - FD_SET(client_fd[num_clients], &rset); - num_clients++; - } - else // we have reached the maximum number of clients - { - // close the connection (meaning "try again" for the client) - close(client_fd[num_clients]); - client_fd[num_clients] = (SOCKET)-1; - return ACCEPT_ERROR; - } - - //dbgPrintf(DEFCOL, "DONE15.\n"); - - return 0; -} - -/* - * getClientIP() - */ -const char *CServerSocket::getClientIP(size_t id) -{ - dbgPrintf(DEFCOL, "getClientIP: %u\n", id); - return inet_ntoa(client_addr[id].sin_addr); -} - -/* - * getClientPort() - */ -const char *CServerSocket::getClientPort(size_t id) -{ - static char buffer[8]; - - dbgPrintf(DEFCOL, "getClientPort: %u\n", id); - UINT16 port = htons(client_addr[id].sin_port); - snprintf(buffer, sizeof buffer, "%d", port); - return buffer; -} - -/* - * mySignal() - */ -#ifndef _WIN32 -static Sigfunc *mySignal(int signo, Sigfunc *func) -{ - struct sigaction act, oact; - - act.sa_handler = func; - sigemptyset(&act.sa_mask); -#if defined (SA_RESTART) - act.sa_flags = SA_RESTART; -#else - act.sa_flags = 0; -#endif - if (sigaction(signo, &act, &oact) < 0) - return SIG_ERR; - return oact.sa_handler; -} - -/* - * sigHandler() - */ -static void sigHandler(int signr) -{ - mySignal(signr, sigHandler); - switch (signr) - { - case SIGPIPE: - dbgPrintf(DEFCOL, "Catch SIG_PIPE\n"); - /// TODO be sure the socket is closed if the client - /// didn't quit properly - break; - } -} -#endif diff --git a/tools/masterserver/ipcs.h b/tools/masterserver/ipcs.h deleted file mode 100644 index b9dc52fdf..000000000 --- a/tools/masterserver/ipcs.h +++ /dev/null @@ -1,281 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#ifndef _IPCS_H_ -#define _IPCS_H_ - -#include "common.h" - -#if defined (_WIN32) || defined ( __OS2__) -#include -#include -typedef int socklen_t; -#if defined (__OS2__) -#include -#endif -#endif -#ifdef _WIN32 -#include -#define close closesocket -#else -#include // inet_addr(),... -#endif - -#ifndef SOCKET -#define SOCKET u_int -#endif - -// ================================ DEFINITIONS =============================== - -#define PACKET_SIZE 1024 -#define MAX_CLIENT 512 - -#ifndef _WIN32 -#define NO_ERROR 0 -#define SOCKET_ERROR -201 -#endif -#define BIND_ERROR -202 -#define CONNECT_ERROR -203 -#define LISTEN_ERROR -204 -#define ACCEPT_ERROR -205 -#define WRITE_ERROR -210 -#define READ_ERROR -211 -#define CLOSE_ERROR -212 -#define GETHOSTBYNAME_ERROR -220 -#define SELECT_ERROR -230 -#define TIMEOUT_ERROR -231 -#define MALLOC_ERROR -301 - -#define INVALID_MSG -1 -#define ACCEPT_MSG 100 -#define ADD_SERVER_MSG 101 -#define ADD_CLIENT_MSG 102 -#define REMOVE_SERVER_MSG 103 -#define ADD_SERVERv2_MSG 104 -#define GET_SERVER_MSG 200 -#define SEND_SERVER_MSG 201 -#define GET_LOGFILE_MSG 202 -#define SEND_FILE_MSG 203 -#define ERASE_LOGFILE_MSG 204 -#define GET_SHORT_SERVER_MSG 205 -#define SEND_SHORT_SERVER_MSG 206 -#define ASK_SERVER_MSG 206 -#define ANSWER_ASK_SERVER_MSG 207 -#define GET_MOTD_MSG 208 -#define SEND_MOTD_MSG 209 -#define GET_ROOMS_MSG 210 -#define SEND_ROOMS_MSG 211 -#define GET_ROOMS_HOST_MSG 212 -#define GET_VERSION_MSG 213 -#define SEND_VERSION_MSG 214 -#define GET_BANNED_MSG 215 -#define PING_SERVER_MSG 216 - -#define UDP_RECV_MSG 300 -#define TIMEOUT_MSG 301 -#define HTTP_REQUEST_MSG 875770417 // "4321" -#define SEND_HTTP_REQUEST_MSG 875770418 // "4322" -#define TEXT_REQUEST_MSG 825373494 // "1236" -#define SEND_TEXT_REQUEST_MSG 825373495 // "1237" -#define RSS92_REQUEST_MSG 825373496 // "1238" -#define SEND_RSS92_REQUEST_MSG 825373497 // "1239" -#define RSS10_REQUEST_MSG 825373744 // "1240" -#define SEND_RSS10_REQUEST_MSG 825373745 // "1241" -#define ADD_PSERVER_MSG 0xabacab81 // this number just need to be different than the others -#define REMOVE_PSERVER_MSG 0xabacab82 - -// Sent FROM Client -#define LIVE_AUTH_USER 600 -#define LIVE_AUTH_KEY 601 -#define LIVE_GET_USER 602 -#define LIVE_UPDATE_LOCATION 603 -#define LIVE_UPDATE_PUBLIC_KEY 604 -#define LIVE_AUTH_PUBLIC_KEY 605 - -// Sent TO Client -#define LIVE_INVALID_KEY 800 -#define LIVE_INVALID_USER 801 -#define LIVE_AUTHORISED_KEY 802 -#define LIVE_SEND_USER 803 -#define LIVE_VALIDATED_USER 804 - -// Location Types -#define LIVE_LOCATION_SP 100 -#define LIVE_LOCATION_MENU 101 -#define LIVE_LOCATION_MP_JOIN 102 -#define LIVE_LOCATION_MP_HOST 103 -#define LIVE_LOCATION_MP_LOCAL 104 -#define LIVE_LOCATION_MP_PRIVATE 105 - -#define HEADER_SIZE ((UINT32)sizeof (UINT32)*4) - -#define HEADER_MSG_POS 0 -#define IP_MSG_POS 16 -#define PORT_MSG_POS 32 -#define HOSTNAME_MSG_POS 40 - -#if defined(_MSC_VER) -#pragma pack(1) -#endif - -// Keep this structure 8 bytes aligned (current size is 80) -typedef struct -{ - char header[16]; // information such as password - char ip[16]; - char port[8]; - char name[32]; - INT32 room; - char key[32]; // Secret key for linking dedicated servers to accounts - char version[8]; // format is: x.yy.z (like 1.30.2 or 1.31) -} ATTRPACK msg_server_t; - -typedef struct -{ - char header[16]; - UINT32 id; - char name[32]; - char motd[256]; -} ATTRPACK msg_rooms_t; - -typedef struct -{ - char header[16]; - char ipstart[16]; - char ipend[16]; - char endstamp[32]; - char reason[256]; - UINT8 hostonly; -} ATTRPACK msg_ban_t; - -typedef struct -{ - char header[16]; - INT32 id; - char username[100]; - char password[32]; -} ATTRPACK msg_live_auth_t; - -typedef struct -{ - char header[16]; - INT32 uid; - char username[100]; - INT32 location_type; - char location_ip[32]; - INT32 location_port; - INT32 lastseen_type; - char lastseen_data1[256]; - char lastseen_data2[256]; - char lastseen_data3[256]; -} ATTRPACK msg_live_user_t; - -typedef struct -{ - char header[16]; - UINT8 location_type; - char location_ip[32]; - INT32 location_port; - char location_data1[256]; - char location_data2[256]; - char location_data3[256]; -} ATTRPACK msg_live_updatelocation_t; - -typedef struct -{ - char header[16]; - char publickey[256]; - char username[256]; -} ATTRPACK msg_live_validateuser_t; - -typedef struct -{ - char header[16]; - char username[256]; - UINT8 keytype; - char keydata[256]; -} ATTRPACK msg_live_update_key_t; - - -typedef struct -{ - UINT32 id; - INT32 type; - INT32 room; - INT32 length; - char buffer[PACKET_SIZE]; -} ATTRPACK msg_t; - -#if defined(_MSC_VER) -#pragma pack() -#endif - -class CSocket -{ -protected: - sockaddr_in addr; - msg_t msg; - fd_set rset; -public: - int getIP(const char *); - CSocket(); - ~CSocket(); -}; - -class CServerSocket : public CSocket -{ -private: - sockaddr_in udp_addr; - sockaddr_in udp_in_addr; - SOCKET udp_fd; - SOCKET accept_fd; - size_t num_clients; - SOCKET client_fd[MAX_CLIENT]; - sockaddr_in client_addr[MAX_CLIENT]; - -public: - int deleteClient(size_t id); - int listen(const char *str_port); - int accept(void); - int read(msg_t *msg); - const char *getUdpIP(void); - const char *getUdpPort(bool); - int write(msg_t *msg); - int writeUDP(const char *data, size_t length, const char *ip, UINT16 port); - const char *getClientIP(size_t id); - const char *getClientPort(size_t id); - CServerSocket(void); - ~CServerSocket(void); -}; - -class CClientSocket : public CSocket -{ -private: - SOCKET socket_fd; -public: - int connect(const char *ip_addr, const char *str_port); - int read(msg_t *msg); - int write(msg_t *msg); - CClientSocket(void); - ~CClientSocket(void); -}; - -// ================================== PROTOS ================================== - -// ================================== EXTERNS ================================= - -#endif diff --git a/tools/masterserver/masterserver.sh b/tools/masterserver/masterserver.sh deleted file mode 100755 index 9b1adb128..000000000 --- a/tools/masterserver/masterserver.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/sh -e -# -# SRB2 MasterServer - start up the masterserver -# - -# Get LSB functions -. /lib/lsb/init-functions -. /etc/default/rcS - -SRB2MS=/usr/local/bin/masterserver -SRB2MS_PORT=28900 - -# Check that the package is still installed -[ -x $SRB2MS ] || exit 0; - -case "$1" in - start) - log_begin_msg "Starting SRB2MS..." - umask 002 - if start-stop-daemon --start \ - --exec $SRB2MS \ - -- $SRB2MS_PORT; then - log_end_msg 0 - else - log_end_msg $? - fi - ;; - - stop) - log_begin_msg "Stopping SRB2MS..." - if start-stop-daemon --stop --exec $SRB2MS; then - log_end_msg 0 - else - log_end_msg $? - fi - ;; - - restart|force-reload) - "$0" stop && "$0" start - ;; - - *) - e cho "Usage: /etc/init.d/masterserver {start|stop|restart|force-reload}" - exit 1 - ;; -esac - -exit 0 diff --git a/tools/masterserver/md5.cpp b/tools/masterserver/md5.cpp deleted file mode 100644 index 4f4ff2292..000000000 --- a/tools/masterserver/md5.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* MD5 - converted to C++ class by Frank Thilo (thilo@unix-ag.org) - for bzflag (http://www.bzflag.org) - - based on: - - md5.h and md5.c - reference implemantion of RFC 1321 - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - -*/ - -/* interface header */ -#include "md5.h" - -/* system implementation headers */ -#include -#include - - -// Constants for MD5Transform routine. -#define S11 7 -#define S12 12 -#define S13 17 -#define S14 22 -#define S21 5 -#define S22 9 -#define S23 14 -#define S24 20 -#define S31 4 -#define S32 11 -#define S33 16 -#define S34 23 -#define S41 6 -#define S42 10 -#define S43 15 -#define S44 21 - -/////////////////////////////////////////////// - -// F, G, H and I are basic MD5 functions. -inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { - return (x&y) | (~x&z); -} - -inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { - return (x&z) | (y&~z); -} - -inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { - return x^y^z; -} - -inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { - return y ^ (x | ~z); -} - -// rotate_left rotates x left n bits. -inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { - return (x << n) | (x >> (32-n)); -} - -// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. -// Rotation is separate from addition to prevent recomputation. -inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a+ F(b,c,d) + x + ac, s) + b; -} - -inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + G(b,c,d) + x + ac, s) + b; -} - -inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + H(b,c,d) + x + ac, s) + b; -} - -inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + I(b,c,d) + x + ac, s) + b; -} - -////////////////////////////////////////////// - -// default ctor, just initailize -MD5::MD5() -{ - init(); -} - -////////////////////////////////////////////// - -// nifty shortcut ctor, compute MD5 for string and finalize it right away -MD5::MD5(const std::string &text) -{ - init(); - update(text.c_str(), text.length()); - finalize(); -} - -////////////////////////////// - -void MD5::init() -{ - finalized=false; - - count[0] = 0; - count[1] = 0; - - // load magic initialization constants. - state[0] = 0x67452301; - state[1] = 0xefcdab89; - state[2] = 0x98badcfe; - state[3] = 0x10325476; -} - -////////////////////////////// - -// decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. -void MD5::decode(uint4 output[], const uint1 input[], size_type len) -{ - for (unsigned int i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) | - (((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24); -} - -////////////////////////////// - -// encodes input (uint4) into output (unsigned char). Assumes len is -// a multiple of 4. -void MD5::encode(uint1 output[], const uint4 input[], size_type len) -{ - for (size_type i = 0, j = 0; j < len; i++, j += 4) { - output[j] = input[i] & 0xff; - output[j+1] = (input[i] >> 8) & 0xff; - output[j+2] = (input[i] >> 16) & 0xff; - output[j+3] = (input[i] >> 24) & 0xff; - } -} - -////////////////////////////// - -// apply MD5 algo on a block -void MD5::transform(const uint1 block[blocksize]) -{ - uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - decode (x, block, blocksize); - - /* Round 1 */ - FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ - FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ - FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ - FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ - FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ - GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ - HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ - HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ - II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ - II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ - II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ - II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ - II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ - II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - // Zeroize sensitive information. - memset(x, 0, sizeof x); -} - -////////////////////////////// - -// MD5 block update operation. Continues an MD5 message-digest -// operation, processing another message block -void MD5::update(const unsigned char input[], size_type length) -{ - // compute number of bytes mod 64 - size_type index = count[0] / 8 % blocksize; - - // Update number of bits - if ((count[0] += (length << 3)) < (length << 3)) - count[1]++; - count[1] += (length >> 29); - - // number of bytes we need to fill in buffer - size_type firstpart = 64 - index; - - size_type i; - - // transform as many times as possible. - if (length >= firstpart) - { - // fill buffer first, transform - memcpy(&buffer[index], input, firstpart); - transform(buffer); - - // transform chunks of blocksize (64 bytes) - for (i = firstpart; i + blocksize <= length; i += blocksize) - transform(&input[i]); - - index = 0; - } - else - i = 0; - - // buffer remaining input - memcpy(&buffer[index], &input[i], length-i); -} - -////////////////////////////// - -// for convenience provide a verson with signed char -void MD5::update(const char input[], size_type length) -{ - update((const unsigned char*)input, length); -} - -////////////////////////////// - -// MD5 finalization. Ends an MD5 message-digest operation, writing the -// the message digest and zeroizing the context. -MD5& MD5::finalize() -{ - static unsigned char padding[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - if (!finalized) { - // Save number of bits - unsigned char bits[8]; - encode(bits, count, 8); - - // pad out to 56 mod 64. - size_type index = count[0] / 8 % 64; - size_type padLen = (index < 56) ? (56 - index) : (120 - index); - update(padding, padLen); - - // Append length (before padding) - update(bits, 8); - - // Store state in digest - encode(digest, state, 16); - - // Zeroize sensitive information. - memset(buffer, 0, sizeof buffer); - memset(count, 0, sizeof count); - - finalized=true; - } - - return *this; -} - -////////////////////////////// - -// return hex representation of digest as string -std::string MD5::hexdigest() const -{ - if (!finalized) - return ""; - - char buf[33]; - for (int i=0; i<16; i++) - sprintf(buf+i*2, "%02x", digest[i]); - buf[32]=0; - - return std::string(buf); -} - -////////////////////////////// - -std::ostream& operator<<(std::ostream& out, MD5 md5) -{ - return out << md5.hexdigest(); -} - -////////////////////////////// - -std::string md5(const std::string str) -{ - MD5 md5 = MD5(str); - - return md5.hexdigest(); -} diff --git a/tools/masterserver/md5.h b/tools/masterserver/md5.h deleted file mode 100644 index 55a90c4cb..000000000 --- a/tools/masterserver/md5.h +++ /dev/null @@ -1,93 +0,0 @@ -/* MD5 - converted to C++ class by Frank Thilo (thilo@unix-ag.org) - for bzflag (http://www.bzflag.org) - - based on: - - md5.h and md5.c - reference implementation of RFC 1321 - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - -*/ - -#ifndef BZF_MD5_H -#define BZF_MD5_H - -#include -#include - - -// a small class for calculating MD5 hashes of strings or byte arrays -// it is not meant to be fast or secure -// -// usage: 1) feed it blocks of uchars with update() -// 2) finalize() -// 3) get hexdigest() string -// or -// MD5(std::string).hexdigest() -// -// assumes that char is 8 bit and int is 32 bit -class MD5 -{ -public: - typedef unsigned int size_type; // must be 32bit - - MD5(); - MD5(const std::string& text); - void update(const unsigned char *buf, size_type length); - void update(const char *buf, size_type length); - MD5& finalize(); - std::string hexdigest() const; - friend std::ostream& operator<<(std::ostream&, MD5 md5); - -private: - void init(); - typedef unsigned char uint1; // 8bit - typedef unsigned int uint4; // 32bit - enum {blocksize = 64}; // VC6 won't eat a const static int here - - void transform(const uint1 block[blocksize]); - static void decode(uint4 output[], const uint1 input[], size_type len); - static void encode(uint1 output[], const uint4 input[], size_type len); - - bool finalized; - uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk - uint4 count[2]; // 64bit counter for number of bits (lo, hi) - uint4 state[4]; // digest so far - uint1 digest[16]; // the result - - // low level logic operations - static inline uint4 F(uint4 x, uint4 y, uint4 z); - static inline uint4 G(uint4 x, uint4 y, uint4 z); - static inline uint4 H(uint4 x, uint4 y, uint4 z); - static inline uint4 I(uint4 x, uint4 y, uint4 z); - static inline uint4 rotate_left(uint4 x, int n); - static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); -}; - -std::string md5(const std::string str); - -#endif diff --git a/tools/masterserver/server.cpp b/tools/masterserver/server.cpp deleted file mode 100644 index b7ed0d6b4..000000000 --- a/tools/masterserver/server.cpp +++ /dev/null @@ -1,1037 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- -#ifdef __GNUC__ -#include -#include -#endif -#include -#include -#include -#include "ipcs.h" -#include "common.h" -#include "mysql.h" -#include "md5.h" -#include -//#include - -//============================================================================= - -#ifdef __GNUC__ -#define ATTRPACK __attribute__ ((packed)) -#else -#define ATTRPACK -#endif - -#define PT_ASKINFOVIAMS 15 - -static CServerSocket server_socket; - -FILE *logfile; -FILE *errorfile; -FILE *mysqlfile; -FILE *sockfile; -FILE *pidfile; - -#if defined(_MSC_VER) -#pragma pack(1) -#endif - -typedef struct -{ - char ip[16]; // Big enough to hold a full address. - UINT16 port; - UINT8 padding1[2]; - UINT32 time; -} ATTRPACK ms_holepunch_packet_t; - -typedef struct -{ - char clientaddr[22]; - UINT8 padding1[2]; - UINT32 time; -} ATTRPACK msaskinfo_pak; - -// -// SRB2 network packet data. -// -typedef struct -{ - UINT32 checksum; - UINT8 ack; // if not null the node asks for acknowledgement, the receiver must resend the ack - UINT8 ackreturn; // the return of the ack number - - UINT8 packettype; - UINT8 reserved; // padding - - msaskinfo_pak msaskinfo; -} ATTRPACK doomdata_t; - -#if defined(_MSC_VER) -#pragma pack() -#endif - -//============================================================================= - -#define HOSTNAME "loopback" -#define USER "srb2_ms" -#define PASSWORD "gLRDRb7WgLRDRb7W" -#define DATABASE "srb2_ms" - -// MySQL Stuff :D - - const char *server = HOSTNAME; - const char *user = USER; - const char *password = PASSWORD; - const char *database = DATABASE; - time_t lastupdate; - - MYSQL *conn; - MYSQL_RES *res; - MYSQL_ROW row; - int mysqlconnected = 0; -/* -char *str_replace(char * t1, char * t2, char * t6) -{ - char*t4; - char*t5=new(0); - - while(strstr(t6,t1)){ - t4=strstr(t6,t1); - strncpy(t5+strlen(t5),t6,t4-t6); - strcat(t5,t2); - t4+=strlen(t1); - t6=t4; - } - return strcat(t5,t4); -} -*/ -/* -// Cue was here -char *str_quakeformat(char *msg) -{ - char *quakemsg , *quakemsg1, *quakemsg2; - char *quakemsg3, *quakemsg4, *quakemsg5; - char *quakemsg6, *quakemsg7, *quakemsg8; - - quakemsg1 = new(sizeof(char) * (strlen(msg) + 1)); - strcpy(quakemsg1, msg); - quakemsg2 = str_replace("^1", "\x81",quakemsg1); - quakemsg3 = str_replace("^2", "\x82",quakemsg2); - quakemsg4 = str_replace("^3", "\x83",quakemsg3); - quakemsg5 = str_replace("^4", "\x84",quakemsg4); - quakemsg6 = str_replace("^5", "\x85",quakemsg5); - quakemsg7 = str_replace("^6", "\x86",quakemsg6); - quakemsg8 = str_replace("^7", "\x87",quakemsg7); - quakemsg = str_replace("^0", "\x80",quakemsg8); - delete(quakemsg1); - delete(quakemsg2); - delete(quakemsg3); - delete(quakemsg4); - delete(quakemsg5); - delete(quakemsg6); - delete(quakemsg7); - delete(quakemsg8); - - return quakemsg; -} - */ -void MySQL_Conn(bool force) { - //if(mysql_ping(conn)) - //mysqlconnected = 0; - logPrintf(mysqlfile, "Trying to connect to MySQL...\n"); - if(mysqlconnected != 1 || force) { - if(force) - mysql_close(conn); - const char *server = HOSTNAME; - const char *user = USER; - const char *password = PASSWORD; - const char *database = DATABASE; - - conn = mysql_init(NULL); - - /* Connect to database */ - if (!mysql_real_connect(conn, server, - user, password, database, 8219, NULL, 0)) { - logPrintf(errorfile, "%s\n", mysql_error(conn)); - } - conn = mysql_init(NULL); - - /* Connect to database */ - if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { - logPrintf(errorfile, "%s\n", mysql_error(conn)); - mysqlconnected = 0; - } else { - logPrintf(mysqlfile, "Connection to MySQL Database successful!\n"); - mysqlconnected = 1; - } - } -} - -static int MySQL_CheckBan(const char *ip, UINT32 id, bool sendinfo, bool type) { - msg_t msg; - int writecode; - MySQL_Conn(false); - msg.id = id; - char banqueryp1[500] = "SELECT bid,INET_NTOA(ipstart),INET_NTOA(ipend),DATE_FORMAT(FROM_UNIXTIME(full_endtime),'%%a %%b %%e %%Y at %%k:%%i (CDT)'),reason,hostonly,permanent FROM ms_bans WHERE INET_ATON('%s') BETWEEN `ipstart` AND `ipend` AND (`full_endtime` > %ld OR `permanent` = '1') LIMIT 1"; -// char exqueryp1[500] = "SELECT * FROM ms_exceptions WHERE `ip` = '%s' AND `bid` = '%s' LIMIT 1"; -// char exquery[500]; - char banquery[500]; -// char bid[5]; - - time_t current_time = time (NULL); - sprintf(banquery, banqueryp1, ip, current_time); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", banquery); - if(mysql_query(conn, banquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return false; - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) >= 1) { - logPrintf(logfile, "We got a ban coming on!\n"); - row = mysql_fetch_row(res); - if(!type && strcmp(row[5],"1") == 0) - return false; - if(sendinfo) - { - logPrintf(logfile, "And we're meant to tell them some more!\n"); - msg_ban_t *info = (msg_ban_t *) msg.buffer; - info->header[0] = '\0'; - - logPrintf(logfile, "Got Ban: %s - %s, ends %s, for %s\n", row[1], row[2], row[3], row[4]); - logPrintf(logfile, "COPY: ipstart\n"); - strcpy(info->ipstart, row[1]); - logPrintf(logfile, "COPY: ipend\n"); - strcpy(info->ipend, row[2]); - logPrintf(logfile, "COPY: endtime\n"); - if(strcmp(row[6], "0") == 0) - { - logPrintf(logfile, "COPY: It's not permanent.\n"); - strcpy(info->endstamp, row[3]); - } - else - { - logPrintf(logfile, "COPY: It's permanent.\n"); - strcpy(info->endstamp, "Never"); - } - logPrintf(logfile, "COPY: reason\n"); - strcpy(info->reason, row[4]); - logPrintf(logfile, "COPY: hostonly\n"); - if(strcmp(row[5],"0") == 0) - info->hostonly = false; - else - info->hostonly = true; - - if(info->hostonly) - logPrintf(logfile, "BAN HAMMER: %s - %s || Reason: %s || Endstamp: %s || HOSTONLY\n", info->ipstart, info->ipend, info->reason, info->endstamp); - else - logPrintf(logfile, "BAN HAMMER: %s - %s || Reason: %s || Endstamp: %s || NOTHOSTONLY\n", info->ipstart, info->ipend, info->reason, info->endstamp); - mysql_free_result(res); - msg.type = GET_BANNED_MSG; - msg.length = sizeof (msg_ban_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return true; - } - } - return true; - } else { - mysql_free_result(res); - return false; - } - } -} - -int MySQL_CheckRoom(UINT32 room) -{ - MySQL_Conn(false); - char checkqueryp1[500] = "SELECT private FROM `ms_rooms` WHERE `room_id` = '%d' AND `private` = '1' LIMIT 1"; - char checkquery[500]; - sprintf(checkquery, checkqueryp1, room); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", checkquery); - if(mysql_query(conn, checkquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return false; - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - return true; - else - return false; - } -} - -void MySQL_AddServer(const char *ip, const char *port, const char *name, const char *version, UINT32 room, bool firstadd, const char *key) { - char escapedName[255]; - char escapedPort[10]; - char escapedVersion[10]; - char escapedKey[32]; - char insertquery[5000]; - char checkquery[500]; - char updatequery[5000]; - char queryp1[5000] = "INSERT INTO `ms_servers` (`name`,`ip`,`port`,`version`,`timestamp`,`room`,`key`) VALUES ('%s','%s','%s','%s','%ld','%d','%s')"; - char checkqueryp1[500] = "SELECT room_override FROM `ms_servers` WHERE `ip` = '%s'"; - char updatequeryp1[5000]; - if(firstadd) - { - logPrintf(logfile, "First add.\n"); - strcpy(updatequeryp1, "UPDATE `ms_servers` SET `name` = '%s', `port` = '%s', `version` = '%s', timestamp = '%ld', upnow = '1', `room` = '%d', `delisted` = '0', `key` = '%s' WHERE `ip` = '%s'"); - } - else - { - logPrintf(logfile, "Update ping.\n"); - strcpy(updatequeryp1, "UPDATE `ms_servers` SET `name` = '%s', `port` = '%s', `version` = '%s', timestamp = '%ld', upnow = '1', `room` = '%d', `key` = '%s' WHERE `ip` = '%s' AND `delisted` = '0'"); - } - MySQL_Conn(false); - mysql_real_escape_string(conn, escapedName, name, (unsigned long)strlen(name)); - mysql_real_escape_string(conn, escapedPort, port, (unsigned long)strlen(port)); - mysql_real_escape_string(conn, escapedVersion, version, (unsigned long)strlen(version)); - mysql_real_escape_string(conn, escapedKey, key, (unsigned long)strlen(key)); - if(!MySQL_CheckBan(ip,0,false,1)) { - if(!MySQL_CheckRoom(room)) - { - logPrintf(errorfile, "IP %s tried to use the private room %d! THIS SHOULD NOT HAPPEN\n", ip, room); - return; - } - sprintf(checkquery, checkqueryp1, ip); - time_t timestamp; - timestamp = time (NULL); - logPrintf(logfile, "Checking for existing servers in table with the same IP...\n"); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", checkquery); - if(mysql_query(conn, checkquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d rows...\n", mysql_num_rows(res)); - if(mysql_num_rows(res) < 1) { - mysql_free_result(res); - logPrintf(logfile, "Adding the temporary server: %s:%s || Name: %s || Version: %s || Time: %ld || Room: %d || Key: %s\n", ip, port, name, version, timestamp, room, key); - sprintf(insertquery, queryp1, escapedName, ip, escapedPort, escapedVersion, timestamp, room, escapedKey); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", insertquery); - if(mysql_query(conn, insertquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - logPrintf(logfile, "Server added successfully!\n"); - } - } else { - row = mysql_fetch_row(res); - if(atoi(row[0]) != 0) - room = atoi(row[0]); - mysql_free_result(res); - logPrintf(logfile, "Server's IP already exists, so let's just update it instead...\n"); - logPrintf(logfile, "Updating Server Data for %s\n", ip); - sprintf(updatequery, updatequeryp1, escapedName, escapedPort, escapedVersion, timestamp, room, escapedKey, ip); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", updatequery); - if(mysql_query(conn, updatequery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - logPrintf(logfile, "Server status for Server: %s:%s || Name: %s || Version: %s || Time: %ld || Room: %d || Key: %s set successfully.\n", ip, port, name, version, timestamp, room, key); - } - } - } - } else { - logPrintf(logfile, "IP %s is banned so do nothing.\n", ip); - } -} - -void MySQL_ListServers(UINT32 id, UINT32 type, const char *ip, UINT32 room) { - msg_t msg; - int writecode; - MySQL_Conn(false); - msg.id = id; - msg.type = type; - char servquery[1000]; - if(room == 0) - sprintf(servquery, "SELECT ip, port, name, version FROM ( SELECT * FROM `ms_servers` WHERE `upnow` = '1' ORDER BY `sid` ASC) as t2 ORDER BY `sticky` DESC"); - else - { - char servqueryp1[1000] = "SELECT ip, port, name, version FROM ( SELECT * FROM `ms_servers` WHERE `upnow` = '1' AND `room` = '%d' ORDER BY `sid` ASC) as t2 ORDER BY `sticky` DESC"; - sprintf(servquery, servqueryp1, room); - } - if(!MySQL_CheckBan(ip,0,false,0)) { - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", servquery); - if(mysql_query(conn, servquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d servers...\n", mysql_num_rows(res)); - while ((row = mysql_fetch_row(res)) != NULL) - { - msg_server_t *info = (msg_server_t *) msg.buffer; - - info->header[0] = '\0'; // nothing interresting in it (for now) - strcpy(info->ip, row[0]); - strcpy(info->port, row[1]); - strcpy(info->name, row[2]); - strcpy(info->version, row[3]); - - msg.length = sizeof (msg_server_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - } - mysql_free_result(res); - } - } else { - logPrintf(logfile, "IP %s is banned so do nothing.\n", ip); - } -} - -void MySQL_ListRooms(UINT32 id, UINT32 type, const char *ip, bool sendtype) { - msg_t msg; - int writecode; - //(void)ip; - MySQL_Conn(false); - msg.id = id; - msg.type = type; - char roomquery[1000]; - logPrintf(logfile, "Check their ban status first... (ID %d)\n",id); - if(MySQL_CheckBan(ip,id,true,sendtype)) - return; - - //Hmph! I suppose it'll be up to me to handle this. ~Inuyasha - if (sendtype) - { - char overridequery[500]; - - sprintf(overridequery, "SELECT room_override FROM `ms_servers` WHERE `ip` = '%s' AND `room_override` > 0", ip); - logPrintf(mysqlfile, "Checking for room overrides! Executing MySQL Query: %s\n", overridequery); - if (mysql_query(conn, overridequery)) - { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return; - } - - res = mysql_store_result(conn); - if (mysql_num_rows(res) >= 1) - { - int overriddenRoom; - - row = mysql_fetch_row(res); - overriddenRoom = atoi(row[0]); - mysql_free_result(res); - - sprintf(roomquery, "SELECT room_id, title, motd FROM `ms_rooms` WHERE `room_id` = '%d' LIMIT 1", overriddenRoom); - if (mysql_query(conn, roomquery)) - { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - return; - } - res = mysql_store_result(conn); - if (mysql_num_rows(res) >= 1) - { - msg_rooms_t *info = (msg_rooms_t *) msg.buffer; - char roommotd[300]; - - row = mysql_fetch_row(res); - - info->header[0] = '\0'; // nothing interesting in it (for now) - strcpy(info->name, row[1]); - - // Just in case, let's make sure we don't overflow. - sprintf(roommotd, "\x85Your server has had a room override applied to it, so this is the only room you may host in.\x80\n\n%s", row[2]); - strncpy(info->motd, roommotd, 255); - info->motd[255] = '\0'; - - info->id = atoi(row[0]); - - logPrintf(logfile, "Sending Room %s with ID %d and MOTD %s\n", info->name, info->id, info->motd); - - msg.length = sizeof (msg_rooms_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - } - mysql_free_result(res); - return; - } - else - { - logPrintf(errorfile, "Someone's room override isn't set correctly! Room %d doesn't exist!", overriddenRoom); - mysql_free_result(res); - } - } - } - - if(sendtype) - sprintf(roomquery, "SELECT room_id, title, motd FROM `ms_rooms` WHERE `private` = '0' AND `visible` = '1' ORDER BY `order` ASC"); - else - sprintf(roomquery, "SELECT room_id, title, motd FROM `ms_rooms` WHERE `visible` = '1' ORDER BY `order` ASC"); - if(mysql_query(conn, roomquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else - { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d rooms...\n", mysql_num_rows(res)); - while ((row = mysql_fetch_row(res)) != NULL) - { - msg_rooms_t *info = (msg_rooms_t *) msg.buffer; - - info->header[0] = '\0'; // nothing interresting in it (for now) - strcpy(info->name, row[1]); - strcpy(info->motd, row[2]); - info->id = atoi(row[0]); - - logPrintf(logfile, "Sending Room %s with ID %d and MOTD %s\n", info->name, info->id, info->motd); - - msg.length = sizeof (msg_rooms_t); - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - } - mysql_free_result(res); - } -} - -void MySQL_CheckVersion(UINT32 id, UINT32 type, const char *ip, UINT32 modid, const char *modversion) { - msg_t msg; - int writecode; - (void)ip; - MySQL_Conn(false); - msg.id = id; - msg.type = type; - char versionquery[1000]; - sprintf(versionquery, "SELECT * FROM `ms_versions` WHERE `mod_id` = '%d' AND `mod_version` > %s LIMIT 1",modid, modversion); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", versionquery); - if(mysql_query(conn, versionquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else - { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - { - logPrintf(logfile, "Buffer to NULL\n"); - strcpy(msg.buffer,"NULL"); - } - else - { - row = mysql_fetch_row(res); - logPrintf(logfile, "Version found: %s || Codebase: %s || Version: %s || Version String: %s || Mod ID: %s\n", row[4], row[3], row[1], row[2], row[0]); - strcpy(msg.buffer,row[2]); - } - msg.length = sizeof msg.buffer; - msg.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - mysql_free_result(res); - } -} - -void MySQL_ListServServers(UINT32 id, UINT32 type, const char *ip) { - msg_t msg; - int writecode; - static char str[1024]; - //char banqueryp1[500] = "SELECT reason,name,FROM_UNIXTIME(endtime) FROM ms_bans WHERE INET_ATON('%s') BETWEEN `ipstart` AND `ipend` AND `endtime` < %ld LIMIT 1"; - //char banquery[500]; - //time_t current_time = time (NULL); - char servquery[1000] = "SELECT ip, port, name, version, permanent FROM ( SELECT * FROM `ms_servers` WHERE `upnow` = '1' OR `permanent` = '1' ORDER BY `sid` ASC) as ms_servers ORDER BY `sticky` DESC"; - MySQL_Conn(false); - if(!MySQL_CheckBan(ip,0,false,0)) { - msg.id = id; - msg.type = type; - msg.room = 0; - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", servquery); - if(mysql_query(conn, servquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - logPrintf(logfile, "Found %d servers...\n", mysql_num_rows(res)); - while ((row = mysql_fetch_row(res)) != NULL) - { - if(strcmp(row[4], "0") == 1) - snprintf(str, sizeof str, "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t\t: %s\nPermanent\t: %s\n", row[0], row[1], row[2], row[3], "Yes"); - else - snprintf(str, sizeof str, "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t\t: %s\nPermanent\t: %s\n", row[0], row[1], row[2], row[3], "No"); - - msg.length = (INT32)(strlen(str)+1); // send also the '\0' - strcpy(msg.buffer, str); - dbgPrintf(CYAN, "Writing: (%d)\n%s\n", msg.length, msg.buffer); - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", writecode, id); - return; - } - } - mysql_free_result(res); - } - } else { - logPrintf(logfile, "IP %s is banned so do nothing! Let them find out for themselves.\n", ip); - } -} - -void MySQL_RemoveServer(char *ip, char *port, char *name, char *version) { - char escapedName[255]; - char updatequery[5000]; - char updatequeryp1[5000] = "UPDATE `ms_servers` SET upnow = '0' WHERE `ip` = '%s' AND `permanent` = '0'"; - MySQL_Conn(false); - mysql_real_escape_string(conn, escapedName, name, (unsigned long)strlen(name)); - sprintf(updatequery, updatequeryp1, ip); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", updatequery); - if(mysql_query(conn, updatequery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - logPrintf(logfile, "Server: %s:%s || Name: %s || Version: %s removed successfully.\n", ip, port, name, version); - } -} - -/* LIVE FUNCTIONS */ -void LIVE_AuthUser(UINT32 id, char *buffer) -{ - msg_live_auth_t *auth; - char escapedName[255]; - char saltedPassword[62]; - char hashedPassword[34]; - char namequery[1000]; - char namequeryp1[1000] = "SELECT username,userid,salt,password FROM `user` WHERE `username` = '%s' LIMIT 1"; - char userquery[1000]; - char userqueryp1[1000] = "SELECT userid,username,live_authkey,live_publickey FROM `user` WHERE `userid` = '%s' LIMIT 1"; - msg_t msg2; - char ip[32]; - int writecode; - msg2.type = LIVE_INVALID_USER; - - auth = (msg_live_auth_t *)buffer; - - logPrintf(logfile, "Got User %s Pass %s\n", auth->username, auth->password); - // retrieve the true ip of the server - strcpy(ip, server_socket.getClientIP(id)); - MySQL_Conn(false); - msg2.id = id; - logPrintf(logfile, "Check their ban status first... (ID %d)\n",id); - if(MySQL_CheckBan(ip,0,false,0)) - return; - mysql_real_escape_string(conn, escapedName, auth->username, (unsigned long)strlen(auth->username)); - sprintf(namequery, namequeryp1, escapedName); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", namequery); - if(mysql_query(conn, namequery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - { - logPrintf(logfile, "Invalid user: %s\n", auth->username); - msg2.type = LIVE_INVALID_USER; - } - else - { - row = mysql_fetch_row(res); - sprintf(saltedPassword, "%s%s", auth->password, row[2]); - logPrintf(logfile, "Pre-hash: %s (Salt is %s)\n", saltedPassword, row[2]); - sprintf(hashedPassword, md5(saltedPassword).c_str()); - logPrintf(logfile, "Got Hashed Password: %s\n", hashedPassword); - if(strcmp(hashedPassword, row[3]) != 0) - { - msg2.type = LIVE_INVALID_USER; - logPrintf(logfile, "INVALID USER!\n"); - } else { - msg2.type = LIVE_SEND_USER; - sprintf(userquery, userqueryp1, row[1]); - mysql_free_result(res); - logPrintf(mysqlfile, "Executing MySQL Query: %s\n", userquery); - if(mysql_query(conn, userquery)) { - logPrintf(errorfile, "MYSQL ERROR: %s\n", mysql_error(conn)); - MySQL_Conn(true); - } else { - res = mysql_store_result(conn); - if(mysql_num_rows(res) < 1) - { - logPrintf(errorfile, "User Information Error, invalid USER ID!\n"); - msg2.type = LIVE_INVALID_USER; - } else { - row = mysql_fetch_row(res); - msg_live_user_t *user = (msg_live_user_t *) msg2.buffer; - - user->header[0] = '\0'; // nothing interresting in it (for now) - user->uid = atoi(row[0]); - strcpy(user->username, row[1]); - logPrintf(logfile, "Found user: %s, id %s\n", row[1], row[0]); - logPrintf(logfile, "Sending User %s with ID %d\n", user->username, user->uid); - - msg2.length = sizeof (msg_live_user_t); - } - } - } - } - } - msg2.length = sizeof msg2.buffer; - msg2.room = 0; - logPrintf(logfile, "Sending message?\n"); - writecode = server_socket.write(&msg2); - logPrintf(logfile, "Message sent! :D\n"); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d " - "deleted\n", writecode, id); - return; - } - mysql_free_result(res); -} - -/* -** sendServersInformations() -*/ -static void sendServersInformations(UINT32 id, UINT32 room) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - (void)room; - logPrintf(logfile, "Sending servers informations\n"); - msg.id = id; - msg.type = SEND_SERVER_MSG; - msg.room = 0; - MySQL_ListServServers(id, SEND_SERVER_MSG, ip); // Awesome new MySQL Code! - msg.length = 0; - //dbgPrintf(CYAN, "Writing: (%d) %s\n", msg.length, ""); - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** sendShortServersInformations() -*/ -static void sendShortServersInformations(UINT32 id, UINT32 room) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - - logPrintf(logfile, "Sending short servers informations\n"); - msg.id = id; - msg.type = SEND_SHORT_SERVER_MSG; - MySQL_ListServers(id, SEND_SHORT_SERVER_MSG, ip, room); // New code that's full of win! - logPrintf(logfile, "Packet Room: %d\n", room); - msg.length = 0; - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** sendRoomInformations() -*/ -static void sendRoomInformations(UINT32 id, UINT32 room, bool type) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - (void)room; - logPrintf(logfile, "Sending room information\n"); - msg.id = id; - msg.type = SEND_ROOMS_MSG; - msg.room = 0; - MySQL_ListRooms(id, SEND_ROOMS_MSG, ip, type); // New code that's full of win! - msg.length = 0; - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** sendVersionInformations() -*/ -static void sendVersionInformations(UINT32 id, UINT32 modid, char *modversion) -{ - msg_t msg; - int writecode; - char ip[16]; - strcpy(ip, server_socket.getClientIP(id)); - - logPrintf(logfile, "Sending version information\n"); - msg.id = id; - msg.type = SEND_VERSION_MSG; - msg.room = 0; - MySQL_CheckVersion(id, SEND_VERSION_MSG, ip, modid, modversion); // New code that's full of win! - msg.length = sizeof msg.buffer; - writecode = server_socket.write(&msg); - if (writecode < 0) - { - dbgPrintf(LIGHTRED, "Write error... %d client %d deleted\n", - writecode, id); - } -} - -/* -** addServer() -*/ -static void addServer(int id, char *buffer, bool firstadd) -{ - msg_server_t *info; - char oldversion = 0; - - //TODO: Be sure there is no flood from a given IP: - // If a host need more than 2 servers, then it should be registrated - // manually - - info = (msg_server_t *)buffer; - - // I want to be sure the informations are correct, of course! - info->port[sizeof (info->port)-1] = '\0'; - info->name[sizeof (info->name)-1] = '\0'; - info->version[sizeof (info->version)-1] = '\0'; - // retrieve the true ip of the server - strcpy(info->ip, server_socket.getClientIP(id)); - //strcpy(info->port, server_socket.getClientPort(id)); - - if (info->version[0] == '1' && - info->version[1] == '.' && - info->version[2] == '0' && - info->version[3] == '9' && - info->version[4] == '.') - { - if ((info->version[5] == '2') || (info->version[5] == '3')) - { - oldversion = 1; - } - } - - if (info->version[0] == '1' && - info->version[1] == '.' && - info->version[2] == '6' && - info->version[3] == '9' && - info->version[4] == '.' && - info->version[5] == '6') - { - oldversion = 1; - } - - if (!oldversion) - { - MySQL_AddServer(info->ip, info->port, info->name, info->version, info->room, firstadd, info->key); - } - else - { - logPrintf(logfile, "Not adding the temporary server: %s %s %s %s\n", info->ip, info->port, info->name, info->version); - } -} - -/* -** removeServer() -*/ -static void removeServer(int id, char *buffer) -{ - msg_server_t *info; - - info = (msg_server_t *)buffer; - - // I want to be sure the informations are correct, of course! - info->port[sizeof (info->port)-1] = '\0'; - info->name[sizeof (info->name)-1] = '\0'; - info->version[sizeof (info->version)-1] = '\0'; - - // retrieve the true ip of the server - strcpy(info->ip, server_socket.getClientIP(id)); - - logPrintf(logfile, "Removing the temporary server: %s %s %s %s\n", info->ip, info->port, info->name, info->version); - MySQL_RemoveServer(info->ip, info->port, info->name, info->version); // New and win. -} - -/* -** analyseUDP() -*/ -static int analyseUDP(size_t size, const char *buffer) -{ - // this would be the part of reading the PT_SERVERINFO packet, - // but i'm not about to backport that sloppy code - (void)size; - (void)buffer; - return INVALID_MSG; -} - -/* -** UDPMessage() -*/ -static int UDPMessage(size_t size, const char *buffer) -{ - if (size == 4) - { - return 0; - } - else if (size == sizeof(ms_holepunch_packet_t)) - { - return 0; - } - else if (size > 58) - { - dbgPrintf(LIGHTGREEN, "Got a UDP %d byte long message\n", size); - return analyseUDP(size, buffer); - } - else - return INVALID_MSG; -} - -/* -** analyseMessage() -*/ -static int analyseMessage(msg_t *msg) -{ - switch (msg->type) - { - case UDP_RECV_MSG: - return UDPMessage(msg->length, msg->buffer); - case ACCEPT_MSG: - break; - case ADD_SERVER_MSG: - addServer(msg->id, msg->buffer, true); - break; - case PING_SERVER_MSG: - addServer(msg->id, msg->buffer, false); - break; - case REMOVE_SERVER_MSG: - removeServer(msg->id, msg->buffer); - break; - case GET_SERVER_MSG: - sendServersInformations(msg->id, msg->room); - break; - case GET_SHORT_SERVER_MSG: - sendShortServersInformations(msg->id, msg->room); - break; - case GET_ROOMS_MSG: - sendRoomInformations(msg->id, msg->room, 0); - break; - case GET_ROOMS_HOST_MSG: - sendRoomInformations(msg->id, msg->room, 1); - break; - case GET_VERSION_MSG: - sendVersionInformations(msg->id, msg->room, msg->buffer); - break; - case LIVE_AUTH_USER: - LIVE_AuthUser(msg->id, msg->buffer); - break; - default: - return INVALID_MSG; - } - return 0; -} - -/* -** main() -*/ -int main(int argc, char *argv[]) -{ - msg_t msg; -#ifdef __unix__ - pid_t pid; - char pidstr[12]; -#endif - - if (argc <= 1) - { - fprintf(stderr, "usage: %s port\n", argv[0]); - exit(1); - } - - if (server_socket.listen(argv[1]) < 0) - { - fprintf(stderr, "Error while initializing the server\n"); - exit(2); - } - - logfile = openFile("server.log"); - errorfile = openFile("error.log"); - mysqlfile = openFile("mysql.log"); - sockfile = openFile("sockets.log"); - MySQL_Conn(false); -#if !defined (DEBUG) && defined (__unix__) - pid = fork(); - switch (pid) - { - case 0: break; // child - case -1: printf("Error while launching the server in background\n"); return -1; - default: - pidfile = fopen("msd.pid", "w+"); - sprintf(pidstr, "%d", pid); - fputs(pidstr, pidfile); - fclose(pidfile); - return 0; // parent: keep child in background - } -#endif - srand((unsigned)time(NULL)); // Alam: GUIDs - for (;;) - { - memset(&msg, 0, sizeof (msg)); // remove previous message - if (!server_socket.read(&msg)) - { - // valid message: header message seems ok - analyseMessage(&msg); - //servers_list.show(); // for debug purpose - } - } - -#ifndef _MSC_VER - /* NOTREACHED */ - return 0; -#endif -} diff --git a/tools/masterserver/srvlist.cpp b/tools/masterserver/srvlist.cpp deleted file mode 100644 index c9a6feea9..000000000 --- a/tools/masterserver/srvlist.cpp +++ /dev/null @@ -1,405 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#ifdef __GNUC__ -#include -#endif -#include -#include "common.h" -#include "srvlist.h" - -//============================================================================= - -/* -** -*/ -CList::CList() -{ - list = NULL; - current = NULL; -} - -/* -** -*/ -CList::~CList() -{ - CItem *p; - - while (list) - { - p = list; - list = list->next; - delete(p); - } -} - -/* -** -*/ -int CList::insert(CItem *item) -{ - item->next = list; - list = item; - return 0; -} - -/* -** -*/ -int CList::remove(CItem *item) -{ - CItem *position, *q; - - q = NULL; - position = list; - - while (position && (position != item)) - { - q = position; - position = position->next; - } - if (position) - { - if (q) - q->next = position->next; - else - list = position->next; - delete position; - - return 1; - } - - return 0; -} - -/* -** -*/ -CItem *CList::getFirst() -{ - current = list; - return current; -} - -/* -** -*/ -CItem *CList::getNext() -{ - if (current) - current = current->next; - return current; -} - -/* -** -*/ -void CList::show() -{ - CItem *p; - - p = list; - while (p) - { - p->print(); - p = p->next; - } -} - -//============================================================================= - -/* -** -*/ -CItem::CItem() -{ - next = NULL; -} - -//============================================================================= - -/* -** -*/ -CInetAddr::CInetAddr(const char *ip, const char *port) -{ - strcpy(this->ip, ip); - strcpy(this->port, port); - PortNotChanged = true; -} - -/* -** -*/ -const char *CInetAddr::getIP() -{ - return ip; -} - -/* -** -*/ -const char *CInetAddr::getPort() -{ - return port; -} - -/* -** -*/ -bool CInetAddr::setPort(const char *port) -{ - if (PortNotChanged) - { - strcpy(this->port, port); - PortNotChanged = false; - } - return !PortNotChanged; -} - -//============================================================================= - -/* -** -*/ -CPlayerItem::CPlayerItem(const char *ip, const char *port, - const char *nickname) : CInetAddr(ip, port) -{ - strcpy(this->nickname, nickname); -} - -/* -** -*/ -void CPlayerItem::print() -{ - dbgPrintf(GREEN, "\tIP\t\t: %s\n\tPort\t\t: %s\n\tNickname\t: %s\n", - ip, port, nickname); -} - -/* -** -*/ -char *CPlayerItem::getString() -{ - static char tmpbuf[1024]; - - snprintf(tmpbuf, sizeof tmpbuf, - "\tIP\t\t: %s\n\tPort\t\t: %s\n\tNickname\t: %s\n", - ip, port, nickname); - return tmpbuf; -} - -//============================================================================= - -/* -** -*/ -CServerItem::CServerItem(const char *ip, const char *port, const char *hostname, const char *version, ServerType type) : CInetAddr(ip, port) -{ - time_t timenow = time(NULL); - const tm *timeGMT = gmtime(&timenow); - // check name of server here - strcpy(this->hostname, hostname); - strcpy(this->version, version); - this->type = type; - strftime(reg_time, REG_TIME_SIZE+1, "%Y-%m-%dT%H:%MZ",timeGMT); - { - int i; - memset(guid,'\0',GUID_SIZE); - strcpy(&guid[0], ip); - strcpy(&guid[15], port); // GenUID - for (i = 0; i <= GUID_SIZE-1; i++) - { - if (guid[i] == '\0' || guid[i] == '.') - guid[i] = '0' + (rand()/(RAND_MAX/15)); - if (guid[i] > '9') - guid[i] += 'A'-'9'; - } - guid[GUID_SIZE] = '\0'; - } - - HeartBeat = time(NULL); -} - -/* -** -*/ -void CServerItem::print() -{ - dbgPrintf(GREEN, "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t: %s\nPermanent\t: %s\n", - ip, port, hostname, version, (type == ST_PERMANENT) ? "Yes" : "No"); -} - -/* -** -*/ -const char *CServerItem::getString() -{ - static char tmpbuf[1024]; - - snprintf(tmpbuf, sizeof tmpbuf, - "IP\t\t: %s\nPort\t\t: %s\nHostname\t: %s\nVersion\t\t: %s\nPermanent\t: %s\n", - ip, port, hostname, version, (type==ST_PERMANENT) ? "Yes" : "No"); - return tmpbuf; -} - -/* -** -*/ -const char *CServerItem::getName() -{ - return hostname; -} - -/* -** -*/ -const char *CServerItem::getVersion() -{ - return version; -} - -/* -** -*/ -const char *CServerItem::getGuid() -{ - return guid; -} - -/* -** -*/ -const char *CServerItem::getRegtime() -{ - return reg_time; -} - -/* -** -*/ -//============================================================================= - -/* -** -*/ -void CServerList::insertPlayer(CServerItem *server, CPlayerItem *player) -{ - server->players_list.insert(player); -} - -/* -** -*/ -void CServerList::removePlayer(CServerItem *server, CPlayerItem *player) -{ - server->players_list.remove(player); -} - -/* -** -*/ -int CServerList::insert(CServerItem *server) -{ - CList::insert((CItem *)server); - return 0; -} - -/* -** -*/ -int CServerList::insert(const char *ip, const char *port, - const char *hostname, const char *version, ServerType type) -{ - CServerItem *server; - - server = new CServerItem(ip, port, hostname, version, type); - CList::insert(server); - return 0; -} - -/* -** -*/ -int CServerList::remove(CServerItem *server) -{ - return CList::remove((CItem *)server); -} - -/* -** -*/ -int CServerList::remove(const char *ip, const char *port, - const char *hostname, const char *version, ServerType type) -{ - // TODO - CServerItem *position, *q; - bool match; - - (void)hostname; - (void)port; - - match = false; - position = (CServerItem *)list; - q = NULL; - - while (position && !match) - { - if (strcmp(position->ip, ip) == 0 - && strcmp(position->version, version) == 0 - && strcmp(position->port, port) == 0 - && position->type == type) - { - match = true; - } - else - { - q = position; - position = (CServerItem *)position->next; - } - } - if (position && match) - { - if (q) - q->next = position->next; - else - list = position->next; - delete position; - - return 1; - } - - return 0; -} - -/* -** -*/ -void CServerList::show() -{ - CServerItem *p; - - p = (CServerItem *)list; - while (p) - { - p->print(); - p->players_list.show(); - p = (CServerItem *)p->next; - } -} diff --git a/tools/masterserver/srvlist.h b/tools/masterserver/srvlist.h deleted file mode 100644 index aa582ff8b..000000000 --- a/tools/masterserver/srvlist.h +++ /dev/null @@ -1,136 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#ifndef SRVLIST_H -#define SRVLIST_H - -#include - -enum ServerType -{ - ST_PERMANENT = 0, - ST_TEMPORARY, -}; - -//============================================================================= - -class CItem -{ - friend class CList; -protected: - CItem *next; -public: - CItem(); - virtual ~CItem() {}; // destructor must exist and be virtual - virtual void print() = 0; -}; - -//============================================================================= - -class CList -{ -protected: - CItem *list; - CItem *current; // the current item we are pointing on (for getfirst/getnext) -public: - CList(); - virtual ~CList(); - int insert(CItem *); - int remove(CItem *); - CItem *getFirst(); - CItem *getNext(); - void show(); -}; - -//============================================================================= - -class CInetAddr -{ -protected: - char ip[16]; - char port[8]; - bool PortNotChanged; -public: - CInetAddr(const char *ip, const char *port); - const char *getIP(); - bool setPort(const char *port); - const char *getPort(); -}; - -//============================================================================= - -class CPlayerItem : public CItem, public CInetAddr -{ -friend class CPlayerList; -private: - char nickname[32]; -public: - CPlayerItem(const char *ip, const char *port, const char *nickname); - void print(); - char *getString(); -}; - -//============================================================================= - -class CPlayerList : public CList -{ -}; - -//============================================================================= - -#define REG_TIME_SIZE 24 //1970-00-00T00:00:00.0+00:00 -#define GUID_SIZE 24-1 // format is 12700000000105000 - -class CServerItem : public CItem, public CInetAddr -{ - friend class CServerList; - -private: - char hostname[32]; - char version[8]; // format is: x.yy.z (like 1.30.2 or 1.31) - CPlayerList players_list; - char reg_time[REG_TIME_SIZE]; - char guid[GUID_SIZE+1]; - -public: - ServerType type; - time_t HeartBeat; - - CServerItem(const char *ip, const char *port, const char *hostname, const char *version, ServerType type); - void print(); - const char *getString(); - const char *getName(); - const char *getVersion(); - const char *getRegtime(); - const char *getGuid(); -}; - -//============================================================================= - -class CServerList : public CList -{ -public: - void insertPlayer(CServerItem *server, CPlayerItem *player); - void removePlayer(CServerItem *server, CPlayerItem *player); - int insert(const char *ip, const char *port, const char *hostname, const char *version, ServerType type); - int insert(CServerItem *server); - int remove(const char *ip, const char *port, const char *hostname, const char *version, ServerType type); - int remove(CServerItem *server); - void show(); -}; - -#endif diff --git a/tools/masterserver/stats.cpp b/tools/masterserver/stats.cpp deleted file mode 100644 index 741d82699..000000000 --- a/tools/masterserver/stats.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#ifdef __GNUC__ -#include -#endif -#include // strcat(),... -#include "common.h" -#include "ipcs.h" -#include "stats.h" - -//============================================================================= - -/* -** CServerStats() -*/ -CServerStats::CServerStats() -{ - uptime = time(NULL); - num_connections = 0; - num_http_con = 0; - num_servers = 0; - snprintf(motd, sizeof motd, "%s%s", "Welcome to the SRB2 Master Server!
", SERVERMOTDTEXT); - num_add = 0; - num_removal = 0; - num_retrieval = 0; - num_autoremoval = 0; - num_badconnection = 0; - for (int i = 0; i < NUMLASTSERVERS; i++) - { - strcpy(last_server[i].ip, "0.0.0.0"); - strcpy(last_server[i].name, "Non-Existing SRB2 server"); - strcpy(last_server[i].version, "0.0.0"); - } - snprintf(version, sizeof version, "%s %s", __DATE__, __TIME__); -} - -/* -** ~CServerStats() -*/ -CServerStats::~CServerStats() -{ -} - -/* -** getUptime() -*/ -const char *CServerStats::getUptime() -{ - char *res = ctime(&uptime); - res[strlen(res)-1] = '\0'; // remove the '\n' at the end - return res; -} - -/* -** getHours() -*/ -int CServerStats::getHours() -{ - return (int)(((time(NULL) - uptime)/(60*60))%24); -} - -/* -** getDays() -*/ -int CServerStats::getDays() -{ - return (int)((time(NULL) - uptime)/(60*60*24)); -} - -/* -** getMotd() -*/ -const char *CServerStats::getMotd() -{ - return motd; -} - -/* -** getLastServers() -*/ -const char *CServerStats::getLastServers() -{ - static char res[170*NUMLASTSERVERS]; - - tzset(); - res[0] = '\0'; - for (int i = 0; i < NUMLASTSERVERS; i++) - { - char str[170]; - char *ct; - - ct = ctime(&last_time[i]); - ct[strlen(ct)-1] = '\0'; // replace \n with a \0 - snprintf(str, sizeof str, - "Address: %15s Name: %-31s v%-7s (%s %s)\n000043210000", - last_server[i].ip, last_server[i].name, last_server[i].version, ct, tzname[0]); - strcat(res, str); - } - - return res; -} - -/* -** getVersion() -*/ -const char *CServerStats::getVersion() -{ - return version; -} - -/* -** putMotd() -*/ -void CServerStats::putMotd(char *motd) -{ - strcpy(this->motd, motd); -} - -/* -** putLastServer(): -*/ -void CServerStats::putLastServer(msg_server_t *server) -{ - for (int i = NUMLASTSERVERS-1; i > 0; i--) - { - memcpy(&last_server[i], &last_server[i-1], - sizeof (msg_server_t)); - last_time[i] = last_time[i-1]; - } - memcpy(&last_server[0], server, sizeof (msg_server_t)); - last_time[0] = time(NULL); -} diff --git a/tools/masterserver/stats.h b/tools/masterserver/stats.h deleted file mode 100644 index 4494a76f9..000000000 --- a/tools/masterserver/stats.h +++ /dev/null @@ -1,68 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// Copyright (C) 2000 by DooM Legacy Team. -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -//----------------------------------------------------------------------------- - -#ifndef _STATS_H_ -#define _STATS_H_ -#ifndef _IPCS_H_ -#error "You forget to include ipcs.h" -#endif -#include - -#define NUMLASTSERVERS 6 -#define SERVERMOTDTEXT "No Clans, advertising websites, Chat, Hangout, Hacked, or Role Playing Servers Allowed" - - -// ================================ DEFINITIONS =============================== - -class CServerStats -{ - time_t uptime; // master server uptime - char motd[2048]; // increase that if not enough - msg_server_t last_server[NUMLASTSERVERS]; // keep last 6 named registered servers - time_t last_time[NUMLASTSERVERS]; // keep date/time of registration of those servers - char version[32]; // master server version - -public: - int num_connections; - int num_http_con; - int num_text_con; - int num_RSS92_con; - int num_RSS10_con; - int num_servers; - int num_add; - int num_removal; - int num_retrieval; - int num_autoremoval; - int num_badconnection; - - CServerStats(); - ~CServerStats(); - const char *getUptime(); - int getHours(); - int getDays(); - const char *getMotd(); - const char *getLastServers(); - const char *getVersion(); - void putMotd(char *); - void putLastServer(msg_server_t *); -}; - -// ================================== PROTOS ================================== - -// ================================== EXTERNS ================================= - -#endif diff --git a/tools/masterserver/structure.sql b/tools/masterserver/structure.sql deleted file mode 100644 index 3cc2cb15b..000000000 --- a/tools/masterserver/structure.sql +++ /dev/null @@ -1,117 +0,0 @@ -SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; -SET AUTOCOMMIT = 0; -START TRANSACTION; -SET time_zone = "+00:00"; - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8mb4 */; - --- --- Database: `srb2ms` --- - -CREATE DATABASE IF NOT EXISTS `srb2ms` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; -USE `srb2ms`; - - --- -------------------------------------------------------- - --- --- Table structure for table `ms_bans` --- - -CREATE TABLE `ms_bans` ( - `bid` int(11) DEFAULT NULL, - `ipstart` int(11) DEFAULT NULL, - `ipend` int(11) DEFAULT NULL, - `full_endtime` int(11) DEFAULT NULL, - `permanent` tinyint(1) DEFAULT NULL, - `hostonly` tinyint(1) DEFAULT NULL, - `reason` text COLLATE utf8mb4_unicode_ci -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- -------------------------------------------------------- - --- --- Table structure for table `ms_rooms` --- - -CREATE TABLE `ms_rooms` ( - `room_id` int(11) NOT NULL, - `title` text COLLATE utf8mb4_unicode_ci NOT NULL, - `motd` text COLLATE utf8mb4_unicode_ci NOT NULL, - `visible` tinyint(1) NOT NULL, - `order` int(11) NOT NULL, - `private` tinyint(1) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Dumping data for table `ms_rooms` --- - -INSERT INTO `ms_rooms` (`room_id`, `title`, `motd`, `visible`, `order`, `private`) VALUES -(10, 'Example', 'Example Room', 1, 0, 0), -(0, 'All', 'View all of the servers currently being hosted.', 1, 1, 1); - --- -------------------------------------------------------- - --- --- Table structure for table `ms_servers` --- - -CREATE TABLE `ms_servers` ( - `sid` int(11) NOT NULL, - `name` text COLLATE utf8mb4_unicode_ci NOT NULL, - `ip` text COLLATE utf8mb4_unicode_ci NOT NULL, - `port` int(11) NOT NULL, - `version` text COLLATE utf8mb4_unicode_ci NOT NULL, - `timestamp` int(11) NOT NULL, - `room` int(11) NOT NULL, - `key` text COLLATE utf8mb4_unicode_ci NOT NULL, - `room_override` int(11) NOT NULL, - `upnow` tinyint(1) NOT NULL, - `permanent` tinyint(1) NOT NULL, - `delisted` tinyint(1) NOT NULL, - `sticky` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- -------------------------------------------------------- - --- --- Table structure for table `ms_versions` --- - -CREATE TABLE `ms_versions` ( - `mod_id` int(11) NOT NULL, - `mod_version` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Dumping data for table `ms_versions` --- - -INSERT INTO `ms_versions` (`mod_id`, `mod_version`) VALUES -(12, 25); - --- -------------------------------------------------------- - --- --- Table structure for table `user` --- - -CREATE TABLE `user` ( - `userid` int(11) NOT NULL, - `username` text COLLATE utf8mb4_unicode_ci NOT NULL, - `live_authkey` blob NOT NULL, - `live_publickey` blob NOT NULL, - `salt` blob NOT NULL, - `password` blob NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -COMMIT; - -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/tools/srb2msns/elements/srb2ms.RDF b/tools/srb2msns/elements/srb2ms.RDF deleted file mode 100644 index 46b3c81f0..000000000 --- a/tools/srb2msns/elements/srb2ms.RDF +++ /dev/null @@ -1,36 +0,0 @@ - - - - - -]> - - -The SRB2MS Element Set namespace providing access -to its content by means of an RDF Schema -Logan Arias -The SRB2MS Element Set namespace provides -URIs for the SRB2MS Elements. Entries are declared using RDF Schema language -to support RDF applications. -English - - -Address -The IPv4 address of the server item. - - - - -Port -The Port number of the server item. - - - - -Version -Version number of the server item. - - - - diff --git a/tools/wadconv/Makefile b/tools/wadconv/Makefile deleted file mode 100644 index d11fbf6ce..000000000 --- a/tools/wadconv/Makefile +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/env make -f - -## wadconv: SRB2 WAD Converter. -## Copyright (C) 2011 by Callum Dickinson. -# -## This program is free software; you can redistribute it and/or -## modify it under the terms of the GNU General Public License -## as published by the Free Software Foundation; either version 2 -## of the License, or (at your option) any later version. -# -## This program is distributed in the hope that it will be useful, -## but WITHOUT ANY WARRANTY; without even the implied warranty of -## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -## GNU General Public License for more details. - -# Program name. -PRONAME = wadconv -# Program version. -PROVER = 1.0.0 - -# Program default options. -CPPFLAGS += -DPRONAME="$(PRONAME)" -DPROVER="$(PROVER)" - -# Source files and directory. -SRC = wadconv.c - -# Required libraries. -LIB = -lwad - -# -## Variables that shouldn't be edited unless -## you know what you are doing start here. -# - -# Makefile pretty text output variables. -PRCC = CC -PRINSTALL=INSTALL -PRCLEAN = CLEAN - -# Library name prefix. -LIBPFX = lib - -# Library installation directory. -PREFIX ?= /usr/local -LIBDIR := $(PREFIX)/lib -INCLUDE := $(PREFIX)/include - -# Variables created during compilation. -OBJ = $(SRC:.c=.o) -DEP = $(PRONAME).d -ifdef MINGW -BIN = $(PRONAME).exe -else -BIN = $(PRONAME) -endif - -# Compilation programs. -ECHO := echo -RM := rm -rf -FIND := find -GREP := grep -INSTALLX:= install -m 755 -FOR := for -SED := sed -CC := $(CROSS_COMPILE)$(CC) - -# Shell programs. -SHECHO := $(ECHO) -SHFIND := $(FIND) -SHGREP := $(GREP) -SHINSTALL:= $(INSTALL) -SHSED := $(SED) -SHCC := $(CC) - -# Quiet compiling programs during pretty text output. -NULL := /dev/null 2>&1 -ECHO := @$(ECHO) -ifndef V -RM := @$(RM) -LDCONFIG:= @$(LDCONFIG) -FIND := @$(FIND) -GREP := @$(GREP) -INSTALL := @$(INSTALL) -MKDIR := @$(MKDIR) -FOR := @$(FOR) -SED := @$(SED) -CC := @$(CC) -endif - -# Compiler default flags. -ifdef DEBUG -CFLAGS += -g -O0 -Wall -else -CFLAGS += -O3 -endif - -# Linker flags. -#LDFLAGS += - -# -## Makefile targets. -# - -all: $(DEP) $(BIN) - -$(DEP): $(SRC) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - -$(RM) $@ - $(FOR) f in $(SRC); do \ - $(SHCC) $(CPPFLAGS) $(CFLAGS) -MM $$f >> $@; \ - done --include $@ - -%.o: %.c -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ - -$(BIN): $(OBJ) -ifndef V - $(ECHO) " $(PRCC)$@" -endif - $(CC) $(LDFLAGS) -o $@ $(OBJ) $(LIB) - -install: all -ifndef V - $(SHECHO) " $(PRINSTALL)$(BIN)" -endif - $(INSTALLX) $(BIN) $(INSTALLDIR) - -clean: -ifndef V - $(ECHO) " $(PRCLEAN)$(BIN) $(OBJ) $(DEP)" -endif - -$(RM) $(BIN) $(OBJ) $(DEP) - -.PHONY : all install clean diff --git a/tools/wadconv/wadconv.c b/tools/wadconv/wadconv.c deleted file mode 100644 index 4e9565118..000000000 --- a/tools/wadconv/wadconv.c +++ /dev/null @@ -1,282 +0,0 @@ -// Emacs style mode select -*- C++ -*- -//----------------------------------------------------------------------------- -// -// SRB2 WAD Converter -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -//----------------------------------------------------------------------------- -/// \file wadconv.c -/// \brief Converts wads made for version 2.0 to 2.1. - -#include -#include -#include -#include -#include "wad.h" - -// -// Texture definition. -// Each texture is composed of one or more patches, -// with patches being lumps stored in the WAD. -// The lumps are referenced by number, and patched -// into the rectangular texture space using origin -// and possibly other attributes. -// -typedef struct -{ - wad_int16_t originx, originy; - wad_int16_t patch, stepdir, colormap; -} mappatch_t; - -// -// Texture definition. -// An SRB2 wall texture is a list of patches -// which are to be combined in a predefined order. -// -typedef struct -{ - char name[8]; - wad_int32_t masked; - wad_int16_t width; - wad_int16_t height; - wad_int32_t columndirectory; // FIXTHIS: OBSOLETE - wad_int16_t patchcount; - mappatch_t patches[1]; -} maptexture_t; - -// A single patch from a texture definition, -// basically a rectangular area within -// the texture rectangle. -typedef struct -{ - // Block origin (always UL), which has already accounted for the internal origin of the patch. - wad_uint16_t originx, originy; - lump_t *patch; -} texpatch_t; - -// A maptexturedef_t describes a rectangular texture, -// which is composed of one or more mappatch_t structures -// that arrange graphic patches. -typedef struct -{ - // Keep name for switch changing, etc. - char name[8]; - wad_int16_t width, height; - - // All the patches[patchcount] are drawn back to front into the cached texture. - wad_uint16_t patchcount; - texpatch_t patches[1]; -} texture_t; - -static void ConvertTextures(wad_t *wad) -{ - wad_uint32_t i, j; - lump_t *l; - // PNAMES lump. - char pname[9]; - char *pnamesdata; - lump_t *pnames, **patchlookup; - wad_uint32_t numpatches; - // TEXTURE lump. - lump_t *texturex = NULL; - texture_t **textures; - texpatch_t *patch; - maptexture_t *mtexture; - mappatch_t *mpatch; - wad_uint32_t *directory, *maptex, numtextures, offset; - size_t maxoffset; - // TX_START. - lump_t *tx_start; - - // PNAMES. - if (!(pnames = WAD_CacheLumpInWADByName(wad, "PNAMES"))) - { - printf("error caching lump: %s\n", WAD_Error()); - exit(EXIT_FAILURE); - } - - pnamesdata = pnames->data + 4; - - memcpy(&numpatches, pnames->data, sizeof(wad_uint32_t)); - numpatches = WAD_INT32_Endianness(numpatches); - - if (!(patchlookup = malloc(sizeof(*patchlookup) * numpatches))) - { - printf("unable to allocate patchlookup array for wad %s\n", WAD_BaseName(wad->filename)); - exit(EXIT_FAILURE); - } - - pname[8] = '\0'; - for (i = 0; i < numpatches; i++) - { - strncpy(pname, pnamesdata+i*8, 8); - patchlookup[i] = WAD_LumpInWADByName(wad, pname); - } - - WAD_UncacheLump(pnames); - - // TEXTURE. - - for (i = 1; (texturex = WAD_LumpInWADByName(wad, WAD_VA("TEXTURE%i", i))); i++) - if (texturex) - break; - - texturex = WAD_CacheLump(texturex); - maptex = (wad_uint32_t *)texturex->data; - numtextures = WAD_INT32_Endianness(*maptex); - maxoffset = WAD_LumpSize(texturex); - directory = maptex + 1; - textures = malloc(sizeof(*textures) * numtextures); - - for (i = 0; i < numtextures; i++, directory++) - { - memcpy(&offset, directory, sizeof(wad_uint32_t)); - offset = WAD_INT32_Endianness(offset); - - if (offset > maxoffset) - { - printf("bad texture directory for wad %s\n", WAD_BaseName(wad->filename)); - exit(EXIT_FAILURE); - } - - mtexture = (maptexture_t *)((wad_uint8_t *)maptex + offset); - textures[i] = malloc(sizeof(texture_t) + (sizeof(texpatch_t) * (WAD_INT16_Endianness(mtexture->patchcount) - 1))); - - memcpy(textures[i]->name, mtexture->name, sizeof(textures[i]->name)); - textures[i]->width = WAD_INT16_Endianness(mtexture->width); - textures[i]->height = WAD_INT16_Endianness(mtexture->height); - textures[i]->patchcount = WAD_INT16_Endianness(mtexture->patchcount); - - mpatch = &mtexture->patches[0]; - patch = &textures[i]->patches[0]; - - for (j = 0; j < textures[i]->patchcount; j++, mpatch++, patch++) - { - patch->originx = WAD_INT16_Endianness(mpatch->originx); - patch->originy = WAD_INT16_Endianness(mpatch->originy); - patch->patch = patchlookup[WAD_INT16_Endianness(mpatch->patch)]; - if (!patch->patch) - printf("missing patch in texture %s in wad %s\n", textures[i]->name, wad->filename); - } - } - - WAD_UncacheLump(texturex); - - if (!(tx_start = WAD_LumpInWADByName(wad, "TX_START"))) - { - if (WAD_LumpInWADByName(wad, "P_END")) - tx_start = WAD_AddLumpInWADByNum(wad, WAD_LumpNumByName("P_END") + 1, "TX_START", NULL); - else - tx_start = WAD_AddLump(wad, NULL, "TX_START", NULL); - - if (!tx_start) - { - printf("unable to find TX_START in %s\n", wad->filename); - exit(EXIT_FAILURE); - } - } - WAD_RemoveLumpInWADByName(wad, "TX_END"); - - for (i = 0, l = WAD_LumpInWADByNum(wad, WAD_LumpNum(tx_start) + 1); i < numtextures; i++, directory++) - { - if (textures[i]->patchcount == 1 && !strncmp(textures[i]->name, textures[i]->patches[0].patch->name, 8)) - WAD_MoveLump(textures[i]->patches[0].patch, l); - else - { - FILE *socfile; - char *soc, *socname = textures[i]->name; - - for (j = 0; j < textures[i]->patchcount; j++) - { - if (!strncmp(textures[i]->name, textures[i]->patches[j].patch->name, 8)) - { - wad_int32_t k; - char socname1[5]; - - socname = malloc(sizeof(*socname) * 9); - - socname1[4] = '\0'; - strncpy(socname1, textures[i]->name, 4); - - for (k = 0 ;; k++) - if (!WAD_LumpInWADByName(wad, WAD_VA((k > 9) ? "%sSC%i" : "%sSC0%i", socname1, k))) - break; - - sprintf(socname, (k > 9) ? "%sSC%i" : "%sSC0%i", socname1, k); - break; - } - } - - soc = WAD_VA("%s%s", socname, ".lmp"); - - remove(soc); - socfile = fopen(soc, "wb"); - - fprintf(socfile, "TEXTURE %s\n", textures[i]->name); - fprintf(socfile, "WIDTH = %i\n", textures[i]->width); - fprintf(socfile, "HEIGHT = %i\n", textures[i]->height); - fprintf(socfile, "NUMPATCHES = %i\n\n", textures[i]->patchcount); - - for (j = 0; j < textures[i]->patchcount; j++) - { - fprintf(socfile, "PATCH %s\n", textures[i]->patches[j].patch->name); - fprintf(socfile, "X = %i\n", textures[i]->patches[j].originx); - fprintf(socfile, "Y = %i\n\n", textures[i]->patches[j].originy); - } - - fclose(socfile); - - WAD_AddLump(wad, l, socname, soc); - remove(soc); - } - } - WAD_AddLump(wad, l, "TX_END", NULL); - - WAD_RemoveLump(pnames); - WAD_RemoveLump(texturex); -} - -int main(int argc, char **argv) -{ - wad_t *w; - wad_uint32_t i; - - if (argc < 2) - { - puts("Usage: wadconv [filename]"); - puts("Example: wadconv wadfile.wad"); - return EXIT_FAILURE; - } - - // Open the WAD files. - for (i = 1; i < (unsigned)argc; i++) - { - if (!WAD_OpenWAD(argv[i])) - { - printf("Loading WAD failed: %s\n", WAD_Error()); - return EXIT_FAILURE; - } - } - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - { - w = WAD_WADByNum(i); - // Convert textures. - printf("Converting textures for wad %s...\n", WAD_BaseName(w->filename)); - ConvertTextures(w); - } - - for (i = 0; i < wad_numwads; i = WAD_WADLoopAdvance(i)) - WAD_SaveCloseWADByNum(i); - - puts("Finished."); - return EXIT_SUCCESS; -} diff --git a/tools/wadzip/err.c b/tools/wadzip/err.c deleted file mode 100644 index 37393bfcb..000000000 --- a/tools/wadzip/err.c +++ /dev/null @@ -1,121 +0,0 @@ -#if defined (__WIN32) || defined (WIN32) -#define NEED_ERR -#define LACK_PROGNAME -#define NEED_ENDIAN_STUBS -#define LACK_SYSTYPES -#endif - -#ifdef NEED_ERR - -/* - * Implementation of the err/errx/verr/verrx/warn/warnx/vwarn/vwarnx - * functions from BSD. - * - * This file is public-domain; anyone may deal in it without restriction. - * - * Written by Graue on January 16, 2006. - */ - -/* -err/warn family of functions cheat sheet: - -Print: - last component of program name - [ if fmt is non-NULL - ": " - the formatted error message - ] - [ if function name does not end in x - ": " - strerror(errno) - ] - newline - -Then if function name has "err" in it, quit with exit code `eval'. - -BSD's -x versions actually print ": " at the end if passed NULL, so I -duplicate that behavior. Passing these functions NULL is kind of useless -though. -*/ - -#include -#include -#include -#include -#include - -#ifdef LACK_PROGNAME -char *__progname = "wadzip"; -#else -extern char *__progname; -#endif - -#define progname __progname - -void vwarn(const char *fmt, va_list args) -{ - fputs(progname, stderr); - if (fmt != NULL) - { - fputs(": ", stderr); - vfprintf(stderr, fmt, args); - } - fputs(": ", stderr); - fputs(strerror(errno), stderr); - putc('\n', stderr); -} - -void vwarnx(const char *fmt, va_list args) -{ - fputs(progname, stderr); - fputs(": ", stderr); - if (fmt != NULL) - vfprintf(stderr, fmt, args); - putc('\n', stderr); -} - -void verr(int eval, const char *fmt, va_list args) -{ - vwarn(fmt, args); - exit(eval); -} - -void verrx(int eval, const char *fmt, va_list args) -{ - vwarnx(fmt, args); - exit(eval); -} - -void warn(const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - vwarn(fmt, argptr); - va_end(argptr); -} - -void warnx(const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - vwarnx(fmt, argptr); - va_end(argptr); -} - -void err(int eval, const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - verr(eval, fmt, argptr); - /* NOTREACHED, so don't worry about va_end() */ -} - -void errx(int eval, const char *fmt, ...) -{ - va_list argptr; - va_start(argptr, fmt); - verrx(eval, fmt, argptr); - /* NOTREACHED, so don't worry about va_end() */ -} - -#endif diff --git a/tools/wadzip/err.h b/tools/wadzip/err.h deleted file mode 100644 index 5b9380379..000000000 --- a/tools/wadzip/err.h +++ /dev/null @@ -1,26 +0,0 @@ -#if defined (__WIN32) || defined (WIN32) -#define NEED_ERR -#endif - -#ifndef NEED_ERR -#include /* system version of this file */ -#else - -#ifndef _ERR_H -#define _ERR_H - -#include - -void err (int eval, const char *fmt, ...); -void errx (int eval, const char *fmt, ...); -void verr (int eval, const char *fmt, va_list args); -void verrx (int eval, const char *fmt, va_list args); - -void warn ( const char *fmt, ...); -void warnx( const char *fmt, ...); -void vwarn ( const char *fmt, va_list args); -void vwarnx( const char *fmt, va_list args); - -#endif - -#endif diff --git a/tools/wadzip/lzf.h b/tools/wadzip/lzf.h deleted file mode 100644 index 8538609ab..000000000 --- a/tools/wadzip/lzf.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#ifndef LZF_H -#define LZF_H - -/*********************************************************************** -** -** lzf -- an extremely fast/free compression/decompression-method -** http://liblzf.plan9.de/ -** -** This algorithm is believed to be patent-free. -** -***********************************************************************/ - -#define LZF_VERSION 0x0105 /* 1.5 */ - -/* - * Compress in_len bytes stored at the memory block starting at - * in_data and write the result to out_data, up to a maximum length - * of out_len bytes. - * - * If the output buffer is not large enough or any error occurs - * return 0, otherwise return the number of bytes used (which might - * be considerably larger than in_len, so it makes sense to always - * use out_len == in_len - 1), to ensure _some_ compression, and store - * the data uncompressed otherwise. - * - * lzf_compress might use different algorithms on different systems and - * even diferent runs, thus might result in different compressed strings - * depending on the phase of the moon or similar factors. However, all - * these strings are architecture-independent and will result in the - * original data when decompressed using lzf_decompress. - * - * The buffers must not be overlapping. - * - * If the option LZF_STATE_ARG is enabled, an extra argument must be - * supplied which is not reflected in this header file. Refer to lzfP.h - * and lzf_c.c. - * - */ -unsigned int -lzf_compress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len); - -/* - * Decompress data compressed with some version of the lzf_compress - * function and stored at location in_data and length in_len. The result - * will be stored at out_data up to a maximum of out_len characters. - * - * If the output buffer is not large enough to hold the decompressed - * data, a 0 is returned and errno is set to E2BIG. Otherwise the number - * of decompressed bytes (i.e. the original length of the data) is - * returned. - * - * If an error in the compressed data is detected, a zero is returned and - * errno is set to EINVAL. - * - * This function is very fast, about as fast as a copying loop. - */ -unsigned int -lzf_decompress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len); - -#endif - diff --git a/tools/wadzip/lzfP.h b/tools/wadzip/lzfP.h deleted file mode 100644 index 4d5a21e3c..000000000 --- a/tools/wadzip/lzfP.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#ifndef LZFP_h -#define LZFP_h - -#define STANDALONE 1 /* at the moment, this is ok. */ - -#ifndef STANDALONE -# include "lzf.h" -#endif - -/* - * Size of hashtable is (1 << HLOG) * sizeof (char *) - * decompression is independent of the hash table size - * the difference between 15 and 14 is very small - * for small blocks (and 14 is usually a bit faster). - * For a low-memory/faster configuration, use HLOG == 13; - * For best compression, use 15 or 16 (or more). - */ -#ifndef HLOG -# define HLOG 15 -#endif - -/* - * 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 preferable mode of operation. - */ - -#ifndef VERY_FAST -# define VERY_FAST 1 -#endif - -/* - * 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, - * possibly disable this for text data. - */ -#ifndef ULTRA_FAST -# define ULTRA_FAST 0 -#endif - -/* - * Unconditionally aligning does not cost very much, so do it if unsure - */ -#ifndef STRICT_ALIGN -# define STRICT_ALIGN !(defined(__i386) || defined (__amd64)) -#endif - -/* - * Use string functions to copy memory. - * this is usually a loss, even with glibc's optimized memcpy - */ -#ifndef USE_MEMCPY -# define USE_MEMCPY 0 -#endif - -/* - * You may choose to pre-set the hash table (might be faster on some - * modern cpus and large (>>64k) blocks) - */ -#ifndef INIT_HTAB -# define INIT_HTAB 0 -#endif - -/* - * Avoid assigning values to errno variable? for some embedding purposes - * (linux kernel for example), this is neccessary. NOTE: this breaks - * the documentation in lzf.h. - */ -#ifndef AVOID_ERRNO -# define AVOID_ERRNO 0 -#endif - -/* - * 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. - */ -#ifndef LZF_STATE_ARG -# define LZF_STATE_ARG 0 -#endif - -/* - * 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 noticable on modern hardware - * (<1% slowdown), but might slow down older cpus considerably. - */ -#ifndef CHECK_INPUT -# define CHECK_INPUT 1 -#endif - -/*****************************************************************************/ -/* nothing should be changed below */ - -typedef unsigned char u8; - -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 -# undef STRICT_ALIGN -# define STRICT_ALIGN 1 -# endif -#endif - -#if ULTRA_FAST -# if defined(VERY_FAST) -# undef VERY_FAST -# endif -#endif - -#if USE_MEMCPY || INIT_HTAB -# ifdef __cplusplus -# include -# else -# include -# endif -#endif - -#endif - diff --git a/tools/wadzip/lzf_c.c b/tools/wadzip/lzf_c.c deleted file mode 100644 index b9b9ef991..000000000 --- a/tools/wadzip/lzf_c.c +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#include "lzfP.h" - -#define HSIZE (1 << (HLOG)) - -/* - * don't play with this unless you benchmark! - * 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]) -# 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 */ -# define FRST(p) (p[0] << 5) ^ p[1] -# define NEXT(v,p) ((v) << 5) ^ p[2] -# define IDX(h) ((h) & (HSIZE - 1)) -#endif - -#define MAX_LIT (1 << 5) -#define MAX_OFF (1 << 13) -#define MAX_REF ((1 << 8) + (1 << 3)) - -/* - * compressed format - * - * 000LLLLL ; literal - * LLLooooo oooooooo ; backref L - * 111ooooo LLLLLLLL oooooooo ; backref L+7 - * - */ - -unsigned int -lzf_compress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len -#if LZF_STATE_ARG - , 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; - const u8 *in_end = ip + in_len; - u8 *out_end = op + out_len; - const u8 *ref; - - unsigned int hval = FRST (ip); - unsigned long off; - 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 - - for (;;) - { - if (ip < in_end - 2) - { - hval = NEXT (hval, ip); - hslot = htab + IDX (hval); - ref = *hslot; *hslot = ip; - - if (1 -#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 > (u8 *)in_data -#if STRICT_ALIGN - && ref[0] == ip[0] - && ref[1] == ip[1] - && ref[2] == ip[2] -#else - && *(u16 *)ref == *(u16 *)ip - && ref[2] == ip[2] -#endif - ) - { - /* match found at *ref++ */ - unsigned int len = 2; - unsigned int maxlen = in_end - ip - len; - maxlen = maxlen > MAX_REF ? MAX_REF : maxlen; - - if (op + lit + 1 + 3 >= out_end) - return 0; - - do - len++; - while (len < maxlen && ref[len] == ip[len]); - - if (lit) - { - *op++ = lit - 1; - lit = -lit; - do - *op++ = ip[lit]; - while (++lit); - } - - len -= 2; - ip++; - - if (len < 7) - { - *op++ = (off >> 8) + (len << 5); - } - else - { - *op++ = (off >> 8) + ( 7 << 5); - *op++ = len - 7; - } - - *op++ = off; - -#if ULTRA_FAST || VERY_FAST - 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 if (ip == in_end) - break; - - /* one more literal byte we must copy */ - lit++; - ip++; - - if (lit == MAX_LIT) - { - if (op + 1 + MAX_LIT >= out_end) - return 0; - - *op++ = MAX_LIT - 1; -#if USE_MEMCPY - memcpy (op, ip - MAX_LIT, MAX_LIT); - op += MAX_LIT; - lit = 0; -#else - lit = -lit; - do - *op++ = ip[lit]; - while (++lit); -#endif - } - } - - if (lit) - { - if (op + lit + 1 >= out_end) - return 0; - - *op++ = lit - 1; - lit = -lit; - do - *op++ = ip[lit]; - while (++lit); - } - - return op - (u8 *) out_data; -} diff --git a/tools/wadzip/lzf_d.c b/tools/wadzip/lzf_d.c deleted file mode 100644 index 73a1a80b6..000000000 --- a/tools/wadzip/lzf_d.c +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2000-2005 Marc Alexander Lehmann - * - * Redistribution and use in source and binary forms, with or without modifica- - * tion, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- - * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- - * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- - * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Alternatively, the contents of this file may be used under the terms of - * the GNU General Public License version 2 (the "GPL"), in which case the - * provisions of the GPL are applicable instead of the above. If you wish to - * allow the use of your version of this file only under the terms of the - * GPL and not to allow others to use your version of this file under the - * BSD license, indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by the GPL. If - * you do not delete the provisions above, a recipient may use your version - * of this file under either the BSD or the GPL. - */ - -#include "lzfP.h" - -#if AVOID_ERRNO -# define SET_ERRNO(n) -#else -# include -# define SET_ERRNO(n) errno = (n) -#endif - -unsigned int -lzf_decompress (const void *const in_data, unsigned int in_len, - void *out_data, unsigned int out_len) -{ - u8 const *ip = (const u8 *)in_data; - u8 *op = (u8 *)out_data; - u8 const *const in_end = ip + in_len; - u8 *const out_end = op + out_len; - - do - { - unsigned int ctrl = *ip++; - - if (ctrl < (1 << 5)) /* literal run */ - { - ctrl++; - - if (op + ctrl > out_end) - { - SET_ERRNO (E2BIG); - return 0; - } - -#if CHECK_INPUT - if (ip + ctrl > in_end) - { - SET_ERRNO (EINVAL); - return 0; - } -#endif - -#if USE_MEMCPY - memcpy (op, ip, ctrl); - op += ctrl; - ip += ctrl; -#else - do - *op++ = *ip++; - while (--ctrl); -#endif - } - else /* back reference */ - { - unsigned int len = ctrl >> 5; - - u8 *ref = op - ((ctrl & 0x1f) << 8) - 1; - -#if CHECK_INPUT - if (ip >= in_end) - { - SET_ERRNO (EINVAL); - return 0; - } -#endif - if (len == 7) - { - len += *ip++; -#if CHECK_INPUT - if (ip >= in_end) - { - SET_ERRNO (EINVAL); - return 0; - } -#endif - } - - ref -= *ip++; - - if (op + len + 2 > out_end) - { - SET_ERRNO (E2BIG); - return 0; - } - - if (ref < (u8 *)out_data) - { - SET_ERRNO (EINVAL); - return 0; - } - - *op++ = *ref++; - *op++ = *ref++; - - do - *op++ = *ref++; - while (--len); - } - } - while (ip < in_end); - - return op - (u8 *)out_data; -} - diff --git a/tools/wadzip/wadzip.c b/tools/wadzip/wadzip.c deleted file mode 100644 index c8dae9b61..000000000 --- a/tools/wadzip/wadzip.c +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Wad compressor/decompressor by Graue - * Written January 23, 2007 - * - * This file is in the public domain; use it without any restrictions. - */ - -#include -#include -#ifndef _MSC_VER -#include -#else -typedef unsigned int uint32_t; -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -#endif -#include -#include -#include "err.h" -#include "lzf.h" -#include "xm.h" - -/* Note: Define WORDS_BIGENDIAN if that is the case on the target CPU. */ - -#define MINCOMPRESS 1024 // Don't bother compressing lumps smaller than this. - -#define SWAP16(n) ((((n)&0xff)<<8) | ((n)>>8)) -#define SWAP32(n) \ -( \ - ((((n)&0xff) <<24) \ - | ((((n)>>8)&0xff)<<16) \ - | ((((n)>>16)&0xff)<<8) \ - | ((n)>>24) \ -) -#ifdef WORDS_BIGENDIAN -#define conv16le SWAP16 -#define conv32le SWAP32 -#else -#define conv16le(n) (n) -#define conv32le(n) (n) -#endif -#define READFUNC(name, type, conv) \ -static type name(FILE *fp) \ -{ \ - type val; \ - if (fread(&val, sizeof val, 1, fp) < 1) \ - { \ - if (ferror(fp)) \ - err(1, "error reading input file"); \ - errx(1, "premature end of input file"); \ - } \ - val = conv(val); \ - return val; \ -} -READFUNC(read32le, uint32_t, conv32le) - -#define WRITEFUNC(name, type, conv) \ -static void name(FILE *fp, type val) \ -{ \ - val = conv(val); \ - if (fwrite(&val, sizeof (type), 1, fp) < 1) \ - err(1, "error writing output file"); \ -} -WRITEFUNC(write32le, uint32_t, conv32le) - -#define ID_IWAD 0x44415749 -#define ID_PWAD 0x44415750 -#define ID_ZWAD 0x4441575a // 'ZWAD' for lzf-compressed wad - -typedef struct -{ - char name[8]; - uint32_t len; - void *data; -} lump_t; - -typedef struct -{ - uint32_t id; - uint32_t numlumps; - lump_t *lumps; -} wad_t; - -extern char *__progname; - -static void usage(void) -{ - fprintf(stderr, "usage: %s [cd] infile outfile\n", __progname); - exit(EXIT_FAILURE); -} - -#define fileoffset_t long -#define myseek fseek -#define mytell ftell - -static void readlumpdata(lump_t *lump, uint32_t csize, int compressed, FILE *fp) -{ - uint8_t *cbuf; - uint8_t *ubuf; - uint32_t usize; - unsigned int retval; - - cbuf = xm(1, csize); - if (fread(cbuf, csize, 1, fp) < 1) - err(1, "cannot read lump from input file"); - - if (!compressed) - { - lump->len = csize; - lump->data = cbuf; - return; - } - - usize = conv32le(*(uint32_t *)cbuf); - if (usize == 0) - { - lump->len = csize - 4; - lump->data = cbuf + 4; // XXX cannot be freed later - return; - } - - ubuf = xm(1, usize); - retval = lzf_decompress(cbuf + 4, csize - 4, ubuf, usize); - if (retval == 0) - { - if (errno == E2BIG) - errx(1, "decompressed data bigger than advertised"); - if (errno == EINVAL) - errx(1, "invalid compressed (lzf) data"); - else - err(1, "unknown error from lzf"); - } - else if (retval < usize) - errx(1, "decompressed data smaller than advertised"); - lump->len = usize; - lump->data = ubuf; - free(cbuf); - return; -} - -static wad_t *readwad(const char *fname) -{ - wad_t *wad; - FILE *fp; - int inputcompressed; - fileoffset_t dirstart; - uint32_t ix; - - fp = fopen(fname, "rb"); - if (fp == NULL) err(1, "%s", fname); - - wad = xm(sizeof *wad, 1); - - // Read wad id. If it is ZWAD, prepare to read compressed lumps. - wad->id = read32le(fp); - inputcompressed = wad->id == ID_ZWAD; - - // Read number of lumps, and prepare space for that many. - wad->numlumps = read32le(fp); - wad->lumps = xm(sizeof wad->lumps[0], wad->numlumps); - - // Read offset to directory. - dirstart = (fileoffset_t)read32le(fp); - - for (ix = 0; ix < wad->numlumps; ix++) - { - fileoffset_t lumpofs; - uint32_t lumpsize; // The compressed size, if it is compressed. - - if (myseek(fp, dirstart + (16*ix), SEEK_SET) == -1) - { - err(1, "cannot seek input file to dir entry %lu", - (unsigned long)ix); - } - lumpofs = (fileoffset_t)read32le(fp); - lumpsize = read32le(fp); - if (fread(wad->lumps[ix].name, 1, 8, fp) < 8) - err(1, "cannot read lump %lu name", (unsigned long)ix); - - // Don't try to seek to zero-length lumps. - // Their offset is meaningless. - if (lumpsize == 0) - { - wad->lumps[ix].len = 0; - continue; - } - - if (myseek(fp, lumpofs, SEEK_SET) == -1) - err(1, "cannot seek to lump %lu", (unsigned long)ix); - readlumpdata(&wad->lumps[ix], lumpsize, inputcompressed, fp); - } - - if (fclose(fp) == EOF) - warn("error closing input file %s", fname); - return wad; -} - -void writewad(const wad_t *wad, const char *fname, int compress) -{ - uint32_t *lumpofs; // Each lump's offset in the file. - uint32_t *disksize; // Each lump's disk size (compressed if applicable). - uint32_t dirstart; - uint32_t ix; - FILE *fp; - - lumpofs = xm(sizeof lumpofs[0], wad->numlumps); - disksize = xm(sizeof disksize[0], wad->numlumps); - - fp = fopen(fname, "wb"); - if (fp == NULL) err(1, "%s", fname); - - // Write header. - write32le(fp, compress ? ID_ZWAD : ID_PWAD); - write32le(fp, wad->numlumps); - write32le(fp, 0); // Directory table comes later. - - for (ix = 0; ix < wad->numlumps; ix++) - { - uint8_t *cbuf; - uint32_t csize; - - lumpofs[ix] = (uint32_t)mytell(fp); - if (!compress) - { - cbuf = wad->lumps[ix].data; - csize = wad->lumps[ix].len; - } - else - { - unsigned int retval; - - csize = wad->lumps[ix].len + 4; - cbuf = xm(1, csize); - if (wad->lumps[ix].len < MINCOMPRESS - || (retval = lzf_compress(wad->lumps[ix].data, - wad->lumps[ix].len, cbuf + 4, - csize - 5)) == 0) - { - // Store uncompressed. - memcpy(cbuf + 4, wad->lumps[ix].data, - wad->lumps[ix].len); - *(uint32_t *)cbuf = 0; - } - else - { - // Compression succeeded. - // Store uncompressed size, and set compressed - // size properly. - *(uint32_t *)cbuf = - conv32le(wad->lumps[ix].len); - csize = retval + 4; - } - } - - if (!csize) - ; // inu: 0 length markers aren't to be written - else if (fwrite(cbuf, csize, 1, fp) < 1) - { - err(1, "cannot write lump %lu to %s", (unsigned long)ix, - fname); - } - - if (compress) - free(cbuf); - disksize[ix] = csize; - } - - dirstart = (uint32_t)mytell(fp); - if (myseek(fp, 8L, SEEK_SET) == -1) - err(1, "cannot reseek %s to write directory start", fname); - write32le(fp, dirstart); - if (myseek(fp, dirstart, SEEK_SET) == -1) - err(1, "cannot reseek %s to write actual directory", fname); - - for (ix = 0; ix < wad->numlumps; ix++) - { - // Write the lump's directory entry. - write32le(fp, lumpofs[ix]); - write32le(fp, disksize[ix]); - if (fwrite(wad->lumps[ix].name, 1, 8, fp) < 8) - { - err(1, "cannot write lump %lu's name", - (unsigned long)ix); - } - } - - if (fclose(fp) == EOF) - warn("error closing output file %s", fname); -} - -int main(int argc, char *argv[]) -{ - const char *infile, *outfile; - wad_t *wad; - int compress; - - if (argc != 4 || strlen(argv[1]) != 1) - usage(); - - /* c to compress, d to decompress */ - if (argv[1][0] == 'c') compress = 1; - else if (argv[1][0] == 'd') compress = 0; - else usage(); - - infile = argv[2]; - outfile = argv[3]; - - wad = readwad(infile); - writewad(wad, outfile, compress); - return 0; -} diff --git a/tools/wadzip/wadzip.dsp b/tools/wadzip/wadzip.dsp deleted file mode 100644 index 85f1f99ad..000000000 --- a/tools/wadzip/wadzip.dsp +++ /dev/null @@ -1,104 +0,0 @@ -# Microsoft Developer Studio Project File - Name="wadzip" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=wadzip - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "wadzip.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "wadzip.mak" CFG="wadzip - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "wadzip - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "wadzip - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "wadzip - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 - -!ELSEIF "$(CFG)" == "wadzip - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept - -!ENDIF - -# Begin Target - -# Name "wadzip - Win32 Release" -# Name "wadzip - Win32 Debug" -# Begin Source File - -SOURCE=.\err.c -# End Source File -# Begin Source File - -SOURCE=.\lzf_c.c -# End Source File -# Begin Source File - -SOURCE=.\lzf_d.c -# End Source File -# Begin Source File - -SOURCE=.\wadzip.c -# End Source File -# Begin Source File - -SOURCE=.\xm.c -# End Source File -# End Target -# End Project diff --git a/tools/wadzip/wadzip.dsw b/tools/wadzip/wadzip.dsw deleted file mode 100644 index c4bd785a2..000000000 --- a/tools/wadzip/wadzip.dsw +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "wadzip"=.\wadzip.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/tools/wadzip/wadzip.txt b/tools/wadzip/wadzip.txt deleted file mode 100644 index 24d05d0f0..000000000 --- a/tools/wadzip/wadzip.txt +++ /dev/null @@ -1,30 +0,0 @@ -Compressed wad format: - -Just like a normal wad, except: - -1. The header id at the very beginning says "ZWAD" -instead of PWAD or IWAD. - -2. The first four bytes of each lump are (little -endian) the uncompressed size. If this is zero, -the lump is not compressed, and you can subtract -four from the size given in the wadfile directory. - -3. Unless those first four bytes give a value of -0, the lump is compressed with liblzf after that. - - - -To compile this program, just compiling all its -source files should work, that is: - gcc *.c -o wadzip - -[On a big-endian CPU, add "-DWORDS_BIGENDIAN" to -that command line.] - -Visual C++ should also work, as well as gcc. - -Compress a wad: - wadzip c original.wad compressed.wad -Decompress a wad (restoring the original): - wadzip d compressed.wad original.wad diff --git a/tools/wadzip/xm.c b/tools/wadzip/xm.c deleted file mode 100644 index f388bab9e..000000000 --- a/tools/wadzip/xm.c +++ /dev/null @@ -1,76 +0,0 @@ -/* Fail-proof memory allocation by Graue ; public domain */ - -#include -#include -#include "err.h" - -/* MinGW (for example) appears to lack SIZE_T_MAX. */ -#ifndef SIZE_T_MAX -#define SIZE_T_MAX ULONG_MAX -#endif - -/* - * The usual xmalloc and xrealloc type routines, for allocating memory - * and bombing out if it fails. - * - * xm and xr here take two values: size and nmemb, like fread/fwrite. - * The idea is to be able to check for overflow, to prevent some weird - * crashes and security problems that can arise if you multiply size - * and nmemb and they overflow. - */ - -/* FIXME: use %zu (size_t) in these format arguments if library is C99 */ - -/* - * Multiply size and number of elements, bombing out if overflow would - * occur. - - * Note: In the case where size*nmemb is exactly equal to SIZE_T_MAX, - * this function considers that an overflow, even though it isn't - * really. But it's not likely the program will get that much memory, - * anyway. - */ -static size_t sizmul(size_t size, size_t nmemb) -{ - if (SIZE_T_MAX / size <= nmemb) - { - errx(1, "allocating %lu objects of size %lu " - "would overflow", (unsigned long)nmemb, - (unsigned long)size); - } - return size * nmemb; /* won't overflow */ -} - -static void nomem(size_t size, size_t nmemb) -{ - err(1, "cannot allocate %lu objects of size %lu " - "(total %lu bytes)", (unsigned long)nmemb, - (unsigned long)size, (unsigned long)(nmemb*size)); -} - -void *xm(size_t size, size_t nmemb) -{ - const size_t bytes = sizmul(size, nmemb); - void *p; - - p = malloc(bytes); - if (p == NULL) nomem(size, nmemb); - return p; -} - -void *xr(void *p, size_t size, size_t nmemb) -{ - const size_t bytes = sizmul(size, nmemb); - - p = realloc(p, bytes); - if (p == NULL) nomem(size, nmemb); - return p; -} - -/* expand array */ -void *xpnd(void *p, int nit, int *sit, size_t sz) -{ - if (nit < *sit) return p; - else if (*sit > 0) return xr(p, sz, (*sit *= 2)); - else return xm(sz, (*sit = 10)); -} diff --git a/tools/wadzip/xm.h b/tools/wadzip/xm.h deleted file mode 100644 index d57f8479b..000000000 --- a/tools/wadzip/xm.h +++ /dev/null @@ -1,4 +0,0 @@ -void *xm(size_t size, size_t nmemb); -void *xr(void *p, size_t size, size_t nmemb); -void *xpnd(void *p, int nit, int *sit, size_t sz); -#define XPND(p, num, spc) (p = xpnd(p, num, &spc, sizeof *p))