-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommon.cpp
642 lines (548 loc) · 17.5 KB
/
common.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
#include "common.h"
#include "config.h"
#include <strsafe.h>
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if 0
#define DEBUG_TIC_TOC_TIMER
#endif
// -----------------
// Windows utitities
// -----------------
#pragma warning(push)
#pragma warning(disable : 4995) //deprication warning
#pragma warning(disable : 4996) //security warning
UINT MyCreateUserWindowMessage( const char *name, size_t id )
{ char s[1000],*t = s;
size_t n;
memset(s,0,1000);
n = strlen(name);
memcpy(s,name,n);
t+=n;
if( sizeof(size_t)==8 )
sprintf(t,"_%llu",id);
else
sprintf(t,"_%lu",id);
return ::RegisterWindowMessageA(s);
}
#pragma warning(pop)
//
// Utility functions
//
inline u8 _next_pow2_u8(u8 v)
{ v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v++;
return v;
}
inline u32 _next_pow2_u32(u32 v)
{ v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
inline u64 _next_pow2_u64(u64 v)
{ v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
inline size_t _next_pow2_size_t(size_t v)
{ v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
#ifdef _WIN64
v |= v >> 32;
#endif
v++;
return v;
}
#if _MSC_VER < 1800
long int lroundf(float x)
{
if (x - (long int)x >= 0.5)
return (long int)(x + 1);
return (long int)x;
}
#endif
void Copy_Lines( void *dst, size_t dst_stride, void *src, size_t src_stride, size_t nlines )
{ u8 *dst_cur = (u8*)dst + nlines * dst_stride,
*src_cur = (u8*)src + nlines * src_stride;
size_t nbytes = MIN(dst_stride,src_stride);
while( src_cur > src )
{ src_cur -= src_stride;
dst_cur -= src_stride;
memcpy( dst_cur, src_cur, nbytes );
}
}
void Copy_Planes_By_Lines( void *dst, size_t dst_row_pitch, size_t dst_depth_pitch,
void *src, size_t src_row_pitch, size_t src_depth_pitch,
size_t nlines, size_t nplanes )
{ while(nplanes--)
{ u8 *dst_cur = (u8*)dst + nplanes * dst_depth_pitch + nlines * dst_row_pitch,
*src_cur = (u8*)src + nplanes * src_depth_pitch + nlines * src_row_pitch;
size_t nbytes = MIN(dst_row_pitch,src_row_pitch),
iline = nlines;
while( iline-- )
{ src_cur -= src_row_pitch;
dst_cur -= dst_row_pitch;
memcpy( dst_cur, src_cur, nbytes );
}
}
}
// ---------
// Profiling
// ---------
TicTocTimer tic(void)
{ TicTocTimer t = {0,0};
LARGE_INTEGER tmp;
Guarded_Assert_WinErr( QueryPerformanceFrequency( &tmp ) );
t.rate = tmp.QuadPart;
Guarded_Assert_WinErr( QueryPerformanceCounter ( &tmp ) );
t.last = tmp.QuadPart;
#ifdef DEBUG_TIC_TOC_TIMER
//Guarded_Assert( t.rate > 0 );
debug("Tic() timer frequency: %I64u Hz\r\n"
" resolution: %g ns\r\n"
" counts: %I64u\r\n",t.rate,
1e9/(double)t.rate,
t.last);
#endif
return t;
}
// - returns time since last in seconds
// - updates timer
double toc(TicTocTimer *t)
{ LARGE_INTEGER tmp;
u64 now;
double delta;
Guarded_Assert_WinErr( QueryPerformanceCounter( &tmp ) );
now = tmp.QuadPart;
delta = ( now - t->last) / (double)t->rate;
t->last = now;
return delta;
}
// --------
// Shutdown
// --------
//
// Shutdown callback functions
// - take no arguments
// - do not exit/abort under any circumstances
// - return 0 only on success
// - are called in reverse order of when they were
// added.
//
// After all callbacks return, the system is assumed
// to be in a state where exit/abort can safely be
// called.
//
TYPE_VECTOR_DECLARE( pf_shutdown_callback );
TYPE_VECTOR_DEFINE ( pf_shutdown_callback );
vector_pf_shutdown_callback g_shutdown_callbacks = VECTOR_EMPTY;
LPCRITICAL_SECTION g_p_shutdown_critical_section = NULL;
static LPCRITICAL_SECTION _get_shutdown_critical_section(void)
{ static CRITICAL_SECTION gcs;
if(!g_p_shutdown_critical_section)
{ InitializeCriticalSectionAndSpinCount( &gcs, 0x80000400 );
g_p_shutdown_critical_section = &gcs;
}
return g_p_shutdown_critical_section;
}
static void _cleanup_shutdown_critical_section(void)
{ if(g_p_shutdown_critical_section)
DeleteCriticalSection( g_p_shutdown_critical_section );
g_p_shutdown_critical_section = NULL;
}
size_t Register_New_Shutdown_Callback( pf_shutdown_callback callback )
{ size_t idx;
EnterCriticalSection( _get_shutdown_critical_section() );
idx = g_shutdown_callbacks.count++;
vector_pf_shutdown_callback_request( &g_shutdown_callbacks, idx );
g_shutdown_callbacks.contents[idx] = callback;
LeaveCriticalSection( _get_shutdown_critical_section() );
return idx;
}
unsigned int Shutdown_Soft(void)
{ unsigned err = 0;
EnterCriticalSection( _get_shutdown_critical_section() );
{ size_t cnt = g_shutdown_callbacks.count;
pf_shutdown_callback *beg = g_shutdown_callbacks.contents,
*end = beg+cnt,
*cur;
static int lock = 0;// Avoid recursion
assert( lock == 0 );
lock = 1;
//swhile( cur-- > beg )
for( cur = beg; cur < end; cur++ ) // shutdown functions must be called in a defined order
if(cur)
err |= (*cur)();
lock = 0;
vector_pf_shutdown_callback_free_contents( &g_shutdown_callbacks );
}
LeaveCriticalSection( _get_shutdown_critical_section() );
return err;
}
DWORD WINAPI
_shutdown_thread_proc( LPVOID lparam )
{ return Shutdown_Soft();
}
unsigned int
Shutdown_Soft_Nonblocking(void)
{ return QueueUserWorkItem( _shutdown_thread_proc, NULL, NULL );
}
void Shutdown_Hard(unsigned int err)
{ exit( err | Shutdown_Soft() );
}
void Shutdown_Hard_Nonblocking(unsigned int err)
{ exit( err | Shutdown_Soft_Nonblocking() );
}
// ------------------------------------
// Error, Debug, and Warning reporting
// ------------------------------------
TYPE_VECTOR_DECLARE(pf_reporting_callback);
TYPE_VECTOR_DEFINE(pf_reporting_callback);
vector_pf_reporting_callback g_error_report_callbacks = VECTOR_EMPTY;
vector_pf_reporting_callback g_warning_report_callbacks = VECTOR_EMPTY;
vector_pf_reporting_callback g_debug_report_callbacks = VECTOR_EMPTY;
LPCRITICAL_SECTION g_p_reporting_critical_section = NULL;
static LPCRITICAL_SECTION _get_reporting_critical_section(void)
{ static CRITICAL_SECTION gcs;
if(!g_p_reporting_critical_section)
{ InitializeCriticalSectionAndSpinCount( &gcs, 0x80000400 ); // don't assert - Release builds will optimize this out.
g_p_reporting_critical_section = &gcs;
}
return g_p_reporting_critical_section;
}
static void _cleanup_reporting_critical_section(void)
{ if(g_p_reporting_critical_section)
DeleteCriticalSection( g_p_reporting_critical_section );
g_p_reporting_critical_section = NULL;
}
size_t _register_new_reporting_callback( vector_pf_reporting_callback *vec,
pf_reporting_callback callback )
{ size_t idx;
EnterCriticalSection( _get_reporting_critical_section() );
{ idx = vec->count++;
vector_pf_reporting_callback_request( vec, idx );
vec->contents[idx] = callback;
}
LeaveCriticalSection( _get_reporting_critical_section() );
return idx;
}
size_t Register_New_Error_Reporting_Callback( pf_reporting_callback callback )
{ return _register_new_reporting_callback( &g_error_report_callbacks, callback );
}
size_t Register_New_Warning_Reporting_Callback( pf_reporting_callback callback )
{ return _register_new_reporting_callback( &g_warning_report_callbacks, callback );
}
size_t Register_New_Debug_Reporting_Callback( pf_reporting_callback callback )
{ return _register_new_reporting_callback( &g_debug_report_callbacks, callback );
}
void _reporting_callbacks_remove_all( vector_pf_reporting_callback *vec )
{ vec->count = 0;
}
void Error_Reporting_Remove_All_Callbacks(void)
{ _reporting_callbacks_remove_all( &g_error_report_callbacks );
}
void Debug_Reporting_Remove_All_Callbacks(void)
{ _reporting_callbacks_remove_all( &g_debug_report_callbacks );
}
void Warning_Reporting_Remove_All_Callbacks(void)
{ _reporting_callbacks_remove_all( &g_warning_report_callbacks );
}
//
// Log to debugger console
// -----------------------
//
void _reporting_log_to_vs_console_callback( const char *msg )
{ OutputDebugStringA(msg);
}
void Reporting_Setup_Log_To_VSDebugger_Console(void)
{ Register_New_Error_Reporting_Callback ( &_reporting_log_to_vs_console_callback );
Register_New_Warning_Reporting_Callback( &_reporting_log_to_vs_console_callback );
Register_New_Debug_Reporting_Callback ( &_reporting_log_to_vs_console_callback );
}
//
// Log to file
// -----------
// A simple reporting setup
//
FILE *_g_reporting_log_file = NULL;
void _reporting_log_to_file_callback( const char *msg )
{ if( _g_reporting_log_file )
{ fprintf( _g_reporting_log_file, msg );
fflush( _g_reporting_log_file );
}
}
unsigned int _reporting_log_to_file_shutdown_callback( void )
{
if( _g_reporting_log_file )
{ int code = fclose(_g_reporting_log_file );
_g_reporting_log_file = 0;
return code;
}
return 0;
}
void Reporting_Setup_Log_To_File( FILE *file )
{ _g_reporting_log_file = file;
if(file)
{ Register_New_Error_Reporting_Callback ( &_reporting_log_to_file_callback );
Register_New_Warning_Reporting_Callback( &_reporting_log_to_file_callback );
Register_New_Debug_Reporting_Callback ( &_reporting_log_to_file_callback );
Register_New_Shutdown_Callback( &_reporting_log_to_file_shutdown_callback );
}
}
void Reporting_Setup_Log_To_Filename( const char* filename )
{ FILE* fp = fopen(filename,"w");
assert(fp);
Reporting_Setup_Log_To_File(fp);
}
void _reporting_log_to_stdout_callback( const char *msg )
{ fprintf( stdout, msg );
}
void Reporting_Setup_Log_To_Stdout( void )
{ Register_New_Error_Reporting_Callback ( &_reporting_log_to_stdout_callback );
Register_New_Warning_Reporting_Callback( &_reporting_log_to_stdout_callback );
Register_New_Debug_Reporting_Callback ( &_reporting_log_to_stdout_callback );
}
//
// Main reporting functions
// ------------------------
//
void ReportLastWindowsError(void)
{ EnterCriticalSection( _get_reporting_critical_section() );
{ // Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("Failed with error %d: %s"),
dw, lpMsgBuf);
// spam formated string to listeners
{ static int lock = 0;
assert( lock == 0 ); // One of the logging functions generated a log message
lock = 1;
{ pf_reporting_callback *beg = g_error_report_callbacks.contents;
size_t cnt = g_error_report_callbacks.count;
pf_reporting_callback *cur = beg + cnt;
while( cur-- > beg )
if(cur)
(*cur)((char*)lpDisplayBuf);
}
lock = 0;
}
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
LeaveCriticalSection( _get_reporting_critical_section() );
}
/* HAX
[ngc] adding timestamp
The logging functions exactly allocate the required string length.
To quickly add a timestamp, I ignore this and just add fixed space.
*/
#include <time.h>
static void timestamp(char *str)
{ char buf[1024]={0};
time_t ltime; /* calendar time */
ltime=time(NULL); /* get current cal time */
sprintf(buf,"\t%s\n",asctime( localtime(<ime) ) );
strcat(str,buf);
}
void error(const char* fmt, ...)
{ EnterCriticalSection( _get_reporting_critical_section() );
{ static const char prefix[] = "*** ERROR: ";
size_t len;
va_list argList;
static vector_char vbuf = VECTOR_EMPTY;
// render formated string
va_start( argList, fmt );
len = sizeof(prefix) + _vscprintf(fmt,argList) + 1 +1024;
vector_char_request( &vbuf, len );
memset ( vbuf.contents, 0, len );
#pragma warning( push )
#pragma warning( disable:4996 )
#pragma warning( disable:4995 )
sprintf ( vbuf.contents, prefix );
vsprintf( vbuf.contents+sizeof(prefix)-1, fmt, argList);
timestamp(vbuf.contents);
#pragma warning( pop )
va_end( argList );
// spam formated string to listeners
{ static int lock = 0;
assert( lock == 0 ); // One of the logging functions generated a log message
lock = 1; // protect against recursion
{ pf_reporting_callback *beg = g_error_report_callbacks.contents;
size_t cnt = g_error_report_callbacks.count;
char *buffer = vbuf.contents;
pf_reporting_callback *cur = beg + cnt;
while( cur-- > beg )
if(cur)
(*cur)(buffer);
}
lock = 0;
}
}
LeaveCriticalSection( _get_reporting_critical_section() );
// cleanup and shutdown
Shutdown_Hard_Nonblocking(1);
}
void warning(const char* fmt, ...)
{ EnterCriticalSection( _get_reporting_critical_section() );
{ static const char prefix[] = "--- WARNING: ";
size_t len;
va_list argList;
static vector_char vbuf = VECTOR_EMPTY;
static int lock = 0;
assert( lock == 0 ); // One of the logging functions generated a log message
lock = 1;
// render formated string
va_start( argList, fmt );
len = sizeof(prefix) + _vscprintf(fmt,argList) + 1+1024;
vector_char_request( &vbuf, len );
memset ( vbuf.contents, 0, len );
#pragma warning( push )
#pragma warning( disable:4996 )
#pragma warning( disable:4995 )
sprintf ( vbuf.contents, prefix );
vsprintf( vbuf.contents+sizeof(prefix)-1, fmt, argList);
timestamp(vbuf.contents);
#pragma warning( pop )
va_end( argList );
// spam formated string to listeners
{ pf_reporting_callback *beg = g_warning_report_callbacks.contents;
size_t cnt = g_warning_report_callbacks.count;
char *buffer = vbuf.contents;
pf_reporting_callback *cur = beg + cnt;
while( cur-- > beg )
if(cur)
(*cur)(buffer);
}
lock = 0;
}
LeaveCriticalSection( _get_reporting_critical_section() );
}
void debug(const char* fmt, ...)
{ EnterCriticalSection( _get_reporting_critical_section() );
{ size_t len;
va_list argList;
static vector_char vbuf = VECTOR_EMPTY;
static int lock = 0;
assert( lock == 0 ); // One of the logging callback functions generated a log message (not kosher).
lock = 1; // The "lock" flag blocks recursion. Note that the recursion causes an exit.
// render formated string
va_start( argList, fmt );
len = _vscprintf(fmt,argList) + 1+1024;
vector_char_request( &vbuf, len );
memset ( vbuf.contents, 0, len );
#pragma warning( push )
#pragma warning( disable:4996 )
#pragma warning( disable:4995 )
vsprintf( vbuf.contents, fmt, argList);
timestamp(vbuf.contents);
#pragma warning( pop )
va_end( argList );
// spam formated string to listeners
{ pf_reporting_callback *beg = g_debug_report_callbacks.contents;
size_t cnt = g_debug_report_callbacks.count;
char *buffer = vbuf.contents;
pf_reporting_callback *cur = beg + cnt;
while( cur-- > beg )
if(cur)
(*cur)(buffer);
}
lock = 0;
}
LeaveCriticalSection( _get_reporting_critical_section() );
}
//
// Memory
//
void *Guarded_Malloc( size_t nelem, const char *msg )
{ void *item = malloc( nelem );
if( !item )
error("Could not allocate memory.\n%s\n",msg);
return item;
}
void *Guarded_Calloc( size_t nelem, size_t bytes_per_elem, const char *msg )
{ void *item = calloc( nelem, bytes_per_elem );
if( !item )
error("Could not allocate memory.\n%s\n",msg);
return item;
}
void Guarded_Realloc( void **item, size_t nelem, const char *msg )
{ void *it = *item;
assert(item);
if( !it )
it = malloc( nelem );
else
it = realloc( it, nelem );
if( !it )
error("Could not reallocate memory.\n%s\n",msg);
*item = it;
}
void RequestStorage( void** array, size_t *nelem, size_t request, size_t bytes_per_elem, const char *msg )
{ size_t n = request+1;
if( n <= *nelem ) return;
*nelem = (size_t) (1.25 * n + 64 );
#ifdef DEBUG_REQUEST_STORAGE
debug("REQUEST %7d bytes (%7d items) above current %7d bytes by %s\n",request * bytes_per_elem, request, *nelem * bytes_per_elem, msg);
#endif
Guarded_Realloc( array, *nelem * bytes_per_elem, "Resize" );
}
void RequestStorageLog2( void** array, size_t *nelem, size_t request, size_t bytes_per_elem, const char *msg )
{ size_t n = request+1;
if( n <= *nelem ) return;
*nelem = _next_pow2_size_t(n);
#ifdef DEBUG_REQUEST_STORAGE
debug("REQUEST %7d bytes (%7d items) above current %7d bytes by %s\n",request * bytes_per_elem, request, *nelem * bytes_per_elem, msg);
#endif
Guarded_Realloc( array, *nelem * bytes_per_elem, "Resize" );
}
//
// Container types
//
TYPE_VECTOR_DEFINE(char);
TYPE_VECTOR_DEFINE(u8);
TYPE_VECTOR_DEFINE(u16);
TYPE_VECTOR_DEFINE(u32);
TYPE_VECTOR_DEFINE(u64);
TYPE_VECTOR_DEFINE(size_t);
TYPE_VECTOR_DEFINE(i8);
TYPE_VECTOR_DEFINE(i16);
TYPE_VECTOR_DEFINE(i32);
TYPE_VECTOR_DEFINE(i64);
TYPE_VECTOR_DEFINE(f32);
TYPE_VECTOR_DEFINE(f64);