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