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