]> icculus.org git repositories - icculus/iodoom3.git/blob - neo/sys/sys_public.h
hello world
[icculus/iodoom3.git] / neo / sys / sys_public.h
1 /*
2 ===========================================================================
3
4 Doom 3 GPL Source Code
5 Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. 
6
7 This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).  
8
9 Doom 3 Source Code is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 Doom 3 Source Code is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with Doom 3 Source Code.  If not, see <http://www.gnu.org/licenses/>.
21
22 In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code.  If not, please request a copy in writing from id Software at the address below.
23
24 If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
25
26 ===========================================================================
27 */
28
29 #ifndef __SYS_PUBLIC__
30 #define __SYS_PUBLIC__
31
32 /*
33 ===============================================================================
34
35         Non-portable system services.
36
37 ===============================================================================
38 */
39
40
41 // Win32
42 #if defined(WIN32) || defined(_WIN32)
43
44 #define BUILD_STRING                                    "win-x86"
45 #define BUILD_OS_ID                                             0
46 #define CPUSTRING                                               "x86"
47 #define CPU_EASYARGS                                    1
48
49 #define ALIGN16( x )                                    __declspec(align(16)) x
50 #define PACKED
51
52 #define _alloca16( x )                                  ((void *)((((int)_alloca( (x)+15 )) + 15) & ~15))
53
54 #define PATHSEPERATOR_STR                               "\\"
55 #define PATHSEPERATOR_CHAR                              '\\'
56
57 #define ID_INLINE                                               __forceinline
58 #define ID_STATIC_TEMPLATE                              static
59
60 #define assertmem( x, y )                               assert( _CrtIsValidPointer( x, y, true ) )
61
62 #endif
63
64 // Mac OSX
65 #if defined(MACOS_X) || defined(__APPLE__)
66
67 #define BUILD_STRING                            "MacOSX-universal"
68 #define BUILD_OS_ID                                     1
69 #ifdef __ppc__
70         #define CPUSTRING                                       "ppc"
71         #define CPU_EASYARGS                            0
72 #elif defined(__i386__)
73         #define CPUSTRING                                       "x86"
74         #define CPU_EASYARGS                            1
75 #endif
76
77 #define ALIGN16( x )                                    x __attribute__ ((aligned (16)))
78
79 #ifdef __MWERKS__
80 #define PACKED
81 #include <alloca.h>
82 #else
83 #define PACKED                                                  __attribute__((packed))
84 #endif
85
86 #define _alloca                                                 alloca
87 #define _alloca16( x )                                  ((void *)((((int)alloca( (x)+15 )) + 15) & ~15))
88
89 #define PATHSEPERATOR_STR                               "/"
90 #define PATHSEPERATOR_CHAR                              '/'
91
92 #define __cdecl
93 #define ASSERT                                                  assert
94
95 #define ID_INLINE                                               inline
96 #define ID_STATIC_TEMPLATE
97
98 #define assertmem( x, y )
99
100 #endif
101
102
103 // Linux
104 #ifdef __linux__
105
106 #ifdef __i386__
107         #define BUILD_STRING                            "linux-x86"
108         #define BUILD_OS_ID                                     2
109         #define CPUSTRING                                       "x86"
110         #define CPU_EASYARGS                            1
111 #elif defined(__ppc__)
112         #define BUILD_STRING                            "linux-ppc"
113         #define CPUSTRING                                       "ppc"
114         #define CPU_EASYARGS                            0
115 #endif
116
117 #define _alloca                                                 alloca
118 #define _alloca16( x )                                  ((void *)((((int)alloca( (x)+15 )) + 15) & ~15))
119
120 #define ALIGN16( x )                                    x
121 #define PACKED                                                  __attribute__((packed))
122
123 #define PATHSEPERATOR_STR                               "/"
124 #define PATHSEPERATOR_CHAR                              '/'
125
126 #define __cdecl
127 #define ASSERT                                                  assert
128
129 #define ID_INLINE                                               inline
130 #define ID_STATIC_TEMPLATE
131
132 #define assertmem( x, y )
133
134 #endif
135
136 #ifdef __GNUC__
137 #define id_attribute(x) __attribute__(x)
138 #else
139 #define id_attribute(x)  
140 #endif
141
142 typedef enum {
143         CPUID_NONE                                                      = 0x00000,
144         CPUID_UNSUPPORTED                                       = 0x00001,      // unsupported (386/486)
145         CPUID_GENERIC                                           = 0x00002,      // unrecognized processor
146         CPUID_INTEL                                                     = 0x00004,      // Intel
147         CPUID_AMD                                                       = 0x00008,      // AMD
148         CPUID_MMX                                                       = 0x00010,      // Multi Media Extensions
149         CPUID_3DNOW                                                     = 0x00020,      // 3DNow!
150         CPUID_SSE                                                       = 0x00040,      // Streaming SIMD Extensions
151         CPUID_SSE2                                                      = 0x00080,      // Streaming SIMD Extensions 2
152         CPUID_SSE3                                                      = 0x00100,      // Streaming SIMD Extentions 3 aka Prescott's New Instructions
153         CPUID_ALTIVEC                                           = 0x00200,      // AltiVec
154         CPUID_HTT                                                       = 0x01000,      // Hyper-Threading Technology
155         CPUID_CMOV                                                      = 0x02000,      // Conditional Move (CMOV) and fast floating point comparison (FCOMI) instructions
156         CPUID_FTZ                                                       = 0x04000,      // Flush-To-Zero mode (denormal results are flushed to zero)
157         CPUID_DAZ                                                       = 0x08000       // Denormals-Are-Zero mode (denormal source operands are set to zero)
158 } cpuid_t;
159
160 typedef enum {
161         FPU_EXCEPTION_INVALID_OPERATION         = 1,
162         FPU_EXCEPTION_DENORMALIZED_OPERAND      = 2,
163         FPU_EXCEPTION_DIVIDE_BY_ZERO            = 4,
164         FPU_EXCEPTION_NUMERIC_OVERFLOW          = 8,
165         FPU_EXCEPTION_NUMERIC_UNDERFLOW         = 16,
166         FPU_EXCEPTION_INEXACT_RESULT            = 32
167 } fpuExceptions_t;
168
169 typedef enum {
170         FPU_PRECISION_SINGLE                            = 0,
171         FPU_PRECISION_DOUBLE                            = 1,
172         FPU_PRECISION_DOUBLE_EXTENDED           = 2
173 } fpuPrecision_t;
174
175 typedef enum {
176         FPU_ROUNDING_TO_NEAREST                         = 0,
177         FPU_ROUNDING_DOWN                                       = 1,
178         FPU_ROUNDING_UP                                         = 2,
179         FPU_ROUNDING_TO_ZERO                            = 3
180 } fpuRounding_t;
181
182 typedef enum {
183         AXIS_SIDE,
184         AXIS_FORWARD,
185         AXIS_UP,
186         AXIS_ROLL,
187         AXIS_YAW,
188         AXIS_PITCH,
189         MAX_JOYSTICK_AXIS
190 } joystickAxis_t;
191
192 typedef enum {
193         SE_NONE,                                // evTime is still valid
194         SE_KEY,                                 // evValue is a key code, evValue2 is the down flag
195         SE_CHAR,                                // evValue is an ascii char
196         SE_MOUSE,                               // evValue and evValue2 are reletive signed x / y moves
197         SE_JOYSTICK_AXIS,               // evValue is an axis number and evValue2 is the current state (-127 to 127)
198         SE_CONSOLE                              // evPtr is a char*, from typing something at a non-game console
199 } sysEventType_t;
200
201 typedef enum {
202         M_ACTION1,
203         M_ACTION2,
204         M_ACTION3,
205         M_ACTION4,
206         M_ACTION5,
207         M_ACTION6,
208         M_ACTION7,
209         M_ACTION8,
210         M_DELTAX,
211         M_DELTAY,
212         M_DELTAZ
213 } sys_mEvents;
214
215 typedef struct sysEvent_s {
216         sysEventType_t  evType;
217         int                             evValue;
218         int                             evValue2;
219         int                             evPtrLength;            // bytes of data pointed to by evPtr, for journaling
220         void *                  evPtr;                          // this must be manually freed if not NULL
221 } sysEvent_t;
222
223 typedef struct sysMemoryStats_s {
224         int memoryLoad;
225         int totalPhysical;
226         int availPhysical;
227         int totalPageFile;
228         int availPageFile;
229         int totalVirtual;
230         int availVirtual;
231         int availExtendedVirtual;
232 } sysMemoryStats_t;
233
234 typedef unsigned long address_t;
235
236 template<class type> class idList;              // for Sys_ListFiles
237
238
239 void                    Sys_Init( void );
240 void                    Sys_Shutdown( void );
241 void                    Sys_Error( const char *error, ...);
242 void                    Sys_Quit( void );
243
244 bool                    Sys_AlreadyRunning( void );
245
246 // note that this isn't journaled...
247 char *                  Sys_GetClipboardData( void );
248 void                    Sys_SetClipboardData( const char *string );
249
250 // will go to the various text consoles
251 // NOT thread safe - never use in the async paths
252 void                    Sys_Printf( const char *msg, ... )id_attribute((format(printf,1,2)));
253
254 // guaranteed to be thread-safe
255 void                    Sys_DebugPrintf( const char *fmt, ... )id_attribute((format(printf,1,2)));
256 void                    Sys_DebugVPrintf( const char *fmt, va_list arg );
257
258 // a decent minimum sleep time to avoid going below the process scheduler speeds
259 #define                 SYS_MINSLEEP    20
260
261 // allow game to yield CPU time
262 // NOTE: due to SYS_MINSLEEP this is very bad portability karma, and should be completely removed
263 void                    Sys_Sleep( int msec );
264
265 // Sys_Milliseconds should only be used for profiling purposes,
266 // any game related timing information should come from event timestamps
267 int                             Sys_Milliseconds( void );
268
269 // for accurate performance testing
270 double                  Sys_GetClockTicks( void );
271 double                  Sys_ClockTicksPerSecond( void );
272
273 // returns a selection of the CPUID_* flags
274 cpuid_t                 Sys_GetProcessorId( void );
275 const char *    Sys_GetProcessorString( void );
276
277 // returns true if the FPU stack is empty
278 bool                    Sys_FPU_StackIsEmpty( void );
279
280 // empties the FPU stack
281 void                    Sys_FPU_ClearStack( void );
282
283 // returns the FPU state as a string
284 const char *    Sys_FPU_GetState( void );
285
286 // enables the given FPU exceptions
287 void                    Sys_FPU_EnableExceptions( int exceptions );
288
289 // sets the FPU precision
290 void                    Sys_FPU_SetPrecision( int precision );
291
292 // sets the FPU rounding mode
293 void                    Sys_FPU_SetRounding( int rounding );
294
295 // sets Flush-To-Zero mode (only available when CPUID_FTZ is set)
296 void                    Sys_FPU_SetFTZ( bool enable );
297
298 // sets Denormals-Are-Zero mode (only available when CPUID_DAZ is set)
299 void                    Sys_FPU_SetDAZ( bool enable );
300
301 // returns amount of system ram
302 int                             Sys_GetSystemRam( void );
303
304 // returns amount of video ram
305 int                             Sys_GetVideoRam( void );
306
307 // returns amount of drive space in path
308 int                             Sys_GetDriveFreeSpace( const char *path );
309
310 // returns memory stats
311 void                    Sys_GetCurrentMemoryStatus( sysMemoryStats_t &stats );
312 void                    Sys_GetExeLaunchMemoryStatus( sysMemoryStats_t &stats );
313
314 // lock and unlock memory
315 bool                    Sys_LockMemory( void *ptr, int bytes );
316 bool                    Sys_UnlockMemory( void *ptr, int bytes );
317
318 // set amount of physical work memory
319 void                    Sys_SetPhysicalWorkMemory( int minBytes, int maxBytes );
320
321 // allows retrieving the call stack at execution points
322 void                    Sys_GetCallStack( address_t *callStack, const int callStackSize );
323 const char *    Sys_GetCallStackStr( const address_t *callStack, const int callStackSize );
324 const char *    Sys_GetCallStackCurStr( int depth );
325 const char *    Sys_GetCallStackCurAddressStr( int depth );
326 void                    Sys_ShutdownSymbols( void );
327
328 // DLL loading, the path should be a fully qualified OS path to the DLL file to be loaded
329 int                             Sys_DLL_Load( const char *dllName );
330 void *                  Sys_DLL_GetProcAddress( int dllHandle, const char *procName );
331 void                    Sys_DLL_Unload( int dllHandle );
332
333 // event generation
334 void                    Sys_GenerateEvents( void );
335 sysEvent_t              Sys_GetEvent( void );
336 void                    Sys_ClearEvents( void );
337
338 // input is tied to windows, so it needs to be started up and shut down whenever 
339 // the main window is recreated
340 void                    Sys_InitInput( void );
341 void                    Sys_ShutdownInput( void );
342 void                    Sys_InitScanTable( void );
343 const unsigned char *Sys_GetScanTable( void );
344 unsigned char   Sys_GetConsoleKey( bool shifted );
345 // map a scancode key to a char
346 // does nothing on win32, as SE_KEY == SE_CHAR there
347 // on other OSes, consider the keyboard mapping
348 unsigned char   Sys_MapCharForKey( int key );
349
350 // keyboard input polling
351 int                             Sys_PollKeyboardInputEvents( void );
352 int                             Sys_ReturnKeyboardInputEvent( const int n, int &ch, bool &state );
353 void                    Sys_EndKeyboardInputEvents( void );
354
355 // mouse input polling
356 int                             Sys_PollMouseInputEvents( void );
357 int                             Sys_ReturnMouseInputEvent( const int n, int &action, int &value );
358 void                    Sys_EndMouseInputEvents( void );
359
360 // when the console is down, or the game is about to perform a lengthy
361 // operation like map loading, the system can release the mouse cursor
362 // when in windowed mode
363 void                    Sys_GrabMouseCursor( bool grabIt );
364
365 void                    Sys_ShowWindow( bool show );
366 bool                    Sys_IsWindowVisible( void );
367 void                    Sys_ShowConsole( int visLevel, bool quitOnClose );
368
369
370 void                    Sys_Mkdir( const char *path );
371 ID_TIME_T                       Sys_FileTimeStamp( FILE *fp );
372 // NOTE: do we need to guarantee the same output on all platforms?
373 const char *    Sys_TimeStampToStr( ID_TIME_T timeStamp );
374 const char *    Sys_DefaultCDPath( void );
375 const char *    Sys_DefaultBasePath( void );
376 const char *    Sys_DefaultSavePath( void );
377 const char *    Sys_EXEPath( void );
378
379 // use fs_debug to verbose Sys_ListFiles
380 // returns -1 if directory was not found (the list is cleared)
381 int                             Sys_ListFiles( const char *directory, const char *extension, idList<class idStr> &list );
382
383 // know early if we are performing a fatal error shutdown so the error message doesn't get lost
384 void                    Sys_SetFatalError( const char *error );
385
386 // display perference dialog
387 void                    Sys_DoPreferences( void );
388
389 /*
390 ==============================================================
391
392         Networking
393
394 ==============================================================
395 */
396
397 typedef enum {
398         NA_BAD,                                 // an address lookup failed
399         NA_LOOPBACK,
400         NA_BROADCAST,
401         NA_IP
402 } netadrtype_t;
403
404 typedef struct {
405         netadrtype_t    type;
406         unsigned char   ip[4];
407         unsigned short  port;
408 } netadr_t;
409
410 #define PORT_ANY                        -1
411
412 class idPort {
413 public:
414                                 idPort();                               // this just zeros netSocket and port
415         virtual         ~idPort();
416
417         // if the InitForPort fails, the idPort.port field will remain 0
418         bool            InitForPort( int portNumber );
419         int                     GetPort( void ) const { return bound_to.port; }
420         netadr_t        GetAdr( void ) const { return bound_to; }
421         void            Close();
422
423         bool            GetPacket( netadr_t &from, void *data, int &size, int maxSize );
424         bool            GetPacketBlocking( netadr_t &from, void *data, int &size, int maxSize, int timeout );
425         void            SendPacket( const netadr_t to, const void *data, int size );
426
427         int                     packetsRead;
428         int                     bytesRead;
429
430         int                     packetsWritten;
431         int                     bytesWritten;
432
433 private:
434         netadr_t        bound_to;               // interface and port
435         int                     netSocket;              // OS specific socket
436 };
437
438 class idTCP {
439 public:
440                                 idTCP();
441         virtual         ~idTCP();
442
443         // if host is host:port, the value of port is ignored
444         bool            Init( const char *host, short port );
445         void            Close();
446
447         // returns -1 on failure (and closes socket)
448         // those are non blocking, can be used for polling
449         // there is no buffering, you are not guaranteed to Read or Write everything in a single call
450         // (specially on win32, see recv and send documentation)
451         int                     Read( void *data, int size );
452         int                     Write( void *data, int size );
453
454 private:
455         netadr_t        address;                // remote address
456         int                     fd;                             // OS specific socket
457 };
458
459                                 // parses the port number
460                                 // can also do DNS resolve if you ask for it.
461                                 // NOTE: DNS resolve is a slow/blocking call, think before you use
462                                 // ( could be exploited for server DoS )
463 bool                    Sys_StringToNetAdr( const char *s, netadr_t *a, bool doDNSResolve );
464 const char *    Sys_NetAdrToString( const netadr_t a );
465 bool                    Sys_IsLANAddress( const netadr_t a );
466 bool                    Sys_CompareNetAdrBase( const netadr_t a, const netadr_t b );
467
468 void                    Sys_InitNetworking( void );
469 void                    Sys_ShutdownNetworking( void );
470
471
472 /*
473 ==============================================================
474
475         Multi-threading
476
477 ==============================================================
478 */
479
480 typedef unsigned int (*xthread_t)( void * );
481
482 typedef enum {
483         THREAD_NORMAL,
484         THREAD_ABOVE_NORMAL,
485         THREAD_HIGHEST
486 } xthreadPriority;
487
488 typedef struct {
489         const char *    name;
490         int                             threadHandle;
491         unsigned long   threadId;
492 } xthreadInfo;
493
494 const int MAX_THREADS                           = 10;
495 extern xthreadInfo *g_threads[MAX_THREADS];
496 extern int                      g_thread_count;
497
498 void                            Sys_CreateThread( xthread_t function, void *parms, xthreadPriority priority, xthreadInfo &info, const char *name, xthreadInfo *threads[MAX_THREADS], int *thread_count );
499 void                            Sys_DestroyThread( xthreadInfo& info ); // sets threadHandle back to 0
500
501 // find the name of the calling thread
502 // if index != NULL, set the index in g_threads array (use -1 for "main" thread)
503 const char *            Sys_GetThreadName( int *index = 0 );
504  
505 const int MAX_CRITICAL_SECTIONS         = 4;
506
507 enum {
508         CRITICAL_SECTION_ZERO = 0,
509         CRITICAL_SECTION_ONE,
510         CRITICAL_SECTION_TWO,
511         CRITICAL_SECTION_THREE
512 };
513
514 void                            Sys_EnterCriticalSection( int index = CRITICAL_SECTION_ZERO );
515 void                            Sys_LeaveCriticalSection( int index = CRITICAL_SECTION_ZERO );
516
517 const int MAX_TRIGGER_EVENTS            = 4;
518
519 enum {
520         TRIGGER_EVENT_ZERO = 0,
521         TRIGGER_EVENT_ONE,
522         TRIGGER_EVENT_TWO,
523         TRIGGER_EVENT_THREE
524 };
525
526 void                            Sys_WaitForEvent( int index = TRIGGER_EVENT_ZERO );
527 void                            Sys_TriggerEvent( int index = TRIGGER_EVENT_ZERO );
528
529 /*
530 ==============================================================
531
532         idSys
533
534 ==============================================================
535 */
536
537 class idSys {
538 public:
539         virtual void                    DebugPrintf( const char *fmt, ... )id_attribute((format(printf,2,3))) = 0;
540         virtual void                    DebugVPrintf( const char *fmt, va_list arg ) = 0;
541
542         virtual double                  GetClockTicks( void ) = 0;
543         virtual double                  ClockTicksPerSecond( void ) = 0;
544         virtual cpuid_t                 GetProcessorId( void ) = 0;
545         virtual const char *    GetProcessorString( void ) = 0;
546         virtual const char *    FPU_GetState( void ) = 0;
547         virtual bool                    FPU_StackIsEmpty( void ) = 0;
548         virtual void                    FPU_SetFTZ( bool enable ) = 0;
549         virtual void                    FPU_SetDAZ( bool enable ) = 0;
550
551         virtual void                    FPU_EnableExceptions( int exceptions ) = 0;
552
553         virtual bool                    LockMemory( void *ptr, int bytes ) = 0;
554         virtual bool                    UnlockMemory( void *ptr, int bytes ) = 0;
555
556         virtual void                    GetCallStack( address_t *callStack, const int callStackSize ) = 0;
557         virtual const char *    GetCallStackStr( const address_t *callStack, const int callStackSize ) = 0;
558         virtual const char *    GetCallStackCurStr( int depth ) = 0;
559         virtual void                    ShutdownSymbols( void ) = 0;
560
561         virtual int                             DLL_Load( const char *dllName ) = 0;
562         virtual void *                  DLL_GetProcAddress( int dllHandle, const char *procName ) = 0;
563         virtual void                    DLL_Unload( int dllHandle ) = 0;
564         virtual void                    DLL_GetFileName( const char *baseName, char *dllName, int maxLength ) = 0;
565
566         virtual sysEvent_t              GenerateMouseButtonEvent( int button, bool down ) = 0;
567         virtual sysEvent_t              GenerateMouseMoveEvent( int deltax, int deltay ) = 0;
568
569         virtual void                    OpenURL( const char *url, bool quit ) = 0;
570         virtual void                    StartProcess( const char *exePath, bool quit ) = 0;
571 };
572
573 extern idSys *                          sys;
574
575 bool Sys_LoadOpenAL( void );
576 void Sys_FreeOpenAL( void );
577
578 #endif /* !__SYS_PUBLIC__ */