if the OS returns a very bogus time (or it wrapped), warn about it and keep ticking
[xonotic/darkplaces.git] / sys_win.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // sys_win.c -- Win32 system interface code
21
22 #define WIN32_USETIMEGETTIME 0
23
24 #include "quakedef.h"
25 #include "winquake.h"
26 #include "errno.h"
27 #include "resource.h"
28 #include "conproc.h"
29 #include "direct.h"
30
31 // # of seconds to wait on Sys_Error running dedicated before exiting
32 #define CONSOLE_ERROR_TIMEOUT   60.0
33 // sleep time on pause or minimization
34 #define PAUSE_SLEEP             50
35 // sleep time when not focus
36 #define NOT_FOCUS_SLEEP 20
37
38 int                     starttime;
39 qboolean        ActiveApp, Minimized;
40
41 static qboolean         sc_return_on_enter = false;
42 HANDLE                          hinput, houtput;
43
44 static HANDLE   tevent;
45 static HANDLE   hFile;
46 static HANDLE   heventParent;
47 static HANDLE   heventChild;
48
49 /*
50 ===============================================================================
51
52 QFile IO
53
54 ===============================================================================
55 */
56
57 // LordHavoc: 256 pak files (was 10)
58 #define MAX_HANDLES             256
59 QFile   *sys_handles[MAX_HANDLES];
60
61 int             findhandle (void)
62 {
63         int             i;
64
65         for (i=1 ; i<MAX_HANDLES ; i++)
66                 if (!sys_handles[i])
67                         return i;
68         Sys_Error ("out of handles");
69         return -1;
70 }
71
72 /*
73 ================
74 Sys_FileLength
75 ================
76 */
77 int Sys_FileLength (QFile *f)
78 {
79         int             pos;
80         int             end;
81
82         pos = Qtell (f);
83         Qseek (f, 0, SEEK_END);
84         end = Qtell (f);
85         Qseek (f, pos, SEEK_SET);
86
87         return end;
88 }
89
90 int Sys_FileOpenRead (char *path, int *hndl)
91 {
92         QFile   *f;
93         int             i, retval;
94
95         i = findhandle ();
96
97         f = Qopen(path, "rbz");
98
99         if (!f)
100         {
101                 *hndl = -1;
102                 retval = -1;
103         }
104         else
105         {
106                 sys_handles[i] = f;
107                 *hndl = i;
108                 retval = Sys_FileLength(f);
109         }
110
111         return retval;
112 }
113
114 int Sys_FileOpenWrite (char *path)
115 {
116         QFile   *f;
117         int             i;
118
119         i = findhandle ();
120
121         f = Qopen(path, "wb");
122         if (!f)
123         {
124                 Con_Printf("Sys_FileOpenWrite: Error opening %s: %s", path, strerror(errno));
125                 return 0;
126         }
127         sys_handles[i] = f;
128
129         return i;
130 }
131
132 void Sys_FileClose (int handle)
133 {
134         Qclose (sys_handles[handle]);
135         sys_handles[handle] = NULL;
136 }
137
138 void Sys_FileSeek (int handle, int position)
139 {
140         Qseek (sys_handles[handle], position, SEEK_SET);
141 }
142
143 int Sys_FileRead (int handle, void *dest, int count)
144 {
145         return Qread (sys_handles[handle], dest, count);
146 }
147
148 int Sys_FileWrite (int handle, void *data, int count)
149 {
150         return Qwrite (sys_handles[handle], data, count);
151 }
152
153 int     Sys_FileTime (char *path)
154 {
155         QFile   *f;
156
157         f = Qopen(path, "rb");
158         if (f)
159         {
160                 Qclose(f);
161                 return 1;
162         }
163
164         return -1;
165 }
166
167 void Sys_mkdir (char *path)
168 {
169         _mkdir (path);
170 }
171
172
173 /*
174 ===============================================================================
175
176 SYSTEM IO
177
178 ===============================================================================
179 */
180
181 void SleepUntilInput (int time);
182
183 void Sys_Error (char *error, ...)
184 {
185         va_list         argptr;
186         char            text[1024], text2[1024];
187         char            *text3 = "Press Enter to exit\n";
188         char            *text4 = "***********************************\n";
189         char            *text5 = "\n";
190         DWORD           dummy;
191         double          starttime;
192         static int      in_sys_error0 = 0;
193         static int      in_sys_error1 = 0;
194         static int      in_sys_error2 = 0;
195         static int      in_sys_error3 = 0;
196
197         if (!in_sys_error3)
198                 in_sys_error3 = 1;
199
200         va_start (argptr, error);
201         vsprintf (text, error, argptr);
202         va_end (argptr);
203
204         if (cls.state == ca_dedicated)
205         {
206                 va_start (argptr, error);
207                 vsprintf (text, error, argptr);
208                 va_end (argptr);
209
210                 sprintf (text2, "ERROR: %s\n", text);
211                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
212                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
213                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
214                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
215                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
216
217
218                 starttime = Sys_DoubleTime ();
219                 sc_return_on_enter = true;      // so Enter will get us out of here
220
221                 while (!Sys_ConsoleInput () && ((Sys_DoubleTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
222                         SleepUntilInput(1);
223         }
224         else
225         {
226         // switch to windowed so the message box is visible, unless we already
227         // tried that and failed
228                 if (!in_sys_error0)
229                 {
230                         in_sys_error0 = 1;
231                         VID_SetDefaultMode ();
232                         MessageBox(NULL, text, "Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
233                 }
234                 else
235                         MessageBox(NULL, text, "Double Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
236         }
237
238         if (!in_sys_error1)
239         {
240                 in_sys_error1 = 1;
241                 Host_Shutdown ();
242         }
243
244 // shut down QHOST hooks if necessary
245         if (!in_sys_error2)
246         {
247                 in_sys_error2 = 1;
248                 DeinitConProc ();
249         }
250
251         exit (1);
252 }
253
254 void Sys_Quit (void)
255 {
256         Host_Shutdown();
257
258         if (tevent)
259                 CloseHandle (tevent);
260
261         if (cls.state == ca_dedicated)
262                 FreeConsole ();
263
264 // shut down QHOST hooks if necessary
265         DeinitConProc ();
266
267         exit (0);
268 }
269
270
271 /*
272 ================
273 Sys_DoubleTime
274 ================
275 */
276 double Sys_DoubleTime (void)
277 {
278         static int first = true;
279         static double oldtime = 0.0, curtime = 0.0;
280         double newtime;
281         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
282 #if WIN32_USETIMEGETTIME
283         // timeGetTime
284         // platform:
285         // Windows 95/98/ME/NT/2000
286         // features:
287         // reasonable accuracy (millisecond)
288         // issues:
289         // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
290
291         // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
292         if (first)
293                 timeBeginPeriod (1);
294
295         newtime = (double) timeGetTime () / 1000.0;
296 #else
297         // QueryPerformanceCounter
298         // platform:
299         // Windows 95/98/ME/NT/2000
300         // features:
301         // very accurate (CPU cycles)
302         // known issues:
303         // does not necessarily match realtime too well (tends to get faster and faster in win98)
304         // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
305         static double timescale = 0.0;
306         LARGE_INTEGER PerformanceFreq;
307         LARGE_INTEGER PerformanceCount;
308
309         if (!QueryPerformanceFrequency (&PerformanceFreq))
310                 Sys_Error ("No hardware timer available");
311         QueryPerformanceCounter (&PerformanceCount);
312
313 #ifdef __BORLANDC__
314         timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
315         newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
316 #else
317         timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
318         newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
319 #endif
320 #endif
321
322         if (first)
323         {
324                 first = false;
325                 oldtime = newtime;
326         }
327
328         if (newtime < oldtime)
329                 Con_Printf("Sys_DoubleTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, newtime - oldtime);
330         else
331                 curtime += newtime - oldtime;
332         oldtime = newtime;
333
334         return curtime;
335 }
336
337
338 char *Sys_ConsoleInput (void)
339 {
340         static char text[256];
341         static int len;
342         INPUT_RECORD recs[1024];
343         int ch;
344         DWORD numread, numevents, dummy;
345
346         if (cls.state != ca_dedicated)
347                 return NULL;
348
349
350         for ( ;; )
351         {
352                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
353                         Sys_Error ("Error getting # of console events");
354
355                 if (numevents <= 0)
356                         break;
357
358                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
359                         Sys_Error ("Error reading console input");
360
361                 if (numread != 1)
362                         Sys_Error ("Couldn't read console input");
363
364                 if (recs[0].EventType == KEY_EVENT)
365                 {
366                         if (!recs[0].Event.KeyEvent.bKeyDown)
367                         {
368                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
369
370                                 switch (ch)
371                                 {
372                                         case '\r':
373                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
374
375                                                 if (len)
376                                                 {
377                                                         text[len] = 0;
378                                                         len = 0;
379                                                         return text;
380                                                 }
381                                                 else if (sc_return_on_enter)
382                                                 {
383                                                 // special case to allow exiting from the error handler on Enter
384                                                         text[0] = '\r';
385                                                         len = 0;
386                                                         return text;
387                                                 }
388
389                                                 break;
390
391                                         case '\b':
392                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
393                                                 if (len)
394                                                 {
395                                                         len--;
396                                                 }
397                                                 break;
398
399                                         default:
400                                                 if (ch >= ' ')
401                                                 {
402                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);
403                                                         text[len] = ch;
404                                                         len = (len + 1) & 0xff;
405                                                 }
406
407                                                 break;
408
409                                 }
410                         }
411                 }
412         }
413
414         return NULL;
415 }
416
417 void Sys_Sleep (void)
418 {
419         Sleep (1);
420 }
421
422
423 void Sys_SendKeyEvents (void)
424 {
425         MSG msg;
426
427         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
428         {
429         // we always update if there are any event, even if we're paused
430                 scr_skipupdate = 0;
431
432                 if (!GetMessage (&msg, NULL, 0, 0))
433                         Sys_Quit ();
434
435                 TranslateMessage (&msg);
436                 DispatchMessage (&msg);
437         }
438 }
439
440
441 /*
442 ==============================================================================
443
444 WINDOWS CRAP
445
446 ==============================================================================
447 */
448
449
450 void SleepUntilInput (int time)
451 {
452         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
453 }
454
455
456 /*
457 ==================
458 WinMain
459 ==================
460 */
461 HINSTANCE       global_hInstance;
462 int                     global_nCmdShow;
463 char            *argv[MAX_NUM_ARGVS];
464 static char     *empty_string = "";
465
466 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
467 {
468         double                  frameoldtime, framenewtime;
469         MEMORYSTATUS    lpBuffer;
470         static  char    cwd[1024];
471         int                             t;
472
473         /* previous instances do not exist in Win32 */
474         if (hPrevInstance)
475                 return 0;
476
477         global_hInstance = hInstance;
478         global_nCmdShow = nCmdShow;
479
480         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
481         GlobalMemoryStatus (&lpBuffer);
482
483         if (!GetCurrentDirectory (sizeof(cwd), cwd))
484                 Sys_Error ("Couldn't determine current directory");
485
486         if (cwd[strlen(cwd)-1] == '/')
487                 cwd[strlen(cwd)-1] = 0;
488
489         memset(&host_parms, 0, sizeof(host_parms));
490
491         host_parms.basedir = cwd;
492
493         host_parms.argc = 1;
494         argv[0] = empty_string;
495
496         while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS))
497         {
498                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
499                         lpCmdLine++;
500
501                 if (*lpCmdLine)
502                 {
503                         argv[host_parms.argc] = lpCmdLine;
504                         host_parms.argc++;
505
506                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
507                                 lpCmdLine++;
508
509                         if (*lpCmdLine)
510                         {
511                                 *lpCmdLine = 0;
512                                 lpCmdLine++;
513                         }
514
515                 }
516         }
517
518         host_parms.argv = argv;
519
520         COM_InitArgv (host_parms.argc, host_parms.argv);
521
522         host_parms.argc = com_argc;
523         host_parms.argv = com_argv;
524
525         Sys_Shared_EarlyInit();
526
527         tevent = CreateEvent(NULL, false, false, NULL);
528
529         if (!tevent)
530                 Sys_Error ("Couldn't create event");
531
532         // LordHavoc: can't check cls.state because it hasn't been initialized yet
533         // if (cls.state == ca_dedicated)
534         if (COM_CheckParm("-dedicated"))
535         {
536                 if (!AllocConsole ())
537                         Sys_Error ("Couldn't create dedicated server console");
538
539                 hinput = GetStdHandle (STD_INPUT_HANDLE);
540                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
541
542         // give QHOST a chance to hook into the console
543                 if ((t = COM_CheckParm ("-HFILE")) > 0)
544                 {
545                         if (t < com_argc)
546                                 hFile = (HANDLE)atoi (com_argv[t+1]);
547                 }
548
549                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
550                 {
551                         if (t < com_argc)
552                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
553                 }
554
555                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
556                 {
557                         if (t < com_argc)
558                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
559                 }
560
561                 InitConProc (hFile, heventParent, heventChild);
562         }
563
564 // because sound is off until we become active
565         S_BlockSound ();
566
567         Host_Init ();
568
569         Sys_Shared_LateInit();
570
571         frameoldtime = Sys_DoubleTime ();
572
573         /* main window message loop */
574         while (1)
575         {
576                 if (cls.state != ca_dedicated)
577                 {
578                 // yield the CPU for a little while when paused, minimized, or not the focus
579                         if ((cl.paused && !ActiveApp) || Minimized)
580                         {
581                                 SleepUntilInput (PAUSE_SLEEP);
582                                 scr_skipupdate = 1;             // no point in bothering to draw
583                         }
584                         else if (!ActiveApp)
585                                 SleepUntilInput (NOT_FOCUS_SLEEP);
586                 }
587
588                 framenewtime = Sys_DoubleTime ();
589                 Host_Frame (framenewtime - frameoldtime);
590                 frameoldtime = framenewtime;
591         }
592
593         /* return success of application */
594         return true;
595 }
596