]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - sys_win.c
Borland C++ compile fix - works/compiles now.
[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 #include "quakedef.h"
23 #include "winquake.h"
24 #include "errno.h"
25 #include "resource.h"
26 #include "conproc.h"
27 #include "direct.h"
28
29 // LordHavoc: raised min to 64mb (was 8.5mb)
30 #define MINIMUM_WIN_MEMORY              0x04000000
31 // LordHavoc: raised max to 64mb (was 16mb)
32 #define MAXIMUM_WIN_MEMORY              0x04000000
33
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
38
39 int                     starttime;
40 qboolean        ActiveApp, Minimized;
41 qboolean        WinNT;
42
43 static double           pfreq;
44 static double           curtime = 0.0;
45 static double           lastcurtime = 0.0;
46 static int                      lowshift;
47 qboolean                        isDedicated;
48 static qboolean         sc_return_on_enter = false;
49 HANDLE                          hinput, houtput;
50
51 static char                     *tracking_tag = "Clams & Mooses";
52
53 static HANDLE   tevent;
54 static HANDLE   hFile;
55 static HANDLE   heventParent;
56 static HANDLE   heventChild;
57
58 void Sys_InitFloatTime (void);
59
60 volatile int                                    sys_checksum;
61
62
63 /*
64 ================
65 Sys_PageIn
66 ================
67 */
68 void Sys_PageIn (void *ptr, int size)
69 {
70         byte    *x;
71         int             m, n;
72
73 // touch all the memory to make sure it's there. The 16-page skip is to
74 // keep Win 95 from thinking we're trying to page ourselves in (we are
75 // doing that, of course, but there's no reason we shouldn't)
76         x = (byte *)ptr;
77
78         for (n=0 ; n<4 ; n++)
79         {
80                 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
81                 {
82                         sys_checksum += *(int *)&x[m];
83                         sys_checksum += *(int *)&x[m + 16 * 0x1000];
84                 }
85         }
86 }
87
88
89 /*
90 ===============================================================================
91
92 FILE IO
93
94 ===============================================================================
95 */
96
97 // LordHavoc: 256 pak files (was 10)
98 #define MAX_HANDLES             256
99 FILE    *sys_handles[MAX_HANDLES];
100
101 int             findhandle (void)
102 {
103         int             i;
104         
105         for (i=1 ; i<MAX_HANDLES ; i++)
106                 if (!sys_handles[i])
107                         return i;
108         Sys_Error ("out of handles");
109         return -1;
110 }
111
112 /*
113 ================
114 filelength
115 ================
116 */
117 int filelength (FILE *f)
118 {
119         int             pos;
120         int             end;
121
122         pos = ftell (f);
123         fseek (f, 0, SEEK_END);
124         end = ftell (f);
125         fseek (f, pos, SEEK_SET);
126
127         return end;
128 }
129
130 int Sys_FileOpenRead (char *path, int *hndl)
131 {
132         FILE    *f;
133         int             i, retval;
134
135         i = findhandle ();
136
137         f = fopen(path, "rb");
138
139         if (!f)
140         {
141                 *hndl = -1;
142                 retval = -1;
143         }
144         else
145         {
146                 sys_handles[i] = f;
147                 *hndl = i;
148                 retval = filelength(f);
149         }
150
151         return retval;
152 }
153
154 int Sys_FileOpenWrite (char *path)
155 {
156         FILE    *f;
157         int             i;
158
159         i = findhandle ();
160
161         f = fopen(path, "wb");
162         if (!f)
163                 Host_Error ("Error opening %s: %s", path,strerror(errno));
164         sys_handles[i] = f;
165         
166         return i;
167 }
168
169 void Sys_FileClose (int handle)
170 {
171         fclose (sys_handles[handle]);
172         sys_handles[handle] = NULL;
173 }
174
175 void Sys_FileSeek (int handle, int position)
176 {
177         fseek (sys_handles[handle], position, SEEK_SET);
178 }
179
180 int Sys_FileRead (int handle, void *dest, int count)
181 {
182         return fread (dest, 1, count, sys_handles[handle]);
183 }
184
185 int Sys_FileWrite (int handle, void *data, int count)
186 {
187         return fwrite (data, 1, count, sys_handles[handle]);
188 }
189
190 int     Sys_FileTime (char *path)
191 {
192         FILE    *f;
193         int             retval;
194
195         f = fopen(path, "rb");
196
197         if (f)
198         {
199                 fclose(f);
200                 retval = 1;
201         }
202         else
203         {
204                 retval = -1;
205         }
206         
207         return retval;
208 }
209
210 void Sys_mkdir (char *path)
211 {
212         _mkdir (path);
213 }
214
215
216 /*
217 ===============================================================================
218
219 SYSTEM IO
220
221 ===============================================================================
222 */
223
224 /*
225 ================
226 Sys_MakeCodeWriteable
227 ================
228 */
229 void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
230 {
231         DWORD  flOldProtect;
232
233         if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect))
234                 Sys_Error("Protection change failed\n");
235 }
236
237
238 /*
239 ================
240 Sys_Init
241 ================
242 */
243 void Sys_Init (void)
244 {
245         LARGE_INTEGER   PerformanceFreq;
246         unsigned int    lowpart, highpart;
247         OSVERSIONINFO   vinfo;
248
249         if (!QueryPerformanceFrequency (&PerformanceFreq))
250                 Sys_Error ("No hardware timer available");
251
252 // get 32 out of the 64 time bits such that we have around
253 // 1 microsecond resolution
254 #ifdef __BORLANDC__
255         lowpart = (unsigned int)PerformanceFreq.u.LowPart;
256         highpart = (unsigned int)PerformanceFreq.u.HighPart;
257 #else
258         lowpart = (unsigned int)PerformanceFreq.LowPart;
259         highpart = (unsigned int)PerformanceFreq.HighPart;
260 #endif  
261         lowshift = 0;
262
263         while (highpart || (lowpart > 2000000.0))
264         {
265                 lowshift++;
266                 lowpart >>= 1;
267                 lowpart |= (highpart & 1) << 31;
268                 highpart >>= 1;
269         }
270
271         pfreq = 1.0 / (double)lowpart;
272
273         Sys_InitFloatTime ();
274
275         vinfo.dwOSVersionInfoSize = sizeof(vinfo);
276
277         if (!GetVersionEx (&vinfo))
278                 Sys_Error ("Couldn't get OS info");
279
280         if ((vinfo.dwMajorVersion < 4) ||
281                 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
282         {
283                 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
284         }
285
286         if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
287                 WinNT = true;
288         else
289                 WinNT = false;
290 }
291
292
293 void Sys_Error (char *error, ...)
294 {
295         va_list         argptr;
296         char            text[1024], text2[1024];
297         char            *text3 = "Press Enter to exit\n";
298         char            *text4 = "***********************************\n";
299         char            *text5 = "\n";
300         DWORD           dummy;
301         double          starttime;
302         static int      in_sys_error0 = 0;
303         static int      in_sys_error1 = 0;
304         static int      in_sys_error2 = 0;
305         static int      in_sys_error3 = 0;
306
307         if (!in_sys_error3)
308                 in_sys_error3 = 1;
309
310         va_start (argptr, error);
311         vsprintf (text, error, argptr);
312         va_end (argptr);
313
314         if (isDedicated)
315         {
316                 va_start (argptr, error);
317                 vsprintf (text, error, argptr);
318                 va_end (argptr);
319
320                 sprintf (text2, "ERROR: %s\n", text);
321                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
322                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
323                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
324                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
325                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
326
327
328                 starttime = Sys_FloatTime ();
329                 sc_return_on_enter = true;      // so Enter will get us out of here
330
331                 while (!Sys_ConsoleInput () &&
332                                 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
333                 {
334                 }
335         }
336         else
337         {
338         // switch to windowed so the message box is visible, unless we already
339         // tried that and failed
340                 if (!in_sys_error0)
341                 {
342                         in_sys_error0 = 1;
343                         VID_SetDefaultMode ();
344                         MessageBox(NULL, text, "Quake Error",
345                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
346                 }
347                 else
348                 {
349                         MessageBox(NULL, text, "Double Quake Error",
350                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
351                 }
352         }
353
354         if (!in_sys_error1)
355         {
356                 in_sys_error1 = 1;
357                 Host_Shutdown ();
358         }
359
360 // shut down QHOST hooks if necessary
361         if (!in_sys_error2)
362         {
363                 in_sys_error2 = 1;
364                 DeinitConProc ();
365         }
366
367         exit (1);
368 }
369
370 void Sys_Printf (char *fmt, ...)
371 {
372         va_list         argptr;
373         char            text[1024];
374         DWORD           dummy;
375         
376         if (isDedicated)
377         {
378                 va_start (argptr,fmt);
379                 vsprintf (text, fmt, argptr);
380                 va_end (argptr);
381
382                 WriteFile(houtput, text, strlen (text), &dummy, NULL);  
383         }
384 }
385
386 void Sys_Quit (void)
387 {
388
389         Host_Shutdown();
390
391         if (tevent)
392                 CloseHandle (tevent);
393
394         if (isDedicated)
395                 FreeConsole ();
396
397 // shut down QHOST hooks if necessary
398         DeinitConProc ();
399
400         exit (0);
401 }
402
403
404 /*
405 ================
406 Sys_FloatTime
407 ================
408 */
409 double Sys_FloatTime (void)
410 {
411         static int                      sametimecount;
412         static unsigned int     oldtime;
413         static int                      first = 1;
414         LARGE_INTEGER           PerformanceCount;
415         unsigned int            temp, t2;
416         double                          time;
417
418         QueryPerformanceCounter (&PerformanceCount);
419
420 #ifdef __BORLANDC__
421         temp = ((unsigned int)PerformanceCount.u.LowPart >> lowshift) |
422             ((unsigned int)PerformanceCount.u.HighPart << (32 - lowshift));
423 #else
424
425         temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
426                    ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
427 #endif
428         if (first)
429         {
430                 oldtime = temp;
431                 first = 0;
432         }
433         else
434         {
435         // check for turnover or backward time
436                 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
437                 {
438                         oldtime = temp; // so we can't get stuck
439                 }
440                 else
441                 {
442                         t2 = temp - oldtime;
443
444                         time = (double)t2 * pfreq;
445                         oldtime = temp;
446
447                         curtime += time;
448
449                         if (curtime == lastcurtime)
450                         {
451                                 sametimecount++;
452
453                                 if (sametimecount > 100000)
454                                 {
455                                         curtime += 1.0;
456                                         sametimecount = 0;
457                                 }
458                         }
459                         else
460                         {
461                                 sametimecount = 0;
462                         }
463
464                         lastcurtime = curtime;
465                 }
466         }
467
468     return curtime;
469 }
470
471
472 /*
473 ================
474 Sys_InitFloatTime
475 ================
476 */
477 void Sys_InitFloatTime (void)
478 {
479         int             j;
480
481         Sys_FloatTime ();
482
483         j = COM_CheckParm("-starttime");
484
485         if (j)
486         {
487                 curtime = (double) (atof(com_argv[j+1]));
488         }
489         else
490         {
491                 curtime = 0.0;
492         }
493
494         lastcurtime = curtime;
495 }
496
497
498 char *Sys_ConsoleInput (void)
499 {
500         static char     text[256];
501         static int              len;
502         INPUT_RECORD    recs[1024];
503         int             dummy;
504         int             ch, numread, numevents;
505
506         if (!isDedicated)
507                 return NULL;
508
509
510         for ( ;; )
511         {
512                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
513                         Sys_Error ("Error getting # of console events");
514
515                 if (numevents <= 0)
516                         break;
517
518                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
519                         Sys_Error ("Error reading console input");
520
521                 if (numread != 1)
522                         Sys_Error ("Couldn't read console input");
523
524                 if (recs[0].EventType == KEY_EVENT)
525                 {
526                         if (!recs[0].Event.KeyEvent.bKeyDown)
527                         {
528                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
529
530                                 switch (ch)
531                                 {
532                                         case '\r':
533                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);    
534
535                                                 if (len)
536                                                 {
537                                                         text[len] = 0;
538                                                         len = 0;
539                                                         return text;
540                                                 }
541                                                 else if (sc_return_on_enter)
542                                                 {
543                                                 // special case to allow exiting from the error handler on Enter
544                                                         text[0] = '\r';
545                                                         len = 0;
546                                                         return text;
547                                                 }
548
549                                                 break;
550
551                                         case '\b':
552                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);   
553                                                 if (len)
554                                                 {
555                                                         len--;
556                                                 }
557                                                 break;
558
559                                         default:
560                                                 if (ch >= ' ')
561                                                 {
562                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);       
563                                                         text[len] = ch;
564                                                         len = (len + 1) & 0xff;
565                                                 }
566
567                                                 break;
568
569                                 }
570                         }
571                 }
572         }
573
574         return NULL;
575 }
576
577 void Sys_Sleep (void)
578 {
579         Sleep (1);
580 }
581
582
583 void Sys_SendKeyEvents (void)
584 {
585     MSG        msg;
586
587         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
588         {
589         // we always update if there are any event, even if we're paused
590                 scr_skipupdate = 0;
591
592                 if (!GetMessage (&msg, NULL, 0, 0))
593                         Sys_Quit ();
594
595         TranslateMessage (&msg);
596         DispatchMessage (&msg);
597         }
598 }
599
600
601 /*
602 ==============================================================================
603
604  WINDOWS CRAP
605
606 ==============================================================================
607 */
608
609
610 /*
611 ==================
612 WinMain
613 ==================
614 */
615 void SleepUntilInput (int time)
616 {
617
618         MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT);
619 }
620
621
622 /*
623 ==================
624 WinMain
625 ==================
626 */
627 HINSTANCE       global_hInstance;
628 int                     global_nCmdShow;
629 char            *argv[MAX_NUM_ARGVS];
630 static char     *empty_string = "";
631 HWND            hwnd_dialog;
632
633
634 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
635 {
636         quakeparms_t    parms;
637         double                  time, oldtime, newtime/*, timediff*/;
638         MEMORYSTATUS    lpBuffer;
639         static  char    cwd[1024];
640         int                             t;
641         RECT                    rect;
642
643     /* previous instances do not exist in Win32 */
644     if (hPrevInstance)
645         return 0;
646
647         global_hInstance = hInstance;
648         global_nCmdShow = nCmdShow;
649
650         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
651         GlobalMemoryStatus (&lpBuffer);
652
653         if (!GetCurrentDirectory (sizeof(cwd), cwd))
654                 Sys_Error ("Couldn't determine current directory");
655
656         if (cwd[strlen(cwd)-1] == '/')
657                 cwd[strlen(cwd)-1] = 0;
658
659         parms.basedir = cwd;
660         parms.cachedir = NULL;
661
662         parms.argc = 1;
663         argv[0] = empty_string;
664
665         while (*lpCmdLine && (parms.argc < MAX_NUM_ARGVS))
666         {
667                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
668                         lpCmdLine++;
669
670                 if (*lpCmdLine)
671                 {
672                         argv[parms.argc] = lpCmdLine;
673                         parms.argc++;
674
675                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
676                                 lpCmdLine++;
677
678                         if (*lpCmdLine)
679                         {
680                                 *lpCmdLine = 0;
681                                 lpCmdLine++;
682                         }
683                         
684                 }
685         }
686
687         parms.argv = argv;
688
689         COM_InitArgv (parms.argc, parms.argv);
690
691         parms.argc = com_argc;
692         parms.argv = com_argv;
693
694         isDedicated = (COM_CheckParm ("-dedicated") != 0);
695
696         if (!isDedicated)
697         {
698                 hwnd_dialog = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
699
700                 if (hwnd_dialog)
701                 {
702                         if (GetWindowRect (hwnd_dialog, &rect))
703                         {
704                                 if (rect.left > (rect.top * 2))
705                                 {
706                                         SetWindowPos (hwnd_dialog, 0,
707                                                 (rect.left / 2) - ((rect.right - rect.left) / 2),
708                                                 rect.top, 0, 0,
709                                                 SWP_NOZORDER | SWP_NOSIZE);
710                                 }
711                         }
712
713                         ShowWindow (hwnd_dialog, SW_SHOWDEFAULT);
714                         UpdateWindow (hwnd_dialog);
715                         SetForegroundWindow (hwnd_dialog);
716                 }
717         }
718
719 // take the greater of all the available memory or half the total memory,
720 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
721 // request otherwise
722         parms.memsize = lpBuffer.dwAvailPhys;
723
724         if (parms.memsize < MINIMUM_WIN_MEMORY)
725                 parms.memsize = MINIMUM_WIN_MEMORY;
726
727         if (parms.memsize < (lpBuffer.dwTotalPhys >> 1))
728                 parms.memsize = lpBuffer.dwTotalPhys >> 1;
729
730         if (parms.memsize > MAXIMUM_WIN_MEMORY)
731                 parms.memsize = MAXIMUM_WIN_MEMORY;
732
733         if (COM_CheckParm ("-heapsize"))
734         {
735                 t = COM_CheckParm("-heapsize") + 1;
736
737                 if (t < com_argc)
738                         parms.memsize = atoi (com_argv[t]) * 1024;
739         }
740
741         if (COM_CheckParm ("-mem"))
742         {
743                 t = COM_CheckParm("-mem") + 1;
744
745                 if (t < com_argc)
746                         parms.memsize = atoi (com_argv[t]) * 1048576;
747         }
748
749         if (COM_CheckParm ("-winmem"))
750         {
751                 t = COM_CheckParm("-winmem") + 1;
752
753                 if (t < com_argc)
754                         parms.memsize = atoi (com_argv[t]) * 1048576;
755         }
756
757         parms.membase = malloc (parms.memsize);
758
759         if (!parms.membase)
760                 Sys_Error ("Not enough memory free; check disk space\n");
761
762 //      Sys_PageIn (parms.membase, parms.memsize);
763
764         tevent = CreateEvent(NULL, FALSE, FALSE, NULL);
765
766         if (!tevent)
767                 Sys_Error ("Couldn't create event");
768
769         if (isDedicated)
770         {
771                 if (!AllocConsole ())
772                 {
773                         Sys_Error ("Couldn't create dedicated server console");
774                 }
775
776                 hinput = GetStdHandle (STD_INPUT_HANDLE);
777                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
778
779         // give QHOST a chance to hook into the console
780                 if ((t = COM_CheckParm ("-HFILE")) > 0)
781                 {
782                         if (t < com_argc)
783                                 hFile = (HANDLE)atoi (com_argv[t+1]);
784                 }
785                         
786                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
787                 {
788                         if (t < com_argc)
789                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
790                 }
791                         
792                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
793                 {
794                         if (t < com_argc)
795                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
796                 }
797
798                 InitConProc (hFile, heventParent, heventChild);
799         }
800
801         Sys_Init ();
802
803 // because sound is off until we become active
804         S_BlockSound ();
805
806         Sys_Printf ("Host_Init\n");
807         Host_Init (&parms);
808
809         oldtime = Sys_FloatTime ();
810
811     /* main window message loop */
812         while (1)
813         {
814                 if (isDedicated)
815                 {
816                         newtime = Sys_FloatTime ();
817                         time = newtime - oldtime;
818
819                         while (time < sys_ticrate.value )
820                         {
821                                 Sys_Sleep();
822                                 newtime = Sys_FloatTime ();
823                                 time = newtime - oldtime;
824                         }
825                 }
826                 else
827                 {
828                 // yield the CPU for a little while when paused, minimized, or not the focus
829                         if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
830                         {
831                                 SleepUntilInput (PAUSE_SLEEP);
832                                 scr_skipupdate = 1;             // no point in bothering to draw
833                         }
834                         else if (!ActiveApp && !DDActive)
835                         {
836                                 SleepUntilInput (NOT_FOCUS_SLEEP);
837                         }
838                         /*
839                         else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
840                         {
841                                 newtime = Sys_FloatTime ();
842                                 time = newtime - oldtime;
843
844                                 while (time < timediff)
845                                 {
846                                         Sys_Sleep();
847                                         newtime = Sys_FloatTime ();
848                                         time = newtime - oldtime;
849                                 }
850                         }
851                         */
852
853                         newtime = Sys_FloatTime ();
854                         time = newtime - oldtime;
855                 }
856
857                 Host_Frame (time);
858                 oldtime = newtime;
859         }
860
861     /* return success of application */
862     return TRUE;
863 }
864