]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - sys_win.c
changed Sys_Error to not put up a messagebox if in dedicated mode, and cleaned it...
[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 <windows.h>
24 #include <dsound.h>
25 #include "errno.h"
26 #include "resource.h"
27 #include "conproc.h"
28 #include "direct.h"
29
30 extern void S_BlockSound (void);
31
32 cvar_t sys_usetimegettime = {CVAR_SAVE, "sys_usetimegettime", "1"};
33
34 // # of seconds to wait on Sys_Error running dedicated before exiting
35 #define CONSOLE_ERROR_TIMEOUT   60.0
36 // sleep time on pause or minimization
37 #define PAUSE_SLEEP             50
38 // sleep time when not focus
39 #define NOT_FOCUS_SLEEP 20
40
41 static qboolean         sc_return_on_enter = false;
42 HANDLE                          hinput, houtput;
43
44 static HANDLE   tevent;
45 static HANDLE   hFile;
46 static HANDLE   heventParent;
47 static HANDLE   heventChild;
48
49
50 /*
51 ===============================================================================
52
53 SYSTEM IO
54
55 ===============================================================================
56 */
57
58 void SleepUntilInput (int time);
59
60 void Sys_Error (const char *error, ...)
61 {
62         va_list         argptr;
63         char            text[1024];
64         static int      in_sys_error0 = 0;
65         static int      in_sys_error1 = 0;
66         static int      in_sys_error2 = 0;
67         static int      in_sys_error3 = 0;
68
69         va_start (argptr, error);
70         vsnprintf (text, sizeof (text), error, argptr);
71         va_end (argptr);
72
73         Con_Printf ("Quake Error: %s\n", text);
74
75         // close video so the message box is visible, unless we already tried that
76         if (!in_sys_error0 && cls.state != ca_dedicated)
77         {
78                 in_sys_error0 = 1;
79                 VID_Shutdown();
80         }
81
82         if (!in_sys_error3 && cls.state != ca_dedicated)
83         {
84                 in_sys_error3 = true;
85                 MessageBox(NULL, text, "Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
86         }
87
88         if (!in_sys_error1)
89         {
90                 in_sys_error1 = 1;
91                 Host_Shutdown ();
92         }
93
94 // shut down QHOST hooks if necessary
95         if (!in_sys_error2)
96         {
97                 in_sys_error2 = 1;
98                 Sys_Shutdown ();
99         }
100
101         exit (1);
102 }
103
104 void Sys_Shutdown (void)
105 {
106         if (tevent)
107                 CloseHandle (tevent);
108
109         if (cls.state == ca_dedicated)
110                 FreeConsole ();
111
112 // shut down QHOST hooks if necessary
113         DeinitConProc ();
114 }
115
116 void Sys_PrintToTerminal(const char *text)
117 {
118         DWORD dummy;
119         extern HANDLE houtput;
120         if (cls.state == ca_dedicated)
121                 WriteFile(houtput, text, strlen (text), &dummy, NULL);
122 }
123
124 /*
125 ================
126 Sys_DoubleTime
127 ================
128 */
129 double Sys_DoubleTime (void)
130 {
131         static int first = true;
132         static double oldtime = 0.0, curtime = 0.0;
133         double newtime;
134         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
135         if (sys_usetimegettime.integer)
136         {
137                 static int firsttimegettime = true;
138                 // timeGetTime
139                 // platform:
140                 // Windows 95/98/ME/NT/2000/XP
141                 // features:
142                 // reasonable accuracy (millisecond)
143                 // issues:
144                 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
145
146                 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
147                 if (firsttimegettime)
148                 {
149                         timeBeginPeriod (1);
150                         firsttimegettime = false;
151                 }
152
153                 newtime = (double) timeGetTime () / 1000.0;
154         }
155         else
156         {
157                 // QueryPerformanceCounter
158                 // platform:
159                 // Windows 95/98/ME/NT/2000/XP
160                 // features:
161                 // very accurate (CPU cycles)
162                 // known issues:
163                 // does not necessarily match realtime too well (tends to get faster and faster in win98)
164                 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
165                 double timescale;
166                 LARGE_INTEGER PerformanceFreq;
167                 LARGE_INTEGER PerformanceCount;
168
169                 if (!QueryPerformanceFrequency (&PerformanceFreq))
170                         Sys_Error ("No hardware timer available");
171                 QueryPerformanceCounter (&PerformanceCount);
172
173                 #ifdef __BORLANDC__
174                 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
175                 newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
176                 #else
177                 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
178                 newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
179                 #endif
180         }
181
182         if (first)
183         {
184                 first = false;
185                 oldtime = newtime;
186         }
187
188         if (newtime < oldtime)
189         {
190                 // warn if it's significant
191                 if (newtime - oldtime < -0.01)
192                         Con_Printf("Sys_DoubleTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, newtime - oldtime);
193         }
194         else
195                 curtime += newtime - oldtime;
196         oldtime = newtime;
197
198         return curtime;
199 }
200
201
202 char *Sys_ConsoleInput (void)
203 {
204         static char text[256];
205         static int len;
206         INPUT_RECORD recs[1024];
207         int ch;
208         DWORD numread, numevents, dummy;
209
210         if (cls.state != ca_dedicated)
211                 return NULL;
212
213
214         for ( ;; )
215         {
216                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
217                         Sys_Error ("Error getting # of console events");
218
219                 if (numevents <= 0)
220                         break;
221
222                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
223                         Sys_Error ("Error reading console input");
224
225                 if (numread != 1)
226                         Sys_Error ("Couldn't read console input");
227
228                 if (recs[0].EventType == KEY_EVENT)
229                 {
230                         if (!recs[0].Event.KeyEvent.bKeyDown)
231                         {
232                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
233
234                                 switch (ch)
235                                 {
236                                         case '\r':
237                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
238
239                                                 if (len)
240                                                 {
241                                                         text[len] = 0;
242                                                         len = 0;
243                                                         return text;
244                                                 }
245                                                 else if (sc_return_on_enter)
246                                                 {
247                                                 // special case to allow exiting from the error handler on Enter
248                                                         text[0] = '\r';
249                                                         len = 0;
250                                                         return text;
251                                                 }
252
253                                                 break;
254
255                                         case '\b':
256                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
257                                                 if (len)
258                                                 {
259                                                         len--;
260                                                 }
261                                                 break;
262
263                                         default:
264                                                 if (ch >= ' ')
265                                                 {
266                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);
267                                                         text[len] = ch;
268                                                         len = (len + 1) & 0xff;
269                                                 }
270
271                                                 break;
272
273                                 }
274                         }
275                 }
276         }
277
278         return NULL;
279 }
280
281 void Sys_Sleep(int milliseconds)
282 {
283         if (milliseconds < 1)
284                 milliseconds = 1;
285         Sleep(milliseconds);
286 }
287
288 char *Sys_GetClipboardData (void)
289 {
290         char *data = NULL;
291         char *cliptext;
292
293         if (OpenClipboard (NULL) != 0)
294         {
295                 HANDLE hClipboardData;
296
297                 if ((hClipboardData = GetClipboardData (CF_TEXT)) != 0)
298                 {
299                         if ((cliptext = GlobalLock (hClipboardData)) != 0) 
300                         {
301                                 data = malloc (GlobalSize(hClipboardData)+1);
302                                 strcpy (data, cliptext);
303                                 GlobalUnlock (hClipboardData);
304                         }
305                 }
306                 CloseClipboard ();
307         }
308         return data;
309 }
310
311 /*
312 ==============================================================================
313
314 WINDOWS CRAP
315
316 ==============================================================================
317 */
318
319
320 void SleepUntilInput (int time)
321 {
322         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
323 }
324
325
326 /*
327 ==================
328 WinMain
329 ==================
330 */
331 HINSTANCE       global_hInstance;
332 const char      *argv[MAX_NUM_ARGVS];
333 char            program_name[MAX_OSPATH];
334
335 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
336 {
337         double frameoldtime, framenewtime;
338         MEMORYSTATUS lpBuffer;
339         int t;
340
341         /* previous instances do not exist in Win32 */
342         if (hPrevInstance)
343                 return 0;
344
345         global_hInstance = hInstance;
346
347         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
348         GlobalMemoryStatus (&lpBuffer);
349
350         program_name[sizeof(program_name)-1] = 0;
351         GetModuleFileNameA(NULL, program_name, sizeof(program_name) - 1);
352
353         com_argc = 1;
354         com_argv = argv;
355         argv[0] = program_name;
356
357         // FIXME: this tokenizer is rather redundent, call a more general one
358         while (*lpCmdLine && (com_argc < MAX_NUM_ARGVS))
359         {
360                 while (*lpCmdLine && *lpCmdLine <= ' ')
361                         lpCmdLine++;
362
363                 if (!*lpCmdLine)
364                         break;
365
366                 if (*lpCmdLine == '\"')
367                 {
368                         // quoted string
369                         lpCmdLine++;
370                         argv[com_argc] = lpCmdLine;
371                         com_argc++;
372                         while (*lpCmdLine && (*lpCmdLine != '\"'))
373                                 lpCmdLine++;
374                 }
375                 else
376                 {
377                         // unquoted word
378                         argv[com_argc] = lpCmdLine;
379                         com_argc++;
380                         while (*lpCmdLine && *lpCmdLine > ' ')
381                                 lpCmdLine++;
382                 }
383
384                 if (*lpCmdLine)
385                 {
386                         *lpCmdLine = 0;
387                         lpCmdLine++;
388                 }
389         }
390
391         Sys_Shared_EarlyInit();
392
393         Cvar_RegisterVariable(&sys_usetimegettime);
394
395         tevent = CreateEvent(NULL, false, false, NULL);
396
397         if (!tevent)
398                 Sys_Error ("Couldn't create event");
399
400         // LordHavoc: can't check cls.state because it hasn't been initialized yet
401         // if (cls.state == ca_dedicated)
402         if (COM_CheckParm("-dedicated"))
403         {
404                 if (!AllocConsole ())
405                         Sys_Error ("Couldn't create dedicated server console");
406
407                 hinput = GetStdHandle (STD_INPUT_HANDLE);
408                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
409
410         // give QHOST a chance to hook into the console
411                 if ((t = COM_CheckParm ("-HFILE")) > 0)
412                 {
413                         if (t < com_argc)
414                                 hFile = (HANDLE)atoi (com_argv[t+1]);
415                 }
416
417                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
418                 {
419                         if (t < com_argc)
420                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
421                 }
422
423                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
424                 {
425                         if (t < com_argc)
426                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
427                 }
428
429                 InitConProc (hFile, heventParent, heventChild);
430         }
431
432 // because sound is off until we become active
433         S_BlockSound ();
434
435         Host_Init ();
436
437         Sys_Shared_LateInit();
438
439         frameoldtime = Sys_DoubleTime ();
440         
441         /* main window message loop */
442         while (1)
443         {
444                 if (cls.state != ca_dedicated)
445                 {
446                 // yield the CPU for a little while when paused, minimized, or not the focus
447                         if ((cl.paused && !vid_activewindow) || vid_hidden)
448                         {
449                                 SleepUntilInput (PAUSE_SLEEP);
450                                 scr_skipupdate = 1;             // no point in bothering to draw
451                         }
452                         else if (!vid_activewindow)
453                                 SleepUntilInput (NOT_FOCUS_SLEEP);
454                 }
455
456                 framenewtime = Sys_DoubleTime ();
457                 Host_Frame (framenewtime - frameoldtime);
458                 frameoldtime = framenewtime;
459         }
460
461         /* return success of application */
462         return true;
463 }