moved Sys_Printf and related code/data to sys_shared.c (new), removed all uses of...
[divverent/darkplaces.git] / sys_win.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sys_win.c -- Win32 system interface code
21
22 #define WIN32_USETIMEGETTIME 0
23
24 #include "quakedef.h"
25 #include "winquake.h"
26 #include "errno.h"
27 #include "resource.h"
28 #include "conproc.h"
29 #include "direct.h"
30
31 #define CONSOLE_ERROR_TIMEOUT   60.0    // # of seconds to wait on Sys_Error running
32                                                                                 //  dedicated before exiting
33 #define PAUSE_SLEEP             50                              // sleep time on pause or minimization
34 #define NOT_FOCUS_SLEEP 20                              // sleep time when not focus
35
36 int                     starttime;
37 qboolean        ActiveApp, Minimized;
38
39 static qboolean         sc_return_on_enter = false;
40 HANDLE                          hinput, houtput;
41
42 static char                     *tracking_tag = "Clams & Mooses";
43
44 static HANDLE   tevent;
45 static HANDLE   hFile;
46 static HANDLE   heventParent;
47 static HANDLE   heventChild;
48
49 volatile int                                    sys_checksum;
50
51
52 /*
53 ================
54 Sys_PageIn
55 ================
56 */
57 /*
58 void Sys_PageIn (void *ptr, int size)
59 {
60         byte    *x;
61         int             m, n;
62
63 // touch all the memory to make sure it's there. The 16-page skip is to
64 // keep Win 95 from thinking we're trying to page ourselves in (we are
65 // doing that, of course, but there's no reason we shouldn't)
66         x = (byte *)ptr;
67
68         for (n=0 ; n<4 ; n++)
69         {
70                 for (m=0 ; m<(size - 16 * 0x1000) ; m += 4)
71                 {
72                         sys_checksum += *(int *)&x[m];
73                         sys_checksum += *(int *)&x[m + 16 * 0x1000];
74                 }
75         }
76 }
77 */
78
79
80 /*
81 ===============================================================================
82
83 QFile IO
84
85 ===============================================================================
86 */
87
88 // LordHavoc: 256 pak files (was 10)
89 #define MAX_HANDLES             256
90 QFile   *sys_handles[MAX_HANDLES];
91
92 int             findhandle (void)
93 {
94         int             i;
95         
96         for (i=1 ; i<MAX_HANDLES ; i++)
97                 if (!sys_handles[i])
98                         return i;
99         Sys_Error ("out of handles");
100         return -1;
101 }
102
103 /*
104 ================
105 filelength
106 ================
107 */
108 int filelength (QFile *f)
109 {
110         int             pos;
111         int             end;
112
113         pos = Qtell (f);
114         Qseek (f, 0, SEEK_END);
115         end = Qtell (f);
116         Qseek (f, pos, SEEK_SET);
117
118         return end;
119 }
120
121 int Sys_FileOpenRead (char *path, int *hndl)
122 {
123         QFile   *f;
124         int             i, retval;
125
126         i = findhandle ();
127
128         f = Qopen(path, "rbz");
129
130         if (!f)
131         {
132                 *hndl = -1;
133                 retval = -1;
134         }
135         else
136         {
137                 sys_handles[i] = f;
138                 *hndl = i;
139                 retval = filelength(f);
140         }
141
142         return retval;
143 }
144
145 int Sys_FileOpenWrite (char *path)
146 {
147         QFile   *f;
148         int             i;
149
150         i = findhandle ();
151
152         f = Qopen(path, "wb");
153         if (!f)
154         {
155                 Con_Printf("Sys_FileOpenWrite: Error opening %s: %s", path, strerror(errno));
156                 return 0;
157         }
158         sys_handles[i] = f;
159         
160         return i;
161 }
162
163 void Sys_FileClose (int handle)
164 {
165         Qclose (sys_handles[handle]);
166         sys_handles[handle] = NULL;
167 }
168
169 void Sys_FileSeek (int handle, int position)
170 {
171         Qseek (sys_handles[handle], position, SEEK_SET);
172 }
173
174 int Sys_FileRead (int handle, void *dest, int count)
175 {
176         return Qread (sys_handles[handle], dest, count);
177 }
178
179 int Sys_FileWrite (int handle, void *data, int count)
180 {
181         return Qwrite (sys_handles[handle], data, count);
182 }
183
184 int     Sys_FileTime (char *path)
185 {
186         QFile   *f;
187         
188         f = Qopen(path, "rb");
189         if (f)
190         {
191                 Qclose(f);
192                 return 1;
193         }
194         
195         return -1;
196 }
197
198 void Sys_mkdir (char *path)
199 {
200         _mkdir (path);
201 }
202
203
204 /*
205 ===============================================================================
206
207 SYSTEM IO
208
209 ===============================================================================
210 */
211
212 void Sys_Error (char *error, ...)
213 {
214         va_list         argptr;
215         char            text[1024], text2[1024];
216         char            *text3 = "Press Enter to exit\n";
217         char            *text4 = "***********************************\n";
218         char            *text5 = "\n";
219         DWORD           dummy;
220         double          starttime;
221         static int      in_sys_error0 = 0;
222         static int      in_sys_error1 = 0;
223         static int      in_sys_error2 = 0;
224         static int      in_sys_error3 = 0;
225
226         if (!in_sys_error3)
227                 in_sys_error3 = 1;
228
229         va_start (argptr, error);
230         vsprintf (text, error, argptr);
231         va_end (argptr);
232
233         if (cls.state == ca_dedicated)
234         {
235                 va_start (argptr, error);
236                 vsprintf (text, error, argptr);
237                 va_end (argptr);
238
239                 sprintf (text2, "ERROR: %s\n", text);
240                 WriteFile (houtput, text5, strlen (text5), &dummy, NULL);
241                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
242                 WriteFile (houtput, text2, strlen (text2), &dummy, NULL);
243                 WriteFile (houtput, text3, strlen (text3), &dummy, NULL);
244                 WriteFile (houtput, text4, strlen (text4), &dummy, NULL);
245
246
247                 starttime = Sys_DoubleTime ();
248                 sc_return_on_enter = true;      // so Enter will get us out of here
249
250                 while (!Sys_ConsoleInput () && ((Sys_DoubleTime () - starttime) < CONSOLE_ERROR_TIMEOUT))
251                 {
252                 }
253         }
254         else
255         {
256         // switch to windowed so the message box is visible, unless we already
257         // tried that and failed
258                 if (!in_sys_error0)
259                 {
260                         in_sys_error0 = 1;
261                         VID_SetDefaultMode ();
262                         MessageBox(NULL, text, "Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
263                 }
264                 else
265                 {
266                         MessageBox(NULL, text, "Double Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
267                 }
268         }
269
270         if (!in_sys_error1)
271         {
272                 in_sys_error1 = 1;
273                 Host_Shutdown ();
274         }
275
276 // shut down QHOST hooks if necessary
277         if (!in_sys_error2)
278         {
279                 in_sys_error2 = 1;
280                 DeinitConProc ();
281         }
282
283         exit (1);
284 }
285
286 void Sys_Quit (void)
287 {
288
289         Host_Shutdown();
290
291         if (tevent)
292                 CloseHandle (tevent);
293
294         if (cls.state == ca_dedicated)
295                 FreeConsole ();
296
297 // shut down QHOST hooks if necessary
298         DeinitConProc ();
299
300         exit (0);
301 }
302
303
304 /*
305 ================
306 Sys_DoubleTime
307 ================
308 */
309 double Sys_DoubleTime (void)
310 {
311         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
312 #if WIN32_USETIMEGETTIME
313         // timeGetTime
314         // platform:
315         // Windows 95/98/ME/NT/2000
316         // features:
317         // reasonable accuracy (millisecond)
318         // issues:
319         // none known
320         static int first = true;
321         static double oldtime = 0.0, basetime = 0.0, old = 0.0;
322         double newtime, now;
323
324         now = (double) timeGetTime () + basetime;
325
326         if (first)
327         {
328                 first = false;
329                 basetime = now;
330                 now = 0;
331         }
332
333         if (now < old)
334         {
335                 // wrapped
336                 basetime += (65536.0 * 65536.0);
337                 now += (65536.0 * 65536.0);
338         }
339         old = now;
340
341         newtime = now / 1000.0;
342
343         if (newtime < oldtime)
344                 Sys_Error("Sys_DoubleTime: time running backwards??\n");
345
346         oldtime = newtime;
347
348         return newtime;
349 #else
350         // QueryPerformanceCounter
351         // platform:
352         // Windows 95/98/ME/NT/2000
353         // features:
354         // very accurate (CPU cycles)
355         // known issues:
356         // does not necessarily match realtime too well (tends to get faster and faster in win98)
357         static int first = true;
358         static double oldtime = 0.0, basetime = 0.0, timescale = 0.0;
359         double newtime;
360         LARGE_INTEGER PerformanceFreq;
361         LARGE_INTEGER PerformanceCount;
362
363         if (first)
364         {
365                 if (!QueryPerformanceFrequency (&PerformanceFreq))
366                         Sys_Error ("No hardware timer available");
367
368 #ifdef __BORLANDC__
369                 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
370 #else
371                 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
372 #endif  
373         }
374
375         QueryPerformanceCounter (&PerformanceCount);
376
377 #ifdef __BORLANDC__
378         newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale - basetime;
379 #else
380         newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale - basetime;
381 #endif  
382
383         if (first)
384         {
385                 first = false;
386                 basetime = newtime;
387                 newtime = 0;
388         }
389
390         if (newtime < oldtime)
391                 Sys_Error("Sys_DoubleTime: time running backwards??\n");
392
393         oldtime = newtime;
394
395         return newtime;
396 #endif
397 }
398
399
400 char *Sys_ConsoleInput (void)
401 {
402         static char     text[256];
403         static int              len;
404         INPUT_RECORD    recs[1024];
405         int             dummy;
406         int             ch, numread, numevents;
407
408         if (cls.state != ca_dedicated)
409                 return NULL;
410
411
412         for ( ;; )
413         {
414                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
415                         Sys_Error ("Error getting # of console events");
416
417                 if (numevents <= 0)
418                         break;
419
420                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
421                         Sys_Error ("Error reading console input");
422
423                 if (numread != 1)
424                         Sys_Error ("Couldn't read console input");
425
426                 if (recs[0].EventType == KEY_EVENT)
427                 {
428                         if (!recs[0].Event.KeyEvent.bKeyDown)
429                         {
430                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
431
432                                 switch (ch)
433                                 {
434                                         case '\r':
435                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);    
436
437                                                 if (len)
438                                                 {
439                                                         text[len] = 0;
440                                                         len = 0;
441                                                         return text;
442                                                 }
443                                                 else if (sc_return_on_enter)
444                                                 {
445                                                 // special case to allow exiting from the error handler on Enter
446                                                         text[0] = '\r';
447                                                         len = 0;
448                                                         return text;
449                                                 }
450
451                                                 break;
452
453                                         case '\b':
454                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);   
455                                                 if (len)
456                                                 {
457                                                         len--;
458                                                 }
459                                                 break;
460
461                                         default:
462                                                 if (ch >= ' ')
463                                                 {
464                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);       
465                                                         text[len] = ch;
466                                                         len = (len + 1) & 0xff;
467                                                 }
468
469                                                 break;
470
471                                 }
472                         }
473                 }
474         }
475
476         return NULL;
477 }
478
479 void Sys_Sleep (void)
480 {
481         Sleep (1);
482 }
483
484
485 void Sys_SendKeyEvents (void)
486 {
487     MSG        msg;
488
489         while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
490         {
491         // we always update if there are any event, even if we're paused
492                 scr_skipupdate = 0;
493
494                 if (!GetMessage (&msg, NULL, 0, 0))
495                         Sys_Quit ();
496
497         TranslateMessage (&msg);
498         DispatchMessage (&msg);
499         }
500 }
501
502
503 /*
504 ==============================================================================
505
506  WINDOWS CRAP
507
508 ==============================================================================
509 */
510
511
512 /*
513 ==================
514 WinMain
515 ==================
516 */
517 void SleepUntilInput (int time)
518 {
519
520         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
521 }
522
523
524 /*
525 ==================
526 WinMain
527 ==================
528 */
529 HINSTANCE       global_hInstance;
530 int                     global_nCmdShow;
531 char            *argv[MAX_NUM_ARGVS];
532 static char     *empty_string = "";
533
534 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
535 {
536         double                  oldtime, newtime;
537         MEMORYSTATUS    lpBuffer;
538         static  char    cwd[1024];
539         int                             t;
540
541     /* previous instances do not exist in Win32 */
542     if (hPrevInstance)
543         return 0;
544
545         global_hInstance = hInstance;
546         global_nCmdShow = nCmdShow;
547
548         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
549         GlobalMemoryStatus (&lpBuffer);
550
551         if (!GetCurrentDirectory (sizeof(cwd), cwd))
552                 Sys_Error ("Couldn't determine current directory");
553
554         if (cwd[strlen(cwd)-1] == '/')
555                 cwd[strlen(cwd)-1] = 0;
556
557         memset(&host_parms, 0, sizeof(host_parms));
558
559         host_parms.basedir = cwd;
560
561         host_parms.argc = 1;
562         argv[0] = empty_string;
563
564         while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS))
565         {
566                 while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126)))
567                         lpCmdLine++;
568
569                 if (*lpCmdLine)
570                 {
571                         argv[host_parms.argc] = lpCmdLine;
572                         host_parms.argc++;
573
574                         while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126)))
575                                 lpCmdLine++;
576
577                         if (*lpCmdLine)
578                         {
579                                 *lpCmdLine = 0;
580                                 lpCmdLine++;
581                         }
582                         
583                 }
584         }
585
586         host_parms.argv = argv;
587
588         COM_InitArgv (host_parms.argc, host_parms.argv);
589
590         host_parms.argc = com_argc;
591         host_parms.argv = com_argv;
592
593         Sys_Shared_Init();
594
595 // take the greater of all the available memory or half the total memory,
596 // but at least 8 Mb and no more than 16 Mb, unless they explicitly
597 // request otherwise
598         /*
599         host_parms.memsize = lpBuffer.dwAvailPhys;
600
601         if (host_parms.memsize < MINIMUM_WIN_MEMORY)
602                 host_parms.memsize = MINIMUM_WIN_MEMORY;
603
604         if (host_parms.memsize < (lpBuffer.dwTotalPhys >> 1))
605                 host_parms.memsize = lpBuffer.dwTotalPhys >> 1;
606
607         if (host_parms.memsize > MAXIMUM_WIN_MEMORY)
608                 host_parms.memsize = MAXIMUM_WIN_MEMORY;
609         */
610
611 //      Sys_PageIn (parms.membase, parms.memsize);
612
613         tevent = CreateEvent(NULL, false, false, NULL);
614
615         if (!tevent)
616                 Sys_Error ("Couldn't create event");
617
618         // LordHavoc: can't check cls.state because it hasn't been initialized yet
619         // if (cls.state == ca_dedicated)
620         if (COM_CheckParm("-dedicated"))
621         {
622                 if (!AllocConsole ())
623                         Sys_Error ("Couldn't create dedicated server console");
624
625                 hinput = GetStdHandle (STD_INPUT_HANDLE);
626                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
627
628         // give QHOST a chance to hook into the console
629                 if ((t = COM_CheckParm ("-HFILE")) > 0)
630                 {
631                         if (t < com_argc)
632                                 hFile = (HANDLE)atoi (com_argv[t+1]);
633                 }
634                         
635                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
636                 {
637                         if (t < com_argc)
638                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
639                 }
640                         
641                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
642                 {
643                         if (t < com_argc)
644                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
645                 }
646
647                 InitConProc (hFile, heventParent, heventChild);
648         }
649
650 // because sound is off until we become active
651         S_BlockSound ();
652
653 #if WIN32_USETIMEGETTIME
654         // make sure the timer is high precision, otherwise NT gets 18ms resolution
655         // LordHavoc:
656         // Windows 2000 Advanced Server (and possibly other versions)
657         // apparently have a broken timer, because it runs at more like 10x speed
658         // if this isn't used, heh
659         timeBeginPeriod (1);
660 #endif
661
662         Sys_Printf ("Host_Init\n");
663         Host_Init ();
664
665         oldtime = Sys_DoubleTime ();
666
667     /* main window message loop */
668         while (1)
669         {
670                 if (cls.state != ca_dedicated)
671                 {
672                 // yield the CPU for a little while when paused, minimized, or not the focus
673                         if ((cl.paused && !ActiveApp) || Minimized)
674                         {
675                                 SleepUntilInput (PAUSE_SLEEP);
676                                 scr_skipupdate = 1;             // no point in bothering to draw
677                         }
678                         else if (!ActiveApp)
679                                 SleepUntilInput (NOT_FOCUS_SLEEP);
680                 }
681
682                 newtime = Sys_DoubleTime ();
683                 Host_Frame (newtime - oldtime);
684                 oldtime = newtime;
685         }
686
687     /* return success of application */
688     return true;
689 }
690