timer now simply returns same time twice if the time input wraps, and posts a warning...
[divverent/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 Sys_Error (char *error, ...)
182 {
183         va_list         argptr;
184         char            text[1024], text2[1024];
185         char            *text3 = "Press Enter to exit\n";
186         char            *text4 = "***********************************\n";
187         char            *text5 = "\n";
188         DWORD           dummy;
189         double          starttime;
190         static int      in_sys_error0 = 0;
191         static int      in_sys_error1 = 0;
192         static int      in_sys_error2 = 0;
193         static int      in_sys_error3 = 0;
194
195         if (!in_sys_error3)
196                 in_sys_error3 = 1;
197
198         va_start (argptr, error);
199         vsprintf (text, error, argptr);
200         va_end (argptr);
201
202         if (cls.state == ca_dedicated)
203         {
204                 va_start (argptr, error);
205                 vsprintf (text, error, argptr);
206                 va_end (argptr);
207
208                 sprintf (text2, "ERROR: %s\n", text);
209                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
210                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
211                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
212                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
213                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
214
215
216                 starttime = Sys_DoubleTime ();
217                 sc_return_on_enter = true;      // so Enter will get us out of here
218
219                 while (!Sys_ConsoleInput () && ((Sys_DoubleTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
220                         SleepUntilInput(1);
221         }
222         else
223         {
224         // switch to windowed so the message box is visible, unless we already
225         // tried that and failed
226                 if (!in_sys_error0)
227                 {
228                         in_sys_error0 = 1;
229                         VID_SetDefaultMode ();
230                         MessageBox(NULL, text, "Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
231                 }
232                 else
233                         MessageBox(NULL, text, "Double Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
234         }
235
236         if (!in_sys_error1)
237         {
238                 in_sys_error1 = 1;
239                 Host_Shutdown ();
240         }
241
242 // shut down QHOST hooks if necessary
243         if (!in_sys_error2)
244         {
245                 in_sys_error2 = 1;
246                 DeinitConProc ();
247         }
248
249         exit (1);
250 }
251
252 void Sys_Quit (void)
253 {
254         Host_Shutdown();
255
256         if (tevent)
257                 CloseHandle (tevent);
258
259         if (cls.state == ca_dedicated)
260                 FreeConsole ();
261
262 // shut down QHOST hooks if necessary
263         DeinitConProc ();
264
265         exit (0);
266 }
267
268
269 /*
270 ================
271 Sys_DoubleTime
272 ================
273 */
274 double Sys_DoubleTime (void)
275 {
276         static int first = true;
277         static double oldtime = 0.0, curtime = 0.0;
278         double newtime;
279         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
280 #if WIN32_USETIMEGETTIME
281         // timeGetTime
282         // platform:
283         // Windows 95/98/ME/NT/2000
284         // features:
285         // reasonable accuracy (millisecond)
286         // issues:
287         // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
288
289         // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
290         if (first)
291                 timeBeginPeriod (1);
292
293         newtime = (double) timeGetTime () / 1000.0;
294 #else
295         // QueryPerformanceCounter
296         // platform:
297         // Windows 95/98/ME/NT/2000
298         // features:
299         // very accurate (CPU cycles)
300         // known issues:
301         // does not necessarily match realtime too well (tends to get faster and faster in win98)
302         // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
303         static double timescale = 0.0;
304         LARGE_INTEGER PerformanceFreq;
305         LARGE_INTEGER PerformanceCount;
306
307         if (!QueryPerformanceFrequency (&PerformanceFreq))
308                 Sys_Error ("No hardware timer available");
309         QueryPerformanceCounter (&PerformanceCount);
310
311 #ifdef __BORLANDC__
312         timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
313         newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
314 #else
315         timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
316         newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
317 #endif
318 #endif
319
320         if (first)
321         {
322                 first = false;
323                 oldtime = newtime;
324         }
325
326         if (newtime < oldtime)
327                 Con_Printf("Sys_DoubleTime: time running backwards??\n");
328         else
329         {
330                 curtime += newtime - oldtime;
331                 oldtime = newtime;
332         }
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                  oldtime, newtime;
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         oldtime = 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                 newtime = Sys_DoubleTime ();
589                 Host_Frame (newtime - oldtime);
590                 oldtime = newtime;
591         }
592
593         /* return success of application */
594         return true;
595 }
596