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