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