]> git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - sys_shared.c
sys: commenting and tidying
[xonotic/darkplaces.git] / sys_shared.c
index c3b4bab73914425ff91137d422d9beb7504cbad4..286ff7e5a80f1e13df408a3d3e470ea3b9ded7e1 100644 (file)
@@ -4,16 +4,14 @@
 # endif
 #endif
 
-#include "quakedef.h"
-#include "taskqueue.h"
-#include "thread.h"
-
 #define SUPPORTDLL
 
 #ifdef WIN32
 # include <windows.h>
 # include <mmsystem.h> // timeGetTime
 # include <time.h> // localtime
+# include <conio.h> // _kbhit, _getch, _putch
+# include <io.h> // write; Include this BEFORE darkplaces.h because it uses strncpy which trips DP_STATIC_ASSERT
 #ifdef _MSC_VER
 #pragma comment(lib, "winmm.lib")
 #endif
@@ -21,6 +19,9 @@
 # ifdef __FreeBSD__
 #  include <sys/sysctl.h>
 # endif
+# ifdef __ANDROID__
+#  include <android/log.h>
+# endif
 # include <unistd.h>
 # include <fcntl.h>
 # include <sys/time.h>
 # endif
 #endif
 
+#include <signal.h>
+
+#include "quakedef.h"
+#include "taskqueue.h"
+#include "thread.h"
+#include "libcurl.h"
+
+sys_t sys;
+
 static char sys_timestring[128];
 char *Sys_TimeString(const char *timeformat)
 {
@@ -48,10 +58,8 @@ char *Sys_TimeString(const char *timeformat)
 void Sys_Quit (int returnvalue)
 {
        // Unlock mutexes because the quit command may jump directly here, causing a deadlock
-       if ((&cmd_client)->cbuf->lock)
-               Cbuf_Unlock((&cmd_client)->cbuf);
-       if ((&cmd_server)->cbuf->lock)
-               Cbuf_Unlock((&cmd_server)->cbuf);
+       if ((cmd_local)->cbuf->lock)
+               Cbuf_Unlock((cmd_local)->cbuf);
        SV_UnlockThreadMutex();
        TaskQueue_Frame(true);
 
@@ -59,6 +67,15 @@ void Sys_Quit (int returnvalue)
                Sys_AllowProfiling(false);
        host.state = host_shutdown;
        Host_Shutdown();
+
+#ifdef __ANDROID__
+       Sys_AllowProfiling(false);
+#endif
+#ifndef WIN32
+       fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
+#endif
+       fflush(stdout);
+
        exit(returnvalue);
 }
 
@@ -91,7 +108,7 @@ DLL MANAGEMENT
 ===============================================================================
 */
 
-static qbool Sys_LoadLibraryFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
+static qbool Sys_LoadDependencyFunctions(dllhandle_t dllhandle, const dllfunction_t *fcts, qbool complain, qbool has_next)
 {
        const dllfunction_t *func;
        if(dllhandle)
@@ -116,7 +133,22 @@ static qbool Sys_LoadLibraryFunctions(dllhandle_t dllhandle, const dllfunction_t
        return false;
 }
 
-qbool Sys_LoadLibrary (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
+qbool Sys_LoadSelf(dllhandle_t *handle)
+{
+       dllhandle_t dllhandle = 0;
+
+       if (handle == NULL)
+               return false;
+#ifdef WIN32
+       dllhandle = LoadLibrary (NULL);
+#else
+       dllhandle = dlopen (NULL, RTLD_NOW | RTLD_GLOBAL);
+#endif
+       *handle = dllhandle;
+       return true;
+}
+
+qbool Sys_LoadDependency (const char** dllnames, dllhandle_t* handle, const dllfunction_t *fcts)
 {
 #ifdef SUPPORTDLL
        const dllfunction_t *func;
@@ -129,14 +161,14 @@ qbool Sys_LoadLibrary (const char** dllnames, dllhandle_t* handle, const dllfunc
 #ifndef WIN32
 #ifdef PREFER_PRELOAD
        dllhandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
-       if(Sys_LoadLibraryFunctions(dllhandle, fcts, false, false))
+       if(Sys_LoadDependencyFunctions(dllhandle, fcts, false, false))
        {
                Con_DPrintf ("All of %s's functions were already linked in! Not loading dynamically...\n", dllnames[0]);
                *handle = dllhandle;
                return true;
        }
        else
-               Sys_UnloadLibrary(&dllhandle);
+               Sys_FreeLibrary(&dllhandle);
 notfound:
 #endif
 #endif
@@ -158,15 +190,14 @@ notfound:
                SetDllDirectory("bin32");
 #  endif
 # endif
-               dllhandle = LoadLibrary (dllnames[i]);
-               // no need to unset this - we want ALL dlls to be loaded from there, anyway
-#else
-               dllhandle = dlopen (dllnames[i], RTLD_LAZY | RTLD_GLOBAL);
 #endif
-               if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
-                       break;
-               else
-                       Sys_UnloadLibrary (&dllhandle);
+               if(Sys_LoadLibrary(dllnames[i], &dllhandle))
+               {
+                       if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
+                               break;
+                       else
+                               Sys_FreeLibrary (&dllhandle);
+               }
        }
 
        // see if the names can be loaded relative to the executable path
@@ -182,15 +213,14 @@ notfound:
                        strlcpy(temp, path, sizeof(temp));
                        strlcat(temp, dllnames[i], sizeof(temp));
                        Con_DPrintf (" \"%s\"", temp);
-#ifdef WIN32
-                       dllhandle = LoadLibrary (temp);
-#else
-                       dllhandle = dlopen (temp, RTLD_LAZY | RTLD_GLOBAL);
-#endif
-                       if (Sys_LoadLibraryFunctions(dllhandle, fcts, true, dllnames[i+1] != NULL))
-                               break;
-                       else
-                               Sys_UnloadLibrary (&dllhandle);
+
+                       if(Sys_LoadLibrary(temp, &dllhandle))
+                       {
+                               if (Sys_LoadDependencyFunctions(dllhandle, fcts, true, (dllnames[i+1] != NULL) || (strrchr(sys.argv[0], '/'))))
+                                       break;
+                               else
+                                       Sys_FreeLibrary (&dllhandle);
+                       }
                }
        }
 
@@ -211,7 +241,28 @@ notfound:
 #endif
 }
 
-void Sys_UnloadLibrary (dllhandle_t* handle)
+qbool Sys_LoadLibrary(const char *name, dllhandle_t *handle)
+{
+       dllhandle_t dllhandle = 0;
+
+       if(handle == NULL)
+               return false;
+
+#ifdef SUPPORTDLL
+# ifdef WIN32
+       dllhandle = LoadLibrary (name);
+# else
+       dllhandle = dlopen (name, RTLD_LAZY | RTLD_GLOBAL);
+# endif
+#endif
+       if(!dllhandle)
+               return false;
+
+       *handle = dllhandle;
+       return true;
+}
+
+void Sys_FreeLibrary (dllhandle_t* handle)
 {
 #ifdef SUPPORTDLL
        if (handle == NULL || *handle == NULL)
@@ -254,12 +305,8 @@ void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
 # define HAVE_GETTIMEOFDAY 1
 #endif
 
-#ifndef WIN32
-// on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
-// (so much for POSIX...)
-# ifdef FD_SET
-#  define HAVE_SELECT 1
-# endif
+#ifdef FD_SET
+# define HAVE_SELECT 1
 #endif
 
 #ifndef WIN32
@@ -267,18 +314,19 @@ void* Sys_GetProcAddress (dllhandle_t handle, const char* name)
 # define HAVE_USLEEP 1
 #endif
 
-// this one is referenced elsewhere
-cvar_t sys_usenoclockbutbenchmark = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usenoclockbutbenchmark", "0", "don't use ANY real timing, and simulate a clock (for benchmarking); the game then runs as fast as possible. Run a QC mod with bots that does some stuff, then does a quit at the end, to benchmark a server. NEVER do this on a public server."};
+// these are referenced elsewhere
+cvar_t sys_usenoclockbutbenchmark = {CF_SHARED, "sys_usenoclockbutbenchmark", "0", "don't use ANY real timing, and simulate a clock (for benchmarking); the game then runs as fast as possible. Run a QC mod with bots that does some stuff, then does a quit at the end, to benchmark a server. NEVER do this on a public server."};
+cvar_t sys_libdir = {CF_READONLY | CF_SHARED, "sys_libdir", "", "Default engine library directory"};
 
 // these are not
-static cvar_t sys_debugsleep = {CF_CLIENT | CF_SERVER, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
-static cvar_t sys_usesdlgetticks = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
-static cvar_t sys_usesdldelay = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
+static cvar_t sys_debugsleep = {CF_SHARED, "sys_debugsleep", "0", "write requested and attained sleep times to standard output, to be used with gnuplot"};
+static cvar_t sys_usesdlgetticks = {CF_SHARED, "sys_usesdlgetticks", "0", "use SDL_GetTicks() timer (less accurate, for debugging)"};
+static cvar_t sys_usesdldelay = {CF_SHARED, "sys_usesdldelay", "0", "use SDL_Delay() (less accurate, for debugging)"};
 #if HAVE_QUERYPERFORMANCECOUNTER
-static cvar_t sys_usequeryperformancecounter = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_usequeryperformancecounter", "0", "use windows QueryPerformanceCounter timer (which has issues on multicore/multiprocessor machines and processors which are designed to conserve power) for timing rather than timeGetTime function (which has issues on some motherboards)"};
+static cvar_t sys_usequeryperformancecounter = {CF_SHARED | CF_ARCHIVE, "sys_usequeryperformancecounter", "0", "use windows QueryPerformanceCounter timer (which has issues on multicore/multiprocessor machines and processors which are designed to conserve power) for timing rather than timeGetTime function (which has issues on some motherboards)"};
 #endif
 #if HAVE_CLOCKGETTIME
-static cvar_t sys_useclockgettime = {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sys_useclockgettime", "1", "use POSIX clock_gettime function (not adjusted by NTP on some older Linux kernels) for timing rather than gettimeofday (which has issues if the system time is stepped by ntpdate, or apparently on some Xen installations)"};
+static cvar_t sys_useclockgettime = {CF_SHARED | CF_ARCHIVE, "sys_useclockgettime", "1", "use POSIX clock_gettime function (not adjusted by NTP on some older Linux kernels) for timing rather than gettimeofday (which has issues if the system time is stepped by ntpdate, or apparently on some Xen installations)"};
 #endif
 
 static double benchmark_time; // actually always contains an integer amount of milliseconds, will eventually "overflow"
@@ -310,6 +358,7 @@ void Sys_Init_Commands (void)
 {
        Cvar_RegisterVariable(&sys_debugsleep);
        Cvar_RegisterVariable(&sys_usenoclockbutbenchmark);
+       Cvar_RegisterVariable(&sys_libdir);
 #if HAVE_TIMEGETTIME || HAVE_QUERYPERFORMANCECOUNTER || HAVE_CLOCKGETTIME || HAVE_GETTIMEOFDAY
        if(sys_supportsdlgetticks)
        {
@@ -421,60 +470,139 @@ double Sys_DirtyTime(void)
 #endif
 }
 
-void Sys_Sleep(int microseconds)
+extern cvar_t host_maxwait;
+double Sys_Sleep(double time)
 {
-       double t = 0;
+       double dt;
+       uint32_t microseconds;
+
+       // convert to microseconds
+       time *= 1000000.0;
+
+       if(host_maxwait.value <= 0)
+               time = min(time, 1000000.0);
+       else
+               time = min(time, host_maxwait.value * 1000.0);
+
+       if (time < 1 || host.restless)
+               return 0; // not sleeping this frame
+
+       microseconds = time; // post-validation to prevent overflow
+
        if(sys_usenoclockbutbenchmark.integer)
        {
-               if(microseconds)
-               {
-                       double old_benchmark_time = benchmark_time;
-                       benchmark_time += microseconds;
-                       if(benchmark_time == old_benchmark_time)
-                               Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
-               }
-               return;
+               double old_benchmark_time = benchmark_time;
+               benchmark_time += microseconds;
+               if(benchmark_time == old_benchmark_time)
+                       Sys_Error("sys_usenoclockbutbenchmark cannot run any longer, sorry");
+               return 0;
        }
+
        if(sys_debugsleep.integer)
+               Con_Printf("sys_debugsleep: requesting %u ", microseconds);
+       dt = Sys_DirtyTime();
+
+       // less important on newer libcurl so no need to disturb dedicated servers
+       if (cls.state != ca_dedicated && Curl_Select(microseconds))
        {
-               t = Sys_DirtyTime();
+               // a transfer is ready or we finished sleeping
        }
-       if(sys_supportsdlgetticks && sys_usesdldelay.integer)
-       {
+       else if(sys_supportsdlgetticks && sys_usesdldelay.integer)
                Sys_SDL_Delay(microseconds / 1000);
-       }
 #if HAVE_SELECT
        else
        {
                struct timeval tv;
+               lhnetsocket_t *s;
+               fd_set fdreadset;
+               int lastfd = -1;
+
+               FD_ZERO(&fdreadset);
+               if (cls.state == ca_dedicated && sv_checkforpacketsduringsleep.integer)
+               {
+                       List_For_Each_Entry(s, &lhnet_socketlist.list, lhnetsocket_t, list)
+                       {
+                               if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
+                               {
+                                       if (lastfd < s->inetsocket)
+                                               lastfd = s->inetsocket;
+       #if defined(WIN32) && !defined(_MSC_VER)
+                                       FD_SET((int)s->inetsocket, &fdreadset);
+       #else
+                                       FD_SET((unsigned int)s->inetsocket, &fdreadset);
+       #endif
+                               }
+                       }
+               }
                tv.tv_sec = microseconds / 1000000;
                tv.tv_usec = microseconds % 1000000;
-               select(0, NULL, NULL, NULL, &tv);
+               // on Win32, select() cannot be used with all three FD list args being NULL according to MSDN
+               // (so much for POSIX...)
+               // bones_was_here: but a zeroed fd_set seems to be tolerated (tested on Win 7)
+               select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
        }
 #elif HAVE_USLEEP
        else
-       {
                usleep(microseconds);
-       }
 #elif HAVE_Sleep
        else
-       {
                Sleep(microseconds / 1000);
-       }
 #else
        else
-       {
                Sys_SDL_Delay(microseconds / 1000);
-       }
 #endif
+
+       dt = Sys_DirtyTime() - dt;
        if(sys_debugsleep.integer)
+               Con_Printf(" got %u oversleep %d\n", (unsigned int)(dt * 1000000), (unsigned int)(dt * 1000000) - microseconds);
+       return (dt < 0 || dt >= 1800) ? 0 : dt;
+}
+
+
+/*
+===============================================================================
+
+STDIO
+
+===============================================================================
+*/
+
+void Sys_Print(const char *text)
+{
+#ifdef __ANDROID__
+       if (developer.integer > 0)
+       {
+               __android_log_write(ANDROID_LOG_DEBUG, sys.argv[0], text);
+       }
+#else
+       if(sys.outfd < 0)
+               return;
+  #ifndef WIN32
+       // BUG: for some reason, NDELAY also affects stdout (1) when used on stdin (0).
+       // this is because both go to /dev/tty by default!
        {
-               t = Sys_DirtyTime() - t;
-               Sys_PrintfToTerminal("%d %d # debugsleep\n", microseconds, (unsigned int)(t * 1000000));
+               int origflags = fcntl (sys.outfd, F_GETFL, 0);
+               fcntl (sys.outfd, F_SETFL, origflags & ~O_NONBLOCK);
+  #else
+    #define write _write
+  #endif
+               while(*text)
+               {
+                       fs_offset_t written = (fs_offset_t)write(sys.outfd, text, (int)strlen(text));
+                       if(written <= 0)
+                               break; // sorry, I cannot do anything about this error - without an output
+                       text += written;
+               }
+  #ifndef WIN32
+               fcntl (sys.outfd, F_SETFL, origflags);
        }
+  #endif
+       //fprintf(stdout, "%s", text);
+#endif
 }
 
-void Sys_PrintfToTerminal(const char *fmt, ...)
+/// for the console to report failures inside Con_Printf()
+void Sys_Printf(const char *fmt, ...)
 {
        va_list argptr;
        char msg[MAX_INPUTLINE];
@@ -483,7 +611,101 @@ void Sys_PrintfToTerminal(const char *fmt, ...)
        dpvsnprintf(msg,sizeof(msg),fmt,argptr);
        va_end(argptr);
 
-       Sys_PrintToTerminal(msg);
+       Sys_Print(msg);
+}
+
+/// Reads a line from POSIX stdin or the Windows console
+char *Sys_ConsoleInput(void)
+{
+       static char text[MAX_INPUTLINE];
+       static unsigned int len = 0;
+#ifdef WIN32
+       int c;
+
+       // read a line out
+       while (_kbhit ())
+       {
+               c = _getch ();
+               if (c == '\r')
+               {
+                       text[len] = '\0';
+                       _putch ('\n');
+                       len = 0;
+                       return text;
+               }
+               if (c == '\b')
+               {
+                       if (len)
+                       {
+                               _putch (c);
+                               _putch (' ');
+                               _putch (c);
+                               len--;
+                       }
+                       continue;
+               }
+               if (len < sizeof (text) - 1)
+               {
+                       _putch (c);
+                       text[len] = c;
+                       len++;
+               }
+       }
+#else
+       fd_set fdset;
+       struct timeval timeout;
+       FD_ZERO(&fdset);
+       FD_SET(0, &fdset); // stdin
+       timeout.tv_sec = 0;
+       timeout.tv_usec = 0;
+       if (select (1, &fdset, NULL, NULL, &timeout) != -1 && FD_ISSET(0, &fdset))
+       {
+               len = read (0, text, sizeof(text) - 1);
+               if (len >= 1)
+               {
+                       // rip off the \n and terminate
+                       // div0: WHY? console code can deal with \n just fine
+                       // this caused problems with pasting stuff into a terminal window
+                       // so, not ripping off the \n, but STILL keeping a NUL terminator
+                       text[len] = 0;
+                       return text;
+               }
+       }
+#endif
+       return NULL;
+}
+
+
+/*
+===============================================================================
+
+Startup and Shutdown
+
+===============================================================================
+*/
+
+void Sys_Error (const char *error, ...)
+{
+       va_list argptr;
+       char string[MAX_INPUTLINE];
+
+// change stdin to non blocking
+#ifndef WIN32
+       fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK);
+#endif
+
+       va_start (argptr,error);
+       dpvsnprintf (string, sizeof (string), error, argptr);
+       va_end (argptr);
+
+       Con_Printf(CON_ERROR "Engine Error: %s\n", string);
+
+       // don't want a dead window left blocking the OS UI or the crash dialog
+       Host_Shutdown();
+
+       Sys_SDL_Dialog("Engine Error", string);
+
+       exit (1);
 }
 
 #ifndef WIN32
@@ -553,7 +775,7 @@ void Sys_ProvideSelfFD(void)
 static int CPUID_Features(void)
 {
        int features = 0;
-# if defined((__GNUC__) || (__clang__) || (__TINYC__)) && defined(__i386__)
+# if (defined(__GNUC__) || defined(__clang__) || defined(__TINYC__)) && defined(__i386__)
         __asm__ (
 "        movl    %%ebx,%%edi\n"
 "        xorl    %%eax,%%eax                                           \n"
@@ -679,3 +901,37 @@ void Sys_MakeProcessMean (void)
 {
 }
 #endif
+
+int main (int argc, char **argv)
+{
+       signal(SIGFPE, SIG_IGN);
+
+       sys.argc = argc;
+       sys.argv = (const char **)argv;
+
+       // COMMANDLINEOPTION: -noterminal disables console output on stdout
+       if(Sys_CheckParm("-noterminal"))
+               sys.outfd = -1;
+       // COMMANDLINEOPTION: -stderr moves console output to stderr
+       else if(Sys_CheckParm("-stderr"))
+               sys.outfd = 2;
+       else
+               sys.outfd = 1;
+
+       sys.selffd = -1;
+       Sys_ProvideSelfFD(); // may call Con_Printf() so must be after sys.outfd is set
+
+#ifndef WIN32
+       fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK);
+#endif
+
+#ifdef __ANDROID__
+       Sys_AllowProfiling(true);
+#endif
+
+       Host_Main();
+
+       Sys_Quit(0);
+
+       return 0;
+}