2c5e36317b61a6a06c2a56bf9acb2d2b3175955f
[fishladder.git] / vg / vg_platform.h
1 // Copyright (C) 2021 Harry Godden (hgn) - All Rights Reserved
2
3 typedef uint8_t u8;
4 typedef uint16_t u16;
5 typedef uint32_t u32;
6 typedef uint64_t u64;
7 typedef int8_t i8;
8 typedef int16_t i16;
9 typedef int32_t i32;
10 typedef int64_t i64;
11
12 typedef unsigned int uint;
13
14 typedef int v2i[2];
15 typedef int v3i[3];
16 typedef int v4i[4];
17 typedef float v2f[2];
18 typedef float v3f[3];
19 typedef float v4f[4];
20 typedef v2f m2x2f[2];
21 typedef v3f m3x3f[3];
22 typedef v3f m4x3f[4];
23 typedef v3f boxf[2];
24
25 #define vg_static_assert _Static_assert
26
27 #define vg_list_size( A ) (sizeof(A)/sizeof(A[0]))
28
29 // THREADING
30 // ==================================================================================================================
31
32 // Pthred emulation for windows
33 #ifdef _WIN32
34 #include <windows.h>
35 #define MUTEX_TYPE HANDLE
36 #define MUTEX_INITIALIZER NULL
37 #define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL)
38 #define MUTEX_CLEANUP(x) (CloseHandle(x)) //TODO: Why is this defined but never used?
39 #define MUTEX_LOCK(x) emulate_pthread_mutex_lock(&(x))
40 #define MUTEX_UNLOCK(x) (ReleaseMutex(x))
41
42 int emulate_pthread_mutex_lock( volatile MUTEX_TYPE *mx )
43 {
44 if( *mx == NULL ) /* static initializer? */
45 {
46 HANDLE p = CreateMutex( NULL, FALSE, NULL );
47 if( InterlockedCompareExchangePointer( (PVOID*)mx, (PVOID)p, NULL ) != NULL )
48 CloseHandle(p);
49 }
50
51 return WaitForSingleObject( *mx, INFINITE ) == WAIT_FAILED;
52 }
53 #else
54 #include <pthread.h>
55 #define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
56 #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
57 #define MUTEX_TYPE pthread_mutex_t
58 #define MUTEX_INITIALIZER {0}
59 #endif
60
61
62 int vg_thread_run( void *pfunc, void *data )
63 {
64 #ifdef _WIN32
65
66 HANDLE hThread = CreateThread
67 (
68 NULL, // Thread attributes
69 0, // Stack size (0 = use default)
70 pfunc, // Thread start address
71 data, // Parameter to pass to the thread
72 0, // Creation flags
73 NULL // Thread id
74 );
75
76 if ( hThread == NULL )
77 {
78 // Thread creation failed.
79 // More details can be retrieved by calling GetLastError()
80 return 1;
81 }
82 else
83 {
84 CloseHandle( hThread );
85 return 0;
86 }
87
88 #else
89
90 pthread_t hThread;
91 if( pthread_create( &hThread, NULL, pfunc, data ) )
92 {
93 return 1;
94 }
95 else
96 {
97 pthread_detach( hThread );
98 return 0;
99 }
100
101 #endif
102 }