a5b36033e0edd9ccfb04df9591b974086df39926
[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 v3f m3x3f[3];
21 typedef v3f m4x3f[4];
22 typedef v3f boxf[2];
23
24 #define vg_static_assert _Static_assert
25
26 #define vg_list_size( A ) (sizeof(A)/sizeof(A[0]))
27
28 // THREADING
29 // ==================================================================================================================
30
31 // Pthred emulation for windows
32 #ifdef _WIN32
33 #include <windows.h>
34 #define MUTEX_TYPE HANDLE
35 #define MUTEX_INITIALIZER NULL
36 #define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL)
37 #define MUTEX_CLEANUP(x) (CloseHandle(x)) //TODO: Why is this defined but never used?
38 #define MUTEX_LOCK(x) emulate_pthread_mutex_lock(&(x))
39 #define MUTEX_UNLOCK(x) (ReleaseMutex(x))
40
41 int emulate_pthread_mutex_lock( volatile MUTEX_TYPE *mx )
42 {
43 if( *mx == NULL ) /* static initializer? */
44 {
45 HANDLE p = CreateMutex( NULL, FALSE, NULL );
46 if( InterlockedCompareExchangePointer( (PVOID*)mx, (PVOID)p, NULL ) != NULL )
47 CloseHandle(p);
48 }
49
50 return WaitForSingleObject( *mx, INFINITE ) == WAIT_FAILED;
51 }
52 #else
53 #include <pthread.h>
54 #define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
55 #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
56 #define MUTEX_TYPE pthread_mutex_t
57 #define MUTEX_INITIALIZER {0}
58 #endif
59
60
61 int vg_thread_run( void *pfunc, void *data )
62 {
63 #ifdef _WIN32
64
65 HANDLE hThread = CreateThread
66 (
67 NULL, // Thread attributes
68 0, // Stack size (0 = use default)
69 pfunc, // Thread start address
70 data, // Parameter to pass to the thread
71 0, // Creation flags
72 NULL // Thread id
73 );
74
75 if ( hThread == NULL )
76 {
77 // Thread creation failed.
78 // More details can be retrieved by calling GetLastError()
79 return 1;
80 }
81 else
82 {
83 CloseHandle( hThread );
84 return 0;
85 }
86
87 #else
88
89 pthread_t hThread;
90 if( pthread_create( &hThread, NULL, pfunc, data ) )
91 {
92 return 1;
93 }
94 else
95 {
96 pthread_detach( hThread );
97 return 0;
98 }
99
100 #endif
101 }