]> icculus.org git repositories - divverent/darkplaces.git/blob - sys_win.c
upped pack file count limit to 16384 from 2048
[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 #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 24mb (was 8.5mb)
30 #define MINIMUM_WIN_MEMORY              0x1800000
31 // LordHavoc: raised max to 24mb (was 16mb)
32 #define MAXIMUM_WIN_MEMORY              0x1800000
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         lowpart = (unsigned int)PerformanceFreq.LowPart;
255         highpart = (unsigned int)PerformanceFreq.HighPart;
256         lowshift = 0;
257
258         while (highpart || (lowpart > 2000000.0))
259         {
260                 lowshift++;
261                 lowpart >>= 1;
262                 lowpart |= (highpart & 1) << 31;
263                 highpart >>= 1;
264         }
265
266         pfreq = 1.0 / (double)lowpart;
267
268         Sys_InitFloatTime ();
269
270         vinfo.dwOSVersionInfoSize = sizeof(vinfo);
271
272         if (!GetVersionEx (&vinfo))
273                 Sys_Error ("Couldn't get OS info");
274
275         if ((vinfo.dwMajorVersion < 4) ||
276                 (vinfo.dwPlatformId == VER_PLATFORM_WIN32s))
277         {
278                 Sys_Error ("WinQuake requires at least Win95 or NT 4.0");
279         }
280
281         if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
282                 WinNT = true;
283         else
284                 WinNT = false;
285 }
286
287
288 void Sys_Error (char *error, ...)
289 {
290         va_list         argptr;
291         char            text[1024], text2[1024];
292         char            *text3 = "Press Enter to exit\n";
293         char            *text4 = "***********************************\n";
294         char            *text5 = "\n";
295         DWORD           dummy;
296         double          starttime;
297         static int      in_sys_error0 = 0;
298         static int      in_sys_error1 = 0;
299         static int      in_sys_error2 = 0;
300         static int      in_sys_error3 = 0;
301
302         if (!in_sys_error3)
303                 in_sys_error3 = 1;
304
305         va_start (argptr, error);
306         vsprintf (text, error, argptr);
307         va_end (argptr);
308
309         if (isDedicated)
310         {
311                 va_start (argptr, error);
312                 vsprintf (text, error, argptr);
313                 va_end (argptr);
314
315                 sprintf (text2, "ERROR: %s\n", text);
316                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
317                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
318                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
319                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
320                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
321
322
323                 starttime = Sys_FloatTime ();
324                 sc_return_on_enter = true;      // so Enter will get us out of here
325
326                 while (!Sys_ConsoleInput () &&
327                                 ((Sys_FloatTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
328                 {
329                 }
330         }
331         else
332         {
333         // switch to windowed so the message box is visible, unless we already
334         // tried that and failed
335                 if (!in_sys_error0)
336                 {
337                         in_sys_error0 = 1;
338                         VID_SetDefaultMode ();
339                         MessageBox(NULL, text, "Quake Error",
340                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
341                 }
342                 else
343                 {
344                         MessageBox(NULL, text, "Double Quake Error",
345                                            MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
346                 }
347         }
348
349         if (!in_sys_error1)
350         {
351                 in_sys_error1 = 1;
352                 Host_Shutdown ();
353         }
354
355 // shut down QHOST hooks if necessary
356         if (!in_sys_error2)
357         {
358                 in_sys_error2 = 1;
359                 DeinitConProc ();
360         }
361
362         exit (1);
363 }
364
365 void Sys_Printf (char *fmt, ...)
366 {
367         va_list         argptr;
368         char            text[1024];
369         DWORD           dummy;
370         
371         if (isDedicated)
372         {
373                 va_start (argptr,fmt);
374                 vsprintf (text, fmt, argptr);
375                 va_end (argptr);
376
377                 WriteFile(houtput, text, strlen (text), &dummy, NULL);  
378         }
379 }
380
381 void Sys_Quit (void)
382 {
383
384         Host_Shutdown();
385
386         if (tevent)
387                 CloseHandle (tevent);
388
389         if (isDedicated)
390                 FreeConsole ();
391
392 // shut down QHOST hooks if necessary
393         DeinitConProc ();
394
395         exit (0);
396 }
397
398
399 /*
400 ================
401 Sys_FloatTime
402 ================
403 */
404 double Sys_FloatTime (void)
405 {
406         static int                      sametimecount;
407         static unsigned int     oldtime;
408         static int                      first = 1;
409         LARGE_INTEGER           PerformanceCount;
410         unsigned int            temp, t2;
411         double                          time;
412
413         QueryPerformanceCounter (&PerformanceCount);
414
415         temp = ((unsigned int)PerformanceCount.LowPart >> lowshift) |
416                    ((unsigned int)PerformanceCount.HighPart << (32 - lowshift));
417
418         if (first)
419         {
420                 oldtime = temp;
421                 first = 0;
422         }
423         else
424         {
425         // check for turnover or backward time
426                 if ((temp <= oldtime) && ((oldtime - temp) < 0x10000000))
427                 {
428                         oldtime = temp; // so we can't get stuck
429                 }
430                 else
431                 {
432                         t2 = temp - oldtime;
433
434                         time = (double)t2 * pfreq;
435                         oldtime = temp;
436
437                         curtime += time;
438
439                         if (curtime == lastcurtime)
440                         {
441                                 sametimecount++;
442
443                                 if (sametimecount > 100000)
444                                 {
445                                         curtime += 1.0;
446                                         sametimecount = 0;
447                                 }
448                         }
449                         else
450                         {
451                                 sametimecount = 0;
452                         }
453
454                         lastcurtime = curtime;
455                 }
456         }
457
458     return curtime;
459 }
460
461
462 /*
463 ================
464 Sys_InitFloatTime
465 ================
466 */
467 void Sys_InitFloatTime (void)
468 {
469         int             j;
470
471         Sys_FloatTime ();
472
473         j = COM_CheckParm("-starttime");
474
475         if (j)
476         {
477                 curtime = (double) (atof(com_argv[j+1]));
478         }
479         else
480         {
481                 curtime = 0.0;
482         }
483
484         lastcurtime = curtime;
485 }
486
487
488 char *Sys_ConsoleInput (void)
489 {
490         static char     text[256];
491         static int              len;
492         INPUT_RECORD    recs[1024];
493         int             dummy;
494         int             ch, numread, numevents;
495
496         if (!isDedicated)
497                 return NULL;
498
499
500         for ( ;; )
501         {
502                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
503                         Sys_Error ("Error getting # of console events");
504
505                 if (numevents <= 0)
506                         break;
507
508                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
509                         Sys_Error ("Error reading console input");
510
511                 if (numread != 1)
512                         Sys_Error ("Couldn't read console input");
513
514                 if (recs[0].EventType == KEY_EVENT)
515                 {
516                         if (!recs[0].Event.KeyEvent.bKeyDown)
517                         {
518                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
519
520                                 switch (ch)
521                                 {
522                                         case '\r':
523                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);    
524
525                                                 if (len)
526                                                 {
527                                                         text[len] = 0;
528                                                         len = 0;
529                                                         return text;
530                                                 }
531                                                 else if (sc_return_on_enter)
532                                                 {
533                                                 // special case to allow exiting from the error handler on Enter
534                                                         text[0] = '\r';
535                                                         len = 0;
536                                                         return text;
537                                                 }
538
539                                                 break;
540
541                                         case '\b':
542                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);   
543                                                 if (len)
544                                                 {
545                                                         len--;
546                                                 }
547                                                 break;
548
549                                         default:
550                                                 if (ch >= ' ')
551                                                 {
552                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);       
553                                                         text[len] = ch;
554                                                         len = (len + 1) & 0xff;
555                                                 }
556
557                                                 break;
558
559                                 }
560                         }
561                 }
562         }
563
564         return NULL;
565 }
566
567 void Sys_Sleep (void)
568 {
569         Sleep (1);
570 }
571
572
573 void Sys_SendKeyEvents (void)
574 {
575     MSG        msg;
576
577         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
578         {
579         // we always update if there are any event, even if we're paused
580                 scr_skipupdate = 0;
581
582                 if (!GetMessage (&msg, NULL, 0, 0))
583                         Sys_Quit ();
584
585         TranslateMessage (&msg);
586         DispatchMessage (&msg);
587         }
588 }
589
590
591 /*
592 ==============================================================================
593
594  WINDOWS CRAP
595
596 ==============================================================================
597 */
598
599
600 /*
601 ==================
602 WinMain
603 ==================
604 */
605 void SleepUntilInput (int time)
606 {
607
608         MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT);
609 }
610
611
612 /*
613 ==================
614 WinMain
615 ==================
616 */
617 HINSTANCE       global_hInstance;
618 int                     global_nCmdShow;
619 char            *argv[MAX_NUM_ARGVS];
620 static char     *empty_string = "";
621 HWND            hwnd_dialog;
622
623
624 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
625 {
626         quakeparms_t    parms;
627         double                  time, oldtime, newtime/*, timediff*/;
628         MEMORYSTATUS    lpBuffer;
629         static  char    cwd[1024];
630         int                             t;
631         RECT                    rect;
632
633     /* previous instances do not exist in Win32 */
634     if (hPrevInstance)
635         return 0;
636
637         global_hInstance = hInstance;
638         global_nCmdShow = nCmdShow;
639
640         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
641         GlobalMemoryStatus (&lpBuffer);
642
643         if (!GetCurrentDirectory (sizeof(cwd), cwd))
644                 Sys_Error ("Couldn't determine current directory");
645
646         if (cwd[strlen(cwd)-1] == '/')
647                 cwd[strlen(cwd)-1] = 0;
648
649         parms.basedir = cwd;
650         parms.cachedir = NULL;
651
652         parms.argc = 1;
653         argv[0] = empty_string;
654
655         while (*lpCmdLine && (parms.argc < MAX_NUM_ARGVS))
656         {
657                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
658                         lpCmdLine++;
659
660                 if (*lpCmdLine)
661                 {
662                         argv[parms.argc] = lpCmdLine;
663                         parms.argc++;
664
665                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
666                                 lpCmdLine++;
667
668                         if (*lpCmdLine)
669                         {
670                                 *lpCmdLine = 0;
671                                 lpCmdLine++;
672                         }
673                         
674                 }
675         }
676
677         parms.argv = argv;
678
679         COM_InitArgv (parms.argc, parms.argv);
680
681         parms.argc = com_argc;
682         parms.argv = com_argv;
683
684         isDedicated = (COM_CheckParm ("-dedicated") != 0);
685
686         if (!isDedicated)
687         {
688                 hwnd_dialog = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL);
689
690                 if (hwnd_dialog)
691                 {
692                         if (GetWindowRect (hwnd_dialog, &rect))
693                         {
694                                 if (rect.left > (rect.top * 2))
695                                 {
696                                         SetWindowPos (hwnd_dialog, 0,
697                                                 (rect.left / 2) - ((rect.right - rect.left) / 2),
698                                                 rect.top, 0, 0,
699                                                 SWP_NOZORDER | SWP_NOSIZE);
700                                 }
701                         }
702
703                         ShowWindow (hwnd_dialog, SW_SHOWDEFAULT);
704                         UpdateWindow (hwnd_dialog);
705                         SetForegroundWindow (hwnd_dialog);
706                 }
707         }
708
709 // take the greater of all the available memory or half the total memory,
710 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
711 // request otherwise
712         parms.memsize = lpBuffer.dwAvailPhys;
713
714         if (parms.memsize < MINIMUM_WIN_MEMORY)
715                 parms.memsize = MINIMUM_WIN_MEMORY;
716
717         if (parms.memsize < (lpBuffer.dwTotalPhys >> 1))
718                 parms.memsize = lpBuffer.dwTotalPhys >> 1;
719
720         if (parms.memsize > MAXIMUM_WIN_MEMORY)
721                 parms.memsize = MAXIMUM_WIN_MEMORY;
722
723         if (COM_CheckParm ("-heapsize"))
724         {
725                 t = COM_CheckParm("-heapsize") + 1;
726
727                 if (t < com_argc)
728                         parms.memsize = atoi (com_argv[t]) * 1024;
729         }
730
731         if (COM_CheckParm ("-mem"))
732         {
733                 t = COM_CheckParm("-mem") + 1;
734
735                 if (t < com_argc)
736                         parms.memsize = atoi (com_argv[t]) * 1048576;
737         }
738
739         if (COM_CheckParm ("-winmem"))
740         {
741                 t = COM_CheckParm("-winmem") + 1;
742
743                 if (t < com_argc)
744                         parms.memsize = atoi (com_argv[t]) * 1048576;
745         }
746
747         parms.membase = malloc (parms.memsize);
748
749         if (!parms.membase)
750                 Sys_Error ("Not enough memory free; check disk space\n");
751
752         Sys_PageIn (parms.membase, parms.memsize);
753
754         tevent = CreateEvent(NULL, FALSE, FALSE, NULL);
755
756         if (!tevent)
757                 Sys_Error ("Couldn't create event");
758
759         if (isDedicated)
760         {
761                 if (!AllocConsole ())
762                 {
763                         Sys_Error ("Couldn't create dedicated server console");
764                 }
765
766                 hinput = GetStdHandle (STD_INPUT_HANDLE);
767                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
768
769         // give QHOST a chance to hook into the console
770                 if ((t = COM_CheckParm ("-HFILE")) > 0)
771                 {
772                         if (t < com_argc)
773                                 hFile = (HANDLE)atoi (com_argv[t+1]);
774                 }
775                         
776                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
777                 {
778                         if (t < com_argc)
779                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
780                 }
781                         
782                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
783                 {
784                         if (t < com_argc)
785                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
786                 }
787
788                 InitConProc (hFile, heventParent, heventChild);
789         }
790
791         Sys_Init ();
792
793 // because sound is off until we become active
794         S_BlockSound ();
795
796         Sys_Printf ("Host_Init\n");
797         Host_Init (&parms);
798
799         oldtime = Sys_FloatTime ();
800
801     /* main window message loop */
802         while (1)
803         {
804                 if (isDedicated)
805                 {
806                         newtime = Sys_FloatTime ();
807                         time = newtime - oldtime;
808
809                         while (time < sys_ticrate.value )
810                         {
811                                 Sys_Sleep();
812                                 newtime = Sys_FloatTime ();
813                                 time = newtime - oldtime;
814                         }
815                 }
816                 else
817                 {
818                 // yield the CPU for a little while when paused, minimized, or not the focus
819                         if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized)
820                         {
821                                 SleepUntilInput (PAUSE_SLEEP);
822                                 scr_skipupdate = 1;             // no point in bothering to draw
823                         }
824                         else if (!ActiveApp && !DDActive)
825                         {
826                                 SleepUntilInput (NOT_FOCUS_SLEEP);
827                         }
828                         /*
829                         else if (!cls.timedemo && time < (timediff = 1.0 / maxfps.value))
830                         {
831                                 newtime = Sys_FloatTime ();
832                                 time = newtime - oldtime;
833
834                                 while (time < timediff)
835                                 {
836                                         Sys_Sleep();
837                                         newtime = Sys_FloatTime ();
838                                         time = newtime - oldtime;
839                                 }
840                         }
841                         */
842
843                         newtime = Sys_FloatTime ();
844                         time = newtime - oldtime;
845                 }
846
847                 Host_Frame (time);
848                 oldtime = newtime;
849         }
850
851     /* return success of application */
852     return TRUE;
853 }
854