/
vrpn_Shared.C
1449 lines (1260 loc) · 44 KB
/
vrpn_Shared.C
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <math.h> // for floor, fmod
#include <stddef.h> // for size_t
#include <stdio.h> // for fprintf() and such
#include "vrpn_Shared.h"
#ifdef MSVC
// Don't tell us about strcpy being dangerous.
#pragma warning ( disable : 4996)
#endif
#if defined(__APPLE__) || defined(__ANDROID__)
#include <unistd.h>
#endif
#if !( defined(_WIN32) && defined(VRPN_USE_WINSOCK_SOCKETS) )
#include <sys/select.h> // for select
#include <netinet/in.h> // for htonl, htons
#endif
#define CHECK(a) if (a == -1) return -1
// perform normalization of a timeval
// XXX this still needs to be checked for errors if the timeval
// or the rate is negative
#define TIMEVAL_NORMALIZE(tiva) { \
const long div_77777 = (tiva.tv_usec / 1000000); \
tiva.tv_sec += div_77777; \
tiva.tv_usec -= (div_77777 * 1000000); \
}
timeval vrpn_TimevalNormalize( const timeval & in_tv )
{
timeval out_tv = in_tv;
TIMEVAL_NORMALIZE(out_tv);
return out_tv;
}
// Calcs the sum of tv1 and tv2. Returns the sum in a timeval struct.
// Calcs negative times properly, with the appropriate sign on both tv_sec
// and tv_usec (these signs will match unless one of them is 0).
// NOTE: both abs(tv_usec)'s must be < 1000000 (ie, normal timeval format)
timeval vrpn_TimevalSum( const timeval& tv1, const timeval& tv2 )
{
timeval tvSum=tv1;
tvSum.tv_sec += tv2.tv_sec;
tvSum.tv_usec += tv2.tv_usec;
// do borrows, etc to get the time the way i want it: both signs the same,
// and abs(usec) less than 1e6
if (tvSum.tv_sec>0) {
if (tvSum.tv_usec<0) {
tvSum.tv_sec--;
tvSum.tv_usec += 1000000;
} else if (tvSum.tv_usec >= 1000000) {
tvSum.tv_sec++;
tvSum.tv_usec -= 1000000;
}
} else if (tvSum.tv_sec<0) {
if (tvSum.tv_usec>0) {
tvSum.tv_sec++;
tvSum.tv_usec -= 1000000;
} else if (tvSum.tv_usec <= -1000000) {
tvSum.tv_sec--;
tvSum.tv_usec += 1000000;
}
} else {
// == 0, so just adjust usec
if (tvSum.tv_usec >= 1000000) {
tvSum.tv_sec++;
tvSum.tv_usec -= 1000000;
} else if (tvSum.tv_usec <= -1000000) {
tvSum.tv_sec--;
tvSum.tv_usec += 1000000;
}
}
return tvSum;
}
// Calcs the diff between tv1 and tv2. Returns the diff in a timeval struct.
// Calcs negative times properly, with the appropriate sign on both tv_sec
// and tv_usec (these signs will match unless one of them is 0)
timeval vrpn_TimevalDiff( const timeval& tv1, const timeval& tv2 )
{
timeval tv;
tv.tv_sec = -tv2.tv_sec;
tv.tv_usec = -tv2.tv_usec;
return vrpn_TimevalSum( tv1, tv );
}
timeval vrpn_TimevalScale (const timeval & tv, double scale)
{
timeval result;
result.tv_sec = (long)( tv.tv_sec * scale );
result.tv_usec = (long)( tv.tv_usec * scale
+ fmod(tv.tv_sec * scale, 1.0) * 1000000.0 );
TIMEVAL_NORMALIZE(result);
return result;
}
// returns 1 if tv1 is greater than tv2; 0 otherwise
bool vrpn_TimevalGreater (const timeval & tv1, const timeval & tv2)
{
if (tv1.tv_sec > tv2.tv_sec) return 1;
if ((tv1.tv_sec == tv2.tv_sec) &&
(tv1.tv_usec > tv2.tv_usec)) return 1;
return 0;
}
// return 1 if tv1 is equal to tv2; 0 otherwise
bool vrpn_TimevalEqual( const timeval& tv1, const timeval& tv2 )
{
if( tv1.tv_sec == tv2.tv_sec && tv1.tv_usec == tv2.tv_usec )
return true;
else return false;
}
unsigned long vrpn_TimevalDuration(struct timeval endT, struct timeval startT)
{
return (endT.tv_usec - startT.tv_usec) +
1000000L * (endT.tv_sec - startT.tv_sec);
}
double vrpn_TimevalMsecs( const timeval& tv )
{
return tv.tv_sec*1000.0 + tv.tv_usec/1000.0;
}
timeval vrpn_MsecsTimeval( const double dMsecs )
{
timeval tv;
tv.tv_sec = (long) floor(dMsecs/1000.0);
tv.tv_usec = (long) ((dMsecs/1000.0 - tv.tv_sec)*1e6);
return tv;
}
// Sleep for dMsecs milliseconds, freeing up the processor while you
// are doing so.
void vrpn_SleepMsecs( double dMsecs )
{
#if defined(_WIN32)
Sleep((DWORD)dMsecs);
#else
timeval timeout;
// Convert milliseconds to seconds
timeout.tv_sec = (int)(dMsecs / 1000.0);
// Subtract of whole number of seconds
dMsecs -= timeout.tv_sec * 1000;
// Convert remaining milliseconds to microsec
timeout.tv_usec = (int)(dMsecs * 1000);
// A select() with NULL file descriptors acts like a microsecond
// timer.
select(0, 0, 0, 0, & timeout); // wait for that long;
#endif
}
// convert vrpn_float64 to/from network order
// I have chosen big endian as the network order for vrpn_float64
// to match the standard for htons() and htonl().
// NOTE: There is an added complexity when we are using an ARM
// processor in mixed-endian mode for the doubles, whereby we need
// to not just swap all of the bytes but also swap the two 4-byte
// words to get things in the right order.
#if defined (__arm__)
#include <endian.h>
#endif
vrpn_float64 htond( vrpn_float64 d )
{
if (!vrpn_big_endian) {
vrpn_float64 dSwapped;
char *pchSwapped= (char *)&dSwapped;
char *pchOrig= (char *)&d;
// swap to big-endian order.
unsigned i;
for(i=0;i<sizeof(vrpn_float64);i++) {
pchSwapped[i]=pchOrig[sizeof(vrpn_float64)-i-1];
}
#if defined (__arm__) && !defined (__ANDROID__)
// On ARM processor, see if we're in mixed mode. If so,
// we need to swap the two words after doing the total
// swap of bytes.
#if __FLOAT_WORD_ORDER != __BYTE_ORDER
{
/* Fixup mixed endian floating point machines */
vrpn_uint32 *pwSwapped = (vrpn_uint32 *)&dSwapped;
vrpn_uint32 scratch = pwSwapped[0];
pwSwapped[0] = pwSwapped[1];
pwSwapped[1] = scratch;
}
#endif
#endif
return dSwapped;
} else {
return d;
}
}
// they are their own inverses, so ...
vrpn_float64 ntohd (vrpn_float64 d)
{
return htond(d);
}
/** Utility routine for placing a timeval struct into a buffer that
is to be sent as a message. Handles packing into an unaligned
buffer (though this should not be done). Advances the insertPt
pointer to just after newly-inserted value. Decreases the buflen
(space remaining) by the length of the value. Returns zero on
success and -1 on failure.
Part of a family of routines that buffer different VRPN types
based on their type (vrpn_buffer is overloaded based on the third
parameter type). These routines handle byte-swapping to the
VRPN standard wire protocol.
*/
VRPN_API int vrpn_buffer (char ** insertPt, vrpn_int32 * buflen, const timeval t)
{
vrpn_int32 sec, usec;
// tv_sec and usec are 64 bits on some architectures, but we
// define them as 32 bit for network transmission
sec = t.tv_sec;
usec = t.tv_usec;
if (vrpn_buffer(insertPt, buflen, sec)) return -1;
return vrpn_buffer(insertPt, buflen, usec);
}
/** Utility routine for placing a character string of given length
into a buffer that is to be sent as a message. Handles packing into
an unaligned buffer (though this should not be done). Advances the insertPt
pointer to just after newly-inserted value. Decreases the buflen
(space remaining) by the length of the value. Returns zero on
success and -1 on failure.
Part of a family of routines that buffer different VRPN types
based on their type (vrpn_buffer is overloaded based on the third
parameter type). These routines handle byte-swapping to the
VRPN standard wire protocol.
If the length is specified as -1, then the string will be assumed to
be NULL-terminated and will be copied using the string-copy routines.
*/
VRPN_API int vrpn_buffer (char ** insertPt, vrpn_int32 * buflen,
const char * string, vrpn_int32 length)
{
if (length > *buflen) {
fprintf(stderr, "vrpn_buffer: buffer not long enough for string.\n");
return -1;
}
if (length == -1) {
size_t len = strlen(string)+1; // +1 for the NULL terminating character
if (len > (unsigned)*buflen) {
fprintf(stderr, "vrpn_buffer: buffer not long enough for string.\n");
return -1;
}
strcpy(*insertPt, string);
*insertPt += len;
*buflen -= static_cast<vrpn_int32>(len);
} else {
memcpy(*insertPt, string, length);
*insertPt += length;
*buflen -= length;
}
return 0;
}
/** Utility routine for taking a struct timeval from a buffer that
was sent as a message. Handles unpacking from an
unaligned buffer, because people did this anyway. Advances the reading
pointer to just after newly-read value. Assumes that the
buffer holds a complete value. Returns zero on success and -1 on failure.
Part of a family of routines that unbuffer different VRPN types
based on their type (vrpn_buffer is overloaded based on the third
parameter type). These routines handle byte-swapping to and from
the VRPN defined wire protocol.
*/
VRPN_API int vrpn_unbuffer (const char ** buffer, timeval * t)
{
vrpn_int32 sec, usec;
CHECK(vrpn_unbuffer(buffer, &sec));
CHECK(vrpn_unbuffer(buffer, &usec));
t->tv_sec = sec;
t->tv_usec = usec;
return 0;
}
/** Utility routine for taking a string of specified length from a buffer that
was sent as a message. Does NOT handle unpacking from an
unaligned buffer, because the semantics of VRPN require
message buffers and the values in them to be aligned, in order to
reduce the amount of copying that goes on. Advances the read
pointer to just after newly-read value. Assumes that the
buffer holds a complete value. Returns zero on success and -1 on failure.
Part of a family of routines that unbuffer different VRPN types
based on their type (vrpn_buffer is overloaded based on the third
parameter type). These routines handle byte-swapping to and from
the VRPN defined wire protocol.
If the length is specified as less than zero, then the string will be assumed to
be NULL-terminated and will be read using the string-copy routines with a
length that is at most the magnitude of the number (-16 means at most 16). NEVER
use this on a string that was packed with other than the NULL-terminating
condition, since embedded NULL characters will ruin the argument parsing
for any later arguments in the message.
*/
VRPN_API int vrpn_unbuffer (const char ** buffer, char * string, vrpn_int32 length)
{
if (!string) return -1;
if (length < 0) {
// Read the string up to maximum length, then check to make sure we
// found the null-terminator in the length we read.
size_t max_len = static_cast<size_t>(-length);
strncpy(string, *buffer, max_len);
size_t i;
bool found = false;
for (i = 0; i < max_len; i++) {
if ( string[i] == '\0' ) {
found = true;
break;
}
}
if (!found) {
return -1;
}
*buffer += strlen(*buffer)+1; // +1 for NULL terminating character
} else {
memcpy(string, *buffer, length);
*buffer += length;
}
return 0;
}
///////////////////////////////////////////////////////////////
// More accurate gettimeofday() on some Windows operating systems
// and machines can be gotten by using the Performance Counter
// on the CPU. This doesn't seem to work in NT/2000 for some
// computers, so the code to do it is #defined out by default.
// To put it back back, #define VRPN_UNSAFE_WINDOWS_CLOCK and
// the following code will use the performance counter (which it
// takes a second to calibrate at program start-up).
///////////////////////////////////////////////////////////////
#ifndef VRPN_UNSAFE_WINDOWS_CLOCK
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <math.h> // for floor, fmod
#pragma optimize("", on)
#ifdef _WIN32
void get_time_using_GetLocalTime(unsigned long &sec, unsigned long &usec)
{
SYSTEMTIME stime; // System time in funky structure
FILETIME ftime; // Time in 100-nsec intervals since Jan 1 1601
LARGE_INTEGER tics; // ftime stored into a 64-bit quantity
GetLocalTime(&stime);
SystemTimeToFileTime(&stime, &ftime);
// Copy the data into a structure that can be treated as a 64-bit integer
tics.HighPart = ftime.dwHighDateTime;
tics.LowPart = ftime.dwLowDateTime;
// Convert the 64-bit time into seconds and microseconds since July 1 1601
sec = (long)( tics.QuadPart / 10000000L );
usec = (long)( ( tics.QuadPart - ( ((LONGLONG)(sec)) * 10000000L ) ) / 10 );
// Translate the time to be based on January 1, 1970 (_ftime base)
// The offset here is gotten by using the "time_test" program to report the
// difference in seconds between the two clocks.
sec -= 3054524608;
}
#endif
///////////////////////////////////////////////////////////////
// Although VC++ doesn't include a gettimeofday
// call, Cygnus Solutions Cygwin32 environment does,
// so this is not used when compiling with gcc under WIN32.
// XXX Note that the cygwin one was wrong in an earlier
// version. It is claimed that they have fixed it now, but
// better check.
///////////////////////////////////////////////////////////////
int vrpn_gettimeofday(timeval *tp, void *voidp)
{
#ifndef _STRUCT_TIMEZONE
#define _STRUCT_TIMEZONE
/* from HP-UX */
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of dst correction */
};
#endif
struct timezone *tzp = (struct timezone *)voidp;
if (tp != NULL) {
#ifdef _WIN32_WCE
unsigned long sec, usec;
get_time_using_GetLocalTime(sec, usec);
tp->tv_sec = sec;
tp->tv_usec = usec;
#else
struct _timeb t;
_ftime(&t);
tp->tv_sec = t.time;
tp->tv_usec = (long)t. millitm * 1000;
#endif
}
if (tzp != NULL) {
TIME_ZONE_INFORMATION tz;
GetTimeZoneInformation(&tz);
tzp->tz_minuteswest = tz.Bias ;
tzp->tz_dsttime = (tz.StandardBias != tz.Bias);
}
return 0;
}
#endif //defined(_WIN32)
#else // In the case that VRPN_UNSAFE_WINDOWS_CLOCK is defined
// Although VC++ doesn't include a gettimeofday
// call, Cygnus Solutions Cygwin32 environment does.
// XXX AND ITS WRONG in the current release 10/11/99, version b20.1
// They claim it will be fixed in the next release, version b21
// so until then, we will make it right using our solution.
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <math.h> // for floor, fmod
// utility routines to read the pentium time stamp counter
// QueryPerfCounter drifts too much -- others have documented this
// problem on the net
// This is all based on code extracted from the UNC hiball tracker cib lib
// 200 mhz pentium default -- we change this based on our calibration
static __int64 VRPN_CLOCK_FREQ = 200000000;
// Helium to histidine
// __int64 FREQUENCY = 199434500;
// tori -- but queryperfcounter returns this for us
// __int64 FREQUENCY = 198670000;
// Read Time Stamp Counter
#define rdtsc(li) { _asm _emit 0x0f \
_asm _emit 0x31 \
_asm mov li.LowPart, eax \
_asm mov li.HighPart, edx \
}
/*
* calculate the time stamp counter register frequency (clock freq)
*/
#ifndef VRPN_WINDOWS_CLOCK_V2
#pragma optimize("",off)
static int vrpn_AdjustFrequency(void)
{
const int loops = 2;
const int tPerLoop = 500; // milliseconds for Sleep()
fprintf(stderr,"vrpn vrpn_gettimeofday: determining clock frequency...");
LARGE_INTEGER startperf, endperf;
LARGE_INTEGER perffreq;
// See if the hardware supports the high-resolution performance counter.
// If so, get the frequency of it. If not, we can't use it and so return
// -1.
if (QueryPerformanceFrequency( &perffreq ) == 0) {
return -1;
}
// don't optimize away these variables
double sum = 0;
volatile LARGE_INTEGER liStart, liEnd;
DWORD dwPriorityClass=GetPriorityClass(GetCurrentProcess());
int iThreadPriority=GetThreadPriority(GetCurrentThread());
SetPriorityClass( GetCurrentProcess() , REALTIME_PRIORITY_CLASS );
SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL );
// pull all into cache and do rough test to see if tsc and perf counter
// are one and the same
rdtsc( liStart );
QueryPerformanceCounter( &startperf );
Sleep(100);
rdtsc( liEnd );
QueryPerformanceCounter( &endperf );
double freq = perffreq.QuadPart * (liEnd.QuadPart - liStart.QuadPart) /
((double)(endperf.QuadPart - startperf.QuadPart));
if (fabs(perffreq.QuadPart - freq) < 0.05*freq) {
VRPN_CLOCK_FREQ = (__int64) perffreq.QuadPart;
fprintf(stderr,"\nvrpn vrpn_gettimeofday: perf clock is tsc -- using perf clock freq ( %lf MHz)\n", perffreq.QuadPart/1e6);
SetPriorityClass( GetCurrentProcess() , dwPriorityClass );
SetThreadPriority( GetCurrentThread(), iThreadPriority );
return 0;
}
// either tcs and perf clock are not the same, or we could not
// tell accurately enough with the short test. either way we now
// need an accurate frequency measure, so ...
fprintf(stderr," (this will take %lf seconds)...\n", loops*tPerLoop/1000.0);
for (int j = 0; j < loops; j++) {
rdtsc( liStart );
QueryPerformanceCounter( &startperf );
Sleep(tPerLoop);
rdtsc( liEnd );
QueryPerformanceCounter( &endperf );
// perf counter timer ran for one call to Query and one call to
// tcs read in addition to the time between the tsc readings
// tcs read did the same
// endperf - startperf / perf freq = time between perf queries
// endtsc - starttsc = clock ticks between perf queries
// sum += (endtsc - starttsc) / ((double)(endperf - startperf)/perffreq);
sum += perffreq.QuadPart * (liEnd.QuadPart - liStart.QuadPart) /
((double)(endperf.QuadPart - startperf.QuadPart));
}
SetPriorityClass( GetCurrentProcess() , dwPriorityClass );
SetThreadPriority( GetCurrentThread(), iThreadPriority );
// might want last, not sum -- just get into cache and run
freq = (sum/loops);
// if we are on a uniprocessor system, then use the freq estimate
// This used to check against a 200 mhz assumed clock, but now
// we assume the routine works and trust the result.
// if (fabs(freq - VRPN_CLOCK_FREQ) > 0.05 * VRPN_CLOCK_FREQ) {
// cerr << "vrpn vrpn_gettimeofday: measured freq is " << freq/1e6
// << " MHz - DOES NOT MATCH" << endl;
// return -1;
// }
// if we are in a system where the perf clock is the tsc, then use the
// rate the perf clock returns (or rather, if the freq we measure is
// approx the perf clock freq).
if (fabs(perffreq.QuadPart - freq) < 0.05*freq) {
VRPN_CLOCK_FREQ = perffreq.QuadPart;
fprintf(stderr, "vrpn vrpn_gettimeofday: perf clock is tsc -- using perf clock freq ( %lf MHz)\n", perffreq.QuadPart/1e6);
} else {
fprintf(stderr, "vrpn vrpn_gettimeofday: adjusted clock freq to measured freq ( %lf MHz )\n", freq/1e6);
}
VRPN_CLOCK_FREQ = (__int64) freq;
return 0;
}
#pragma optimize("", on)
#endif
// The pc has no gettimeofday call, and the closest thing to it is _ftime.
// _ftime, however, has only about 6 ms resolution, so we use the peformance
// as an offset from a base time which is established by a call to by _ftime.
// The first call to vrpn_gettimeofday will establish a new time frame
// on which all later calls will be based. This means that the time returned
// by vrpn_gettimeofday will not always match _ftime (even at _ftime's resolution),
// but it will be consistent across all vrpn_gettimeofday calls.
///////////////////////////////////////////////////////////////
// Although VC++ doesn't include a gettimeofday
// call, Cygnus Solutions Cygwin32 environment does,
// so this is not used when compiling with gcc under WIN32
// XXX AND ITS WRONG in the current release 10/11/99
// They claim it will be fixed in the next release,
// so until then, we will make it right using our solution.
///////////////////////////////////////////////////////////////
#ifndef VRPN_WINDOWS_CLOCK_V2
int vrpn_gettimeofday(timeval *tp, void *voidp)
{
static int fFirst=1;
static int fHasPerfCounter=1;
static struct _timeb tbInit;
static LARGE_INTEGER liInit;
static LARGE_INTEGER liNow;
static LARGE_INTEGER liDiff;
timeval tvDiff;
#ifndef _STRUCT_TIMEZONE
#define _STRUCT_TIMEZONE
/* from HP-UX */
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of dst correction */
};
#endif
struct timezone *tzp = (struct timezone *)voidp;
if (!fHasPerfCounter) {
_ftime(&tbInit);
tp->tv_sec = tbInit.time;
tp->tv_usec = tbInit.millitm*1000;
return 0;
}
if (fFirst) {
LARGE_INTEGER liTemp;
// establish a time base
fFirst=0;
// Check to see if we are on a Windows NT machine (as opposed to a
// Windows 95/98 machine). If we are not, then use the _ftime code
// because the hi-perf clock does not work under Windows 98SE on my
// laptop, although the query for one seems to indicate that it is
// available.
{ OSVERSIONINFO osvi;
memset(&osvi, 0, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
if (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) {
fprintf(stderr, "\nvrpn_gettimeofday: disabling hi performance clock on non-NT system. "
"Defaulting to _ftime (~6 ms resolution) ...\n");
fHasPerfCounter=0;
vrpn_gettimeofday( tp, tzp );
return 0;
}
}
// check that hi-perf clock is available
if ( !(fHasPerfCounter = QueryPerformanceFrequency( &liTemp )) ) {
fprintf(stderr, "\nvrpn_gettimeofday: no hi performance clock available. "
"Defaulting to _ftime (~6 ms resolution) ...\n");
fHasPerfCounter=0;
vrpn_gettimeofday( tp, tzp );
return 0;
}
if (vrpn_AdjustFrequency()<0) {
fprintf(stderr, "\nvrpn_gettimeofday: can't verify clock frequency. "
"Defaulting to _ftime (~6 ms resolution) ...\n");
fHasPerfCounter=0;
vrpn_gettimeofday( tp, tzp );
return 0;
}
// get current time
// We assume this machine has a time stamp counter register --
// I don't know of an easy way to check for this
rdtsc( liInit );
_ftime(&tbInit);
// we now consider it to be exactly the time _ftime returned
// (beyond the resolution of _ftime, down to the perfCounter res)
}
// now do the regular get time call to get the current time
rdtsc( liNow );
// find offset from initial value
liDiff.QuadPart = liNow.QuadPart - liInit.QuadPart;
tvDiff.tv_sec = (long) ( liDiff.QuadPart / VRPN_CLOCK_FREQ );
tvDiff.tv_usec = (long)(1e6*((liDiff.QuadPart-VRPN_CLOCK_FREQ
*tvDiff.tv_sec)
/ (double) VRPN_CLOCK_FREQ) );
// pack the value and clean it up
tp->tv_sec = tbInit.time + tvDiff.tv_sec;
tp->tv_usec = tbInit.millitm*1000 + tvDiff.tv_usec;
while (tp->tv_usec >= 1000000) {
tp->tv_sec++;
tp->tv_usec -= 1000000;
}
return 0;
}
#else //defined(VRPN_WINDOWS_CLOCK_V2)
void get_time_using_GetLocalTime(unsigned long &sec, unsigned long &usec)
{
static LARGE_INTEGER first_count = { 0, 0 };
static unsigned long first_sec, first_usec;
static LARGE_INTEGER perf_freq; //< Frequency of the performance counter.
SYSTEMTIME stime; // System time in funky structure
FILETIME ftime; // Time in 100-nsec intervals since Jan 1 1601
LARGE_INTEGER tics; // ftime stored into a 64-bit quantity
LARGE_INTEGER perf_counter;
// The first_count value will be zero only the first time through; we
// rely on this to set up the structures needed to interpret the data
// that we get from querying the performance counter.
if (first_count.QuadPart == 0) {
QueryPerformanceCounter( &first_count );
// Find out how fast the performance counter runs. Store this for later runs.
QueryPerformanceFrequency( &perf_freq );
// Find out what time it is in a Windows structure.
GetLocalTime(&stime);
SystemTimeToFileTime(&stime, &ftime);
// Copy the data into a structure that can be treated as a 64-bit integer
tics.HighPart = ftime.dwHighDateTime;
tics.LowPart = ftime.dwLowDateTime;
// Convert the 64-bit time into seconds and microseconds since July 1 1601
sec = (long)( tics.QuadPart / 10000000L );
usec = (long)( ( tics.QuadPart - ( ((LONGLONG)(sec)) * 10000000L ) ) / 10 );
first_sec = sec;
first_usec = usec;
} else {
QueryPerformanceCounter( &perf_counter );
if ( perf_counter.QuadPart >= first_count.QuadPart ) {
perf_counter.QuadPart = perf_counter.QuadPart - first_count.QuadPart;
} else {
// Take care of the case when the counter rolls over.
perf_counter.QuadPart = 0x7fffffffffffffffLL - first_count.QuadPart + perf_counter.QuadPart;
}
// Reinterpret the performance counter into seconds and microseconds
// by dividing by the performance counter. Microseconds is placed
// into perf_counter by subtracting the seconds value out, then
// multiplying by 1 million and re-dividing by the performance counter.
sec = (long)( perf_counter.QuadPart / perf_freq.QuadPart );
perf_counter.QuadPart -= perf_freq.QuadPart * sec;
perf_counter.QuadPart *= 1000000L; //< Turn microseconds into seconds
usec = first_usec + (long)( perf_counter.QuadPart / perf_freq.QuadPart );
sec += first_sec;
// Make sure that we've not got more than a million microseconds.
// If so, then shift it into seconds. We don't expect it to be above
// more than 1 million because we added two things, each of which were
// less than 1 million.
if (usec > 1000000L) {
usec -= 1000000L;
sec++;
}
}
// Translate the time to be based on January 1, 1970 (_ftime base)
// The offset here is gotten by using the "time_test" program to report the
// difference in seconds between the two clocks.
sec -= 3054524608L;
}
int vrpn_gettimeofday(timeval *tp, void *voidp)
{
#ifndef _STRUCT_TIMEZONE
#define _STRUCT_TIMEZONE
/* from HP-UX */
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of dst correction */
};
#endif
struct timezone *tzp = (struct timezone *)voidp;
unsigned long sec,usec;
get_time_using_GetLocalTime(sec,usec);
tp->tv_sec = sec;
tp->tv_usec = usec;
if (tzp != NULL) {
TIME_ZONE_INFORMATION tz;
GetTimeZoneInformation(&tz);
tzp->tz_minuteswest = tz.Bias ;
tzp->tz_dsttime = (tz.StandardBias != tz.Bias);
}
return 0;
}
#endif //defined(VRPN_WINDOWS_CLOCK_V2)
#endif //defined(_WIN32)
// do the calibration before the program ever starts up
static timeval __tv;
static int __iTrash = vrpn_gettimeofday(&__tv, (struct timezone *)NULL);
#endif // VRPN_UNSAFE_WINDOWS_CLOCK
#include <stdio.h> // for fprintf, stderr, perror, etc
#include <string.h> // for memcpy, strlen, strcpy, etc
#ifndef _WIN32
#include <errno.h> // for EAGAIN, errno
#include <signal.h> // for pthread_kill, SIGKILL
#endif
#define ALL_ASSERT(exp, msg) if(!(exp)){ fprintf(stderr, "\nAssertion failed! \n %s (%s, %s)\n", msg, __FILE__, __LINE__); }
// init all fields in init()
vrpn_Semaphore::vrpn_Semaphore( int cNumResources ) :
cResources(cNumResources)
{
init();
}
// create a new internal structure for the semaphore
// (binary copy is not ok)
// This does not copy the state of the semaphore
vrpn_Semaphore::vrpn_Semaphore( const vrpn_Semaphore& s ) :
cResources(s.cResources)
{
init();
}
bool vrpn_Semaphore::init() {
#ifdef sgi
if (vrpn_Semaphore::ppaArena==NULL) {
vrpn_Semaphore::allocArena();
}
if (cResources==1) {
fUsingLock=true;
ps=NULL;
// use lock instead of semaphore
if ((l = usnewlock(vrpn_Semaphore::ppaArena)) == NULL) {
fprintf(stderr,"vrpn_Semaphore::vrpn_Semaphore: error allocating lock from arena.\n");
return false;
}
} else {
fUsingLock=false;
l=NULL;
if ((ps = usnewsema(vrpn_Semaphore::ppaArena, cResources)) == NULL) {
fprintf(stderr,"vrpn_Semaphore::vrpn_Semaphore: error allocating semaphore from arena.\n");
return false;
}
}
#elif defined(_WIN32)
// args are security, initial count, max count, and name
// TCH 20 Feb 2001 - Make the PC behavior closer to the SGI behavior.
int numMax = cResources;
if (numMax < 1) {
numMax = 1;
}
hSemaphore = CreateSemaphore(NULL, cResources, numMax, NULL);
if (!hSemaphore) {
// get error info from windows (from FormatMessage help page)
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
(LPTSTR) &lpMsgBuf, 0, NULL );
fprintf(stderr,"vrpn_Semaphore::vrpn_Semaphore: error creating semaphore, "
"WIN32 CreateSemaphore call caused the following error: %s\n", (LPTSTR) lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return false;
}
#elif defined(__APPLE__)
// We need to use sem_open on the mac because sem_init is not implemented
int numMax = cResources;
if (numMax < 1) {
numMax = 1;
}
char *tempname = new char[100];
sprintf(tempname, "/tmp/vrpn_sem.XXXXXXX");
semaphore = sem_open(mktemp(tempname), O_CREAT, 0600, numMax);
if (semaphore == SEM_FAILED) {
perror("vrpn_Semaphore::vrpn_Semaphore: error opening semaphore");
delete [] tempname;
return false;
}
delete [] tempname;
#else
// Posix threads are the default.
// We use sem_init on linux (instead of sem_open).
int numMax = cResources;
if (numMax < 1) {
numMax = 1;
}
semaphore = new sem_t;
if (sem_init(semaphore, 0, numMax) != 0) {
perror("vrpn_Semaphore::vrpn_Semaphore: error initializing semaphore");
return false;
}
#endif
return true;
}
bool vrpn_Semaphore::destroy() {
#ifdef sgi
if (fUsingLock) {
usfreelock( l, vrpn_Semaphore::ppaArena );
} else {
usfreesema( ps, vrpn_Semaphore::ppaArena );
}
#elif defined(_WIN32)
if (!CloseHandle(hSemaphore)) {
// get error info from windows (from FormatMessage help page)
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
(LPTSTR) &lpMsgBuf, 0, NULL );
fprintf(stderr, "vrpn_Semaphore::destroy: error destroying semaphore, "
"WIN32 CloseHandle call caused the following error: %s\n", (LPTSTR) lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return false;
}
#else
// Posix threads are the default.
#ifdef __APPLE__
if (sem_close(semaphore) != 0) {
perror("vrpn_Semaphore::destroy: error destroying semaphore.");
return false;
}
#else
if (sem_destroy(semaphore) != 0) {
fprintf(stderr, "vrpn_Semaphore::destroy: error destroying semaphore.\n");
return false;
}
#endif
semaphore = NULL;
#endif
return true;
}
vrpn_Semaphore::~vrpn_Semaphore() {
if (!destroy()) {
fprintf(stderr, "vrpn_Semaphore::~vrpn_Semaphore: error destroying semaphore.\n");
}
}
// routine to reset it
bool vrpn_Semaphore::reset( int cNumResources ) {
cResources = cNumResources;
// Destroy the old semaphore and then create a new one with the correct
// value.
if (!destroy()) {
fprintf(stderr, "vrpn_Semaphore::reset: error destroying semaphore.\n");
return false;
}
if (!init()) {
fprintf(stderr, "vrpn_Semaphore::reset: error initializing semaphore.\n");
return false;
}
return true;
}
// routines to use it (p blocks, cond p does not)
// 1 on success, -1 fail
int vrpn_Semaphore::p() {
#ifdef sgi
if (fUsingLock) {
if (ussetlock(l)!=1) {
perror("vrpn_Semaphore::p: ussetlock:");
return -1;
}
} else {
if (uspsema(ps)!=1) {
perror("vrpn_Semaphore::p: uspsema:");
return -1;
}
}
#elif defined(_WIN32)
switch (WaitForSingleObject(hSemaphore, INFINITE)) {
case WAIT_OBJECT_0:
// got the resource