2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 // sys_win.c -- Win32 system interface code
29 // LordHavoc: raised min to 24mb (was 8.5mb)
30 #define MINIMUM_WIN_MEMORY 0x1800000
31 // LordHavoc: raised max to 24mb (was 16mb)
32 #define MAXIMUM_WIN_MEMORY 0x1800000
34 #define CONSOLE_ERROR_TIMEOUT 60.0 // # of seconds to wait on Sys_Error running
35 // dedicated before exiting
36 #define PAUSE_SLEEP 50 // sleep time on pause or minimization
37 #define NOT_FOCUS_SLEEP 20 // sleep time when not focus
40 qboolean ActiveApp, Minimized;
44 static double curtime = 0.0;
45 static double lastcurtime = 0.0;
48 static qboolean sc_return_on_enter = false;
49 HANDLE hinput, houtput;
51 static char *tracking_tag = "Clams & Mooses";
55 static HANDLE heventParent;
56 static HANDLE heventChild;
58 void MaskExceptions (void);
59 void Sys_InitFloatTime (void);
60 void Sys_PushFPCW_SetHigh (void);
61 void Sys_PopFPCW (void);
63 volatile int sys_checksum;
71 void Sys_PageIn (void *ptr, int size)
76 // touch all the memory to make sure it's there. The 16-page skip is to
77 // keep Win 95 from thinking we're trying to page ourselves in (we are
78 // doing that, of course, but there's no reason we shouldn't)
83 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
85 sys_checksum += *(int *)&x[m];
86 sys_checksum += *(int *)&x[m + 16 * 0x1000];
93 ===============================================================================
97 ===============================================================================
100 // LordHavoc: 256 pak files (was 10)
101 #define MAX_HANDLES 256
102 FILE *sys_handles[MAX_HANDLES];
104 int findhandle (void)
108 for (i=1 ; i<MAX_HANDLES ; i++)
111 Sys_Error ("out of handles");
120 int filelength (FILE *f)
126 t = VID_ForceUnlockedAndReturnState ();
129 fseek (f, 0, SEEK_END);
131 fseek (f, pos, SEEK_SET);
133 VID_ForceLockState (t);
138 int Sys_FileOpenRead (char *path, int *hndl)
144 t = VID_ForceUnlockedAndReturnState ();
148 f = fopen(path, "rb");
159 retval = filelength(f);
162 VID_ForceLockState (t);
167 int Sys_FileOpenWrite (char *path)
173 t = VID_ForceUnlockedAndReturnState ();
177 f = fopen(path, "wb");
179 Host_Error ("Error opening %s: %s", path,strerror(errno));
182 VID_ForceLockState (t);
187 void Sys_FileClose (int handle)
191 t = VID_ForceUnlockedAndReturnState ();
192 fclose (sys_handles[handle]);
193 sys_handles[handle] = NULL;
194 VID_ForceLockState (t);
197 void Sys_FileSeek (int handle, int position)
201 t = VID_ForceUnlockedAndReturnState ();
202 fseek (sys_handles[handle], position, SEEK_SET);
203 VID_ForceLockState (t);
206 int Sys_FileRead (int handle, void *dest, int count)
210 t = VID_ForceUnlockedAndReturnState ();
211 x = fread (dest, 1, count, sys_handles[handle]);
212 VID_ForceLockState (t);
216 int Sys_FileWrite (int handle, void *data, int count)
220 t = VID_ForceUnlockedAndReturnState ();
221 x = fwrite (data, 1, count, sys_handles[handle]);
222 VID_ForceLockState (t);
226 int Sys_FileTime (char *path)
231 t = VID_ForceUnlockedAndReturnState ();
233 f = fopen(path, "rb");
245 VID_ForceLockState (t);
249 void Sys_mkdir (char *path)
256 ===============================================================================
260 ===============================================================================
265 Sys_MakeCodeWriteable
268 void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
272 if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect))
273 Sys_Error("Protection change failed\n");
279 void Sys_SetFPCW (void)
283 void Sys_PushFPCW_SetHigh (void)
287 void Sys_PopFPCW (void)
291 void MaskExceptions (void)
304 LARGE_INTEGER PerformanceFreq;
305 unsigned int lowpart, highpart;
311 if (!QueryPerformanceFrequency (&PerformanceFreq))
312 Sys_Error ("No hardware timer available");
314 // get 32 out of the 64 time bits such that we have around
315 // 1 microsecond resolution
316 lowpart = (unsigned int)PerformanceFreq.LowPart;
317 highpart = (unsigned int)PerformanceFreq.HighPart;
320 while (highpart || (lowpart > 2000000.0))
324 lowpart |= (highpart & 1) << 31;
328 pfreq = 1.0 / (double)lowpart;
330 Sys_InitFloatTime ();
332 vinfo.dwOSVersionInfoSize = sizeof(vinfo);
334 if (!GetVersionEx (&vinfo))
335 Sys_Error ("Couldn't get OS info");
337 if ((vinfo.dwMajorVersion < 4) ||
338 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
340 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
343 if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
350 void Sys_Error (char *error, ...)
353 char text[1024], text2[1024];
354 char *text3 = "Press Enter to exit\n";
355 char *text4 = "***********************************\n";
359 static int in_sys_error0 = 0;
360 static int in_sys_error1 = 0;
361 static int in_sys_error2 = 0;
362 static int in_sys_error3 = 0;
367 VID_ForceUnlockedAndReturnState ();
370 va_start (argptr, error);
371 vsprintf (text, error, argptr);
376 va_start (argptr, error);
377 vsprintf (text, error, argptr);
380 sprintf (text2, "ERROR: %s\n", text);
381 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
382 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
383 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
384 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
385 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
388 starttime = Sys_FloatTime ();
389 sc_return_on_enter = true; // so Enter will get us out of here
391 while (!Sys_ConsoleInput () &&
392 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
398 // switch to windowed so the message box is visible, unless we already
399 // tried that and failed
403 VID_SetDefaultMode ();
404 MessageBox(NULL, text, "Quake Error",
405 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
409 MessageBox(NULL, text, "Double Quake Error",
410 MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
420 // shut down QHOST hooks if necessary
430 void Sys_Printf (char *fmt, ...)
438 va_start (argptr,fmt);
439 vsprintf (text, fmt, argptr);
442 WriteFile(houtput, text, strlen (text), &dummy, NULL);
449 VID_ForceUnlockedAndReturnState ();
454 CloseHandle (tevent);
459 // shut down QHOST hooks if necessary
471 double Sys_FloatTime (void)
473 static int sametimecount;
474 static unsigned int oldtime;
475 static int first = 1;
476 LARGE_INTEGER PerformanceCount;
477 unsigned int temp, t2;
480 Sys_PushFPCW_SetHigh ();
482 QueryPerformanceCounter (&PerformanceCount);
484 temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
485 ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
494 // check for turnover or backward time
495 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
497 oldtime = temp; // so we can't get stuck
503 time = (double)t2 * pfreq;
508 if (curtime == lastcurtime)
512 if (sametimecount > 100000)
523 lastcurtime = curtime;
538 void Sys_InitFloatTime (void)
544 j = COM_CheckParm("-starttime");
548 curtime = (double) (atof(com_argv[j+1]));
555 lastcurtime = curtime;
559 char *Sys_ConsoleInput (void)
561 static char text[256];
563 INPUT_RECORD recs[1024];
565 int ch, numread, numevents;
573 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
574 Sys_Error ("Error getting # of console events");
579 if (!ReadConsoleInput(hinput, recs, 1, &numread))
580 Sys_Error ("Error reading console input");
583 Sys_Error ("Couldn't read console input");
585 if (recs[0].EventType == KEY_EVENT)
587 if (!recs[0].Event.KeyEvent.bKeyDown)
589 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
594 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
602 else if (sc_return_on_enter)
604 // special case to allow exiting from the error handler on Enter
613 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
623 WriteFile(houtput, &ch, 1, &dummy, NULL);
625 len = (len + 1) & 0xff;
638 void Sys_Sleep (void)
644 void Sys_SendKeyEvents (void)
648 while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
650 // we always update if there are any event, even if we're paused
653 if (!GetMessage (&msg, NULL, 0, 0))
656 TranslateMessage (&msg);
657 DispatchMessage (&msg);
663 ==============================================================================
667 ==============================================================================
676 void SleepUntilInput (int time)
679 MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT);
688 HINSTANCE global_hInstance;
690 char *argv[MAX_NUM_ARGVS];
691 static char *empty_string = "";
695 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
698 double time, oldtime, newtime/*, timediff*/;
699 MEMORYSTATUS lpBuffer;
700 static char cwd[1024];
704 /* previous instances do not exist in Win32 */
708 global_hInstance = hInstance;
709 global_nCmdShow = nCmdShow;
711 lpBuffer.dwLength = sizeof(MEMORYSTATUS);
712 GlobalMemoryStatus (&lpBuffer);
714 if (!GetCurrentDirectory (sizeof(cwd), cwd))
715 Sys_Error ("Couldn't determine current directory");
717 if (cwd[strlen(cwd)-1] == '/')
718 cwd[strlen(cwd)-1] = 0;
721 parms.cachedir = NULL;
724 argv[0] = empty_string;
726 while (*lpCmdLine && (parms.argc < MAX_NUM_ARGVS))
728 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
733 argv[parms.argc] = lpCmdLine;
736 while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
750 COM_InitArgv (parms.argc, parms.argv);
752 parms.argc = com_argc;
753 parms.argv = com_argv;
755 isDedicated = (COM_CheckParm ("-dedicated") != 0);
759 hwnd_dialog = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
763 if (GetWindowRect (hwnd_dialog, &rect))
765 if (rect.left > (rect.top * 2))
767 SetWindowPos (hwnd_dialog, 0,
768 (rect.left / 2) - ((rect.right - rect.left) / 2),
770 SWP_NOZORDER | SWP_NOSIZE);
774 ShowWindow (hwnd_dialog, SW_SHOWDEFAULT);
775 UpdateWindow (hwnd_dialog);
776 SetForegroundWindow (hwnd_dialog);
780 // take the greater of all the available memory or half the total memory,
781 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
783 parms.memsize = lpBuffer.dwAvailPhys;
785 if (parms.memsize < MINIMUM_WIN_MEMORY)
786 parms.memsize = MINIMUM_WIN_MEMORY;
788 if (parms.memsize < (lpBuffer.dwTotalPhys >> 1))
789 parms.memsize = lpBuffer.dwTotalPhys >> 1;
791 if (parms.memsize > MAXIMUM_WIN_MEMORY)
792 parms.memsize = MAXIMUM_WIN_MEMORY;
794 if (COM_CheckParm ("-heapsize"))
796 t = COM_CheckParm("-heapsize") + 1;
799 parms.memsize = atoi (com_argv[t]) * 1024;
802 if (COM_CheckParm ("-mem"))
804 t = COM_CheckParm("-mem") + 1;
807 parms.memsize = atoi (com_argv[t]) * 1048576;
810 if (COM_CheckParm ("-winmem"))
812 t = COM_CheckParm("-winmem") + 1;
815 parms.memsize = atoi (com_argv[t]) * 1048576;
818 parms.membase = malloc (parms.memsize);
821 Sys_Error ("Not enough memory free; check disk space\n");
823 Sys_PageIn (parms.membase, parms.memsize);
825 tevent = CreateEvent(NULL, FALSE, FALSE, NULL);
828 Sys_Error ("Couldn't create event");
832 if (!AllocConsole ())
834 Sys_Error ("Couldn't create dedicated server console");
837 hinput = GetStdHandle (STD_INPUT_HANDLE);
838 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
840 // give QHOST a chance to hook into the console
841 if ((t = COM_CheckParm ("-HFILE")) > 0)
844 hFile = (HANDLE)atoi (com_argv[t+1]);
847 if ((t = COM_CheckParm ("-HPARENT")) > 0)
850 heventParent = (HANDLE)atoi (com_argv[t+1]);
853 if ((t = COM_CheckParm ("-HCHILD")) > 0)
856 heventChild = (HANDLE)atoi (com_argv[t+1]);
859 InitConProc (hFile, heventParent, heventChild);
864 // because sound is off until we become active
867 Sys_Printf ("Host_Init\n");
870 oldtime = Sys_FloatTime ();
872 /* main window message loop */
877 newtime = Sys_FloatTime ();
878 time = newtime - oldtime;
880 while (time < sys_ticrate.value )
883 newtime = Sys_FloatTime ();
884 time = newtime - oldtime;
889 // yield the CPU for a little while when paused, minimized, or not the focus
890 if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
892 SleepUntilInput (PAUSE_SLEEP);
893 scr_skipupdate = 1; // no point in bothering to draw
895 else if (!ActiveApp && !DDActive)
897 SleepUntilInput (NOT_FOCUS_SLEEP);
900 else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
902 newtime = Sys_FloatTime ();
903 time = newtime - oldtime;
905 while (time < timediff)
908 newtime = Sys_FloatTime ();
909 time = newtime - oldtime;
914 newtime = Sys_FloatTime ();
915 time = newtime - oldtime;
922 /* return success of application */