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