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