]> icculus.org git repositories - divverent/darkplaces.git/blob - sys_win.c
fix the off-by-one fix (oops)
[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 #define CONSOLE_ERROR_TIMEOUT   60.0    // # of seconds to wait on Sys_Error running
32                                                                                 //  dedicated before exiting
33 #define PAUSE_SLEEP             50                              // sleep time on pause or minimization
34 #define NOT_FOCUS_SLEEP 20                              // sleep time when not focus
35
36 int                     starttime;
37 qboolean        ActiveApp, Minimized;
38
39 qboolean                        isDedicated;
40 static qboolean         sc_return_on_enter = false;
41 HANDLE                          hinput, houtput;
42
43 static char                     *tracking_tag = "Clams & Mooses";
44
45 static HANDLE   tevent;
46 static HANDLE   hFile;
47 static HANDLE   heventParent;
48 static HANDLE   heventChild;
49
50 volatile int                                    sys_checksum;
51
52
53 /*
54 ================
55 Sys_PageIn
56 ================
57 */
58 /*
59 void Sys_PageIn (void *ptr, int size)
60 {
61         byte    *x;
62         int             m, n;
63
64 // touch all the memory to make sure it's there. The 16-page skip is to
65 // keep Win 95 from thinking we're trying to page ourselves in (we are
66 // doing that, of course, but there's no reason we shouldn't)
67         x = (byte *)ptr;
68
69         for (n=0 ; n<4 ; n++)
70         {
71                 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
72                 {
73                         sys_checksum += *(int *)&x[m];
74                         sys_checksum += *(int *)&x[m + 16 * 0x1000];
75                 }
76         }
77 }
78 */
79
80
81 /*
82 ===============================================================================
83
84 QFile IO
85
86 ===============================================================================
87 */
88
89 // LordHavoc: 256 pak files (was 10)
90 #define MAX_HANDLES             256
91 QFile   *sys_handles[MAX_HANDLES];
92
93 int             findhandle (void)
94 {
95         int             i;
96         
97         for (i=1 ; i<MAX_HANDLES ; i++)
98                 if (!sys_handles[i])
99                         return i;
100         Sys_Error ("out of handles");
101         return -1;
102 }
103
104 /*
105 ================
106 filelength
107 ================
108 */
109 int filelength (QFile *f)
110 {
111         int             pos;
112         int             end;
113
114         pos = Qtell (f);
115         Qseek (f, 0, SEEK_END);
116         end = Qtell (f);
117         Qseek (f, pos, SEEK_SET);
118
119         return end;
120 }
121
122 int Sys_FileOpenRead (char *path, int *hndl)
123 {
124         QFile   *f;
125         int             i, retval;
126
127         i = findhandle ();
128
129         f = Qopen(path, "rbz");
130
131         if (!f)
132         {
133                 *hndl = -1;
134                 retval = -1;
135         }
136         else
137         {
138                 sys_handles[i] = f;
139                 *hndl = i;
140                 retval = filelength(f);
141         }
142
143         return retval;
144 }
145
146 int Sys_FileOpenWrite (char *path)
147 {
148         QFile   *f;
149         int             i;
150
151         i = findhandle ();
152
153         f = Qopen(path, "wb");
154         if (!f)
155         {
156                 Con_Printf("Sys_FileOpenWrite: Error opening %s: %s", path, strerror(errno));
157                 return 0;
158         }
159         sys_handles[i] = f;
160         
161         return i;
162 }
163
164 void Sys_FileClose (int handle)
165 {
166         Qclose (sys_handles[handle]);
167         sys_handles[handle] = NULL;
168 }
169
170 void Sys_FileSeek (int handle, int position)
171 {
172         Qseek (sys_handles[handle], position, SEEK_SET);
173 }
174
175 int Sys_FileRead (int handle, void *dest, int count)
176 {
177         return Qread (sys_handles[handle], dest, count);
178 }
179
180 int Sys_FileWrite (int handle, void *data, int count)
181 {
182         return Qwrite (sys_handles[handle], data, count);
183 }
184
185 int     Sys_FileTime (char *path)
186 {
187         QFile   *f;
188         
189         f = Qopen(path, "rb");
190         if (f)
191         {
192                 Qclose(f);
193                 return 1;
194         }
195         
196         return -1;
197 }
198
199 void Sys_mkdir (char *path)
200 {
201         _mkdir (path);
202 }
203
204
205 /*
206 ===============================================================================
207
208 SYSTEM IO
209
210 ===============================================================================
211 */
212
213 void Sys_Error (char *error, ...)
214 {
215         va_list         argptr;
216         char            text[1024], text2[1024];
217         char            *text3 = "Press Enter to exit\n";
218         char            *text4 = "***********************************\n";
219         char            *text5 = "\n";
220         DWORD           dummy;
221         double          starttime;
222         static int      in_sys_error0 = 0;
223         static int      in_sys_error1 = 0;
224         static int      in_sys_error2 = 0;
225         static int      in_sys_error3 = 0;
226
227         if (!in_sys_error3)
228                 in_sys_error3 = 1;
229
230         va_start (argptr, error);
231         vsprintf (text, error, argptr);
232         va_end (argptr);
233
234         if (isDedicated)
235         {
236                 va_start (argptr, error);
237                 vsprintf (text, error, argptr);
238                 va_end (argptr);
239
240                 sprintf (text2, "ERROR: %s\n", text);
241                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
242                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
243                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
244                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
245                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
246
247
248                 starttime = Sys_DoubleTime ();
249                 sc_return_on_enter = true;      // so Enter will get us out of here
250
251                 while (!Sys_ConsoleInput () &&
252                                 ((Sys_DoubleTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
253                 {
254                 }
255         }
256         else
257         {
258         // switch to windowed so the message box is visible, unless we already
259         // tried that and failed
260                 if (!in_sys_error0)
261                 {
262                         in_sys_error0 = 1;
263                         VID_SetDefaultMode ();
264                         MessageBox(NULL, text, "Quake Error",
265                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
266                 }
267                 else
268                 {
269                         MessageBox(NULL, text, "Double Quake Error",
270                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
271                 }
272         }
273
274         if (!in_sys_error1)
275         {
276                 in_sys_error1 = 1;
277                 Host_Shutdown ();
278         }
279
280 // shut down QHOST hooks if necessary
281         if (!in_sys_error2)
282         {
283                 in_sys_error2 = 1;
284                 DeinitConProc ();
285         }
286
287         exit (1);
288 }
289
290 void Sys_Printf (char *fmt, ...)
291 {
292         va_list         argptr;
293         char            text[1024];
294         DWORD           dummy;
295         
296         if (isDedicated)
297         {
298                 va_start (argptr,fmt);
299                 vsprintf (text, fmt, argptr);
300                 va_end (argptr);
301
302                 WriteFile(houtput, text, strlen (text), &dummy, NULL);  
303         }
304 }
305
306 void Sys_Quit (void)
307 {
308
309         Host_Shutdown();
310
311         if (tevent)
312                 CloseHandle (tevent);
313
314         if (isDedicated)
315                 FreeConsole ();
316
317 // shut down QHOST hooks if necessary
318         DeinitConProc ();
319
320         exit (0);
321 }
322
323
324 /*
325 ================
326 Sys_DoubleTime
327 ================
328 */
329 double Sys_DoubleTime (void)
330 {
331         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
332 #if WIN32_USETIMEGETTIME
333         // timeGetTime
334         // platform:
335         // Windows 95/98/ME/NT/2000
336         // features:
337         // reasonable accuracy (millisecond)
338         // issues:
339         // none known
340         static int first = true;
341         static double oldtime = 0.0, basetime = 0.0, old = 0.0;
342         double newtime, now;
343
344         now = (double) timeGetTime () + basetime;
345
346         if (first)
347         {
348                 first = false;
349                 basetime = now;
350                 now = 0;
351         }
352
353         if (now < old)
354         {
355                 // wrapped
356                 basetime += (65536.0 * 65536.0);
357                 now += (65536.0 * 65536.0);
358         }
359         old = now;
360
361         newtime = now / 1000.0;
362
363         if (newtime < oldtime)
364                 Sys_Error("Sys_DoubleTime: time running backwards??\n");
365
366         oldtime = newtime;
367
368         return newtime;
369 #else
370         // QueryPerformanceCounter
371         // platform:
372         // Windows 95/98/ME/NT/2000
373         // features:
374         // very accurate (CPU cycles)
375         // known issues:
376         // does not necessarily match realtime too well (tends to get faster and faster in win98)
377         static int first = true;
378         static double oldtime = 0.0, basetime = 0.0, timescale = 0.0;
379         double newtime;
380         LARGE_INTEGER PerformanceFreq;
381         LARGE_INTEGER PerformanceCount;
382
383         if (first)
384         {
385                 if (!QueryPerformanceFrequency (&PerformanceFreq))
386                         Sys_Error ("No hardware timer available");
387
388 #ifdef __BORLANDC__
389                 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
390 #else
391                 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
392 #endif  
393         }
394
395         QueryPerformanceCounter (&PerformanceCount);
396
397 #ifdef __BORLANDC__
398         newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale - basetime;
399 #else
400         newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale - basetime;
401 #endif  
402
403         if (first)
404         {
405                 first = false;
406                 basetime = newtime;
407                 newtime = 0;
408         }
409
410         if (newtime < oldtime)
411                 Sys_Error("Sys_DoubleTime: time running backwards??\n");
412
413         oldtime = newtime;
414
415         return newtime;
416 #endif
417 }
418
419
420 char *Sys_ConsoleInput (void)
421 {
422         static char     text[256];
423         static int              len;
424         INPUT_RECORD    recs[1024];
425         int             dummy;
426         int             ch, numread, numevents;
427
428         if (!isDedicated)
429                 return NULL;
430
431
432         for ( ;; )
433         {
434                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
435                         Sys_Error ("Error getting # of console events");
436
437                 if (numevents <= 0)
438                         break;
439
440                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
441                         Sys_Error ("Error reading console input");
442
443                 if (numread != 1)
444                         Sys_Error ("Couldn't read console input");
445
446                 if (recs[0].EventType == KEY_EVENT)
447                 {
448                         if (!recs[0].Event.KeyEvent.bKeyDown)
449                         {
450                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
451
452                                 switch (ch)
453                                 {
454                                         case '\r':
455                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);    
456
457                                                 if (len)
458                                                 {
459                                                         text[len] = 0;
460                                                         len = 0;
461                                                         return text;
462                                                 }
463                                                 else if (sc_return_on_enter)
464                                                 {
465                                                 // special case to allow exiting from the error handler on Enter
466                                                         text[0] = '\r';
467                                                         len = 0;
468                                                         return text;
469                                                 }
470
471                                                 break;
472
473                                         case '\b':
474                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);   
475                                                 if (len)
476                                                 {
477                                                         len--;
478                                                 }
479                                                 break;
480
481                                         default:
482                                                 if (ch >= ' ')
483                                                 {
484                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);       
485                                                         text[len] = ch;
486                                                         len = (len + 1) & 0xff;
487                                                 }
488
489                                                 break;
490
491                                 }
492                         }
493                 }
494         }
495
496         return NULL;
497 }
498
499 void Sys_Sleep (void)
500 {
501         Sleep (1);
502 }
503
504
505 void Sys_SendKeyEvents (void)
506 {
507     MSG        msg;
508
509         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
510         {
511         // we always update if there are any event, even if we're paused
512                 scr_skipupdate = 0;
513
514                 if (!GetMessage (&msg, NULL, 0, 0))
515                         Sys_Quit ();
516
517         TranslateMessage (&msg);
518         DispatchMessage (&msg);
519         }
520 }
521
522
523 /*
524 ==============================================================================
525
526  WINDOWS CRAP
527
528 ==============================================================================
529 */
530
531
532 /*
533 ==================
534 WinMain
535 ==================
536 */
537 void SleepUntilInput (int time)
538 {
539
540         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
541 }
542
543
544 /*
545 ==================
546 WinMain
547 ==================
548 */
549 HINSTANCE       global_hInstance;
550 int                     global_nCmdShow;
551 char            *argv[MAX_NUM_ARGVS];
552 static char     *empty_string = "";
553
554 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
555 {
556         double                  time, oldtime, newtime/*, timediff*/;
557         MEMORYSTATUS    lpBuffer;
558         static  char    cwd[1024];
559         int                             t;
560
561     /* previous instances do not exist in Win32 */
562     if (hPrevInstance)
563         return 0;
564
565         global_hInstance = hInstance;
566         global_nCmdShow = nCmdShow;
567
568         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
569         GlobalMemoryStatus (&lpBuffer);
570
571         if (!GetCurrentDirectory (sizeof(cwd), cwd))
572                 Sys_Error ("Couldn't determine current directory");
573
574         if (cwd[strlen(cwd)-1] == '/')
575                 cwd[strlen(cwd)-1] = 0;
576
577         memset(&host_parms, 0, sizeof(host_parms));
578
579         host_parms.basedir = cwd;
580
581         host_parms.argc = 1;
582         argv[0] = empty_string;
583
584         while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS))
585         {
586                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
587                         lpCmdLine++;
588
589                 if (*lpCmdLine)
590                 {
591                         argv[host_parms.argc] = lpCmdLine;
592                         host_parms.argc++;
593
594                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
595                                 lpCmdLine++;
596
597                         if (*lpCmdLine)
598                         {
599                                 *lpCmdLine = 0;
600                                 lpCmdLine++;
601                         }
602                         
603                 }
604         }
605
606         host_parms.argv = argv;
607
608         COM_InitArgv (host_parms.argc, host_parms.argv);
609
610         host_parms.argc = com_argc;
611         host_parms.argv = com_argv;
612
613         isDedicated = (COM_CheckParm ("-dedicated") != 0);
614
615 // take the greater of all the available memory or half the total memory,
616 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
617 // request otherwise
618         /*
619         host_parms.memsize = lpBuffer.dwAvailPhys;
620
621         if (host_parms.memsize < MINIMUM_WIN_MEMORY)
622                 host_parms.memsize = MINIMUM_WIN_MEMORY;
623
624         if (host_parms.memsize < (lpBuffer.dwTotalPhys >> 1))
625                 host_parms.memsize = lpBuffer.dwTotalPhys >> 1;
626
627         if (host_parms.memsize > MAXIMUM_WIN_MEMORY)
628                 host_parms.memsize = MAXIMUM_WIN_MEMORY;
629         */
630
631 //      Sys_PageIn (parms.membase, parms.memsize);
632
633         tevent = CreateEvent(NULL, false, false, NULL);
634
635         if (!tevent)
636                 Sys_Error ("Couldn't create event");
637
638         if (isDedicated)
639         {
640                 if (!AllocConsole ())
641                 {
642                         Sys_Error ("Couldn't create dedicated server console");
643                 }
644
645                 hinput = GetStdHandle (STD_INPUT_HANDLE);
646                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
647
648         // give QHOST a chance to hook into the console
649                 if ((t = COM_CheckParm ("-HFILE")) > 0)
650                 {
651                         if (t < com_argc)
652                                 hFile = (HANDLE)atoi (com_argv[t+1]);
653                 }
654                         
655                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
656                 {
657                         if (t < com_argc)
658                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
659                 }
660                         
661                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
662                 {
663                         if (t < com_argc)
664                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
665                 }
666
667                 InitConProc (hFile, heventParent, heventChild);
668         }
669
670 // because sound is off until we become active
671         S_BlockSound ();
672
673 #if WIN32_USETIMEGETTIME
674         // make sure the timer is high precision, otherwise NT gets 18ms resolution
675         // LordHavoc:
676         // Windows 2000 Advanced Server (and possibly other versions)
677         // apparently have a broken timer, because it runs at more like 10x speed
678         // if this isn't used, heh
679         timeBeginPeriod (1);
680 #endif
681
682         Sys_Printf ("Host_Init\n");
683         Host_Init ();
684
685         oldtime = Sys_DoubleTime ();
686
687     /* main window message loop */
688         while (1)
689         {
690                 if (!isDedicated)
691                 {
692                 // yield the CPU for a little while when paused, minimized, or not the focus
693                         if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
694                         {
695                                 SleepUntilInput (PAUSE_SLEEP);
696                                 scr_skipupdate = 1;             // no point in bothering to draw
697                         }
698                         else if (!ActiveApp && !DDActive)
699                         {
700                                 SleepUntilInput (NOT_FOCUS_SLEEP);
701                         }
702
703                         newtime = Sys_DoubleTime ();
704                         time = newtime - oldtime;
705                 }
706
707                 Host_Frame (time);
708                 oldtime = newtime;
709         }
710
711     /* return success of application */
712     return true;
713 }
714