forked from efroemling/bombsquad-remote-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoteViewController.mm
1955 lines (1608 loc) · 61.7 KB
/
RemoteViewController.mm
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
#import "RemoteViewController.h"
#include <arpa/inet.h>
#include <QuartzCore/CAAnimation.h>
#import "AppController.h"
#include <fcntl.h>
#include <iostream>
using namespace std;
RemoteViewController* gRemoteViewController = nil;
#define BS_REMOTE_PROTOCOL_VERSION 121
// how much larger than the button/dpad areas we should count touch events in
#define BUTTON_BUFFER 2.0
#define DPAD_BUFFER 1.2
#define DPAD_DRAG_DIST 0.25 // how far we must be from the dpad before it follows us
#define DPAD_FULL_SPEED_DIST 0.35
#define DPAD_FULL_SPEED_DIST_FLOATING 0.15
#define DPAD_FULL_SPEED_DIST_TILT 0.1
#define DPAD_NEUTRAL_Y 0
enum BSRemoteError {
BS_REMOTE_ERROR_VERSION_MISMATCH,
BS_REMOTE_ERROR_GAME_SHUTTING_DOWN,
BS_REMOTE_ERROR_NOT_ACCEPTING_CONNECTIONS,
BS_REMOTE_ERROR_NOT_CONNECTED
};
// component masks for 16 bit state values
enum BSRemoteState {
BS_REMOTE_STATE_PUNCH=1<<0,
BS_REMOTE_STATE_JUMP=1<<1,
BS_REMOTE_STATE_THROW=1<<2,
BS_REMOTE_STATE_BOMB=1<<3,
BS_REMOTE_STATE_MENU=1<<4,
// (bits 6-10 are d-pad h-value and bits 11-15 are dpad v-value)
BS_REMOTE_STATE_HOLD_POSITION=1<<15
};
enum BSRemoteState2 {
BS_REMOTE_STATE2_MENU=1<<0,
BS_REMOTE_STATE2_JUMP=1<<1,
BS_REMOTE_STATE2_PUNCH=1<<2,
BS_REMOTE_STATE2_THROW=1<<3,
BS_REMOTE_STATE2_BOMB=1<<4,
BS_REMOTE_STATE2_RUN=1<<5,
BS_REMOTE_STATE2_FLY=1<<6,
BS_REMOTE_STATE2_HOLD_POSITION=1<<7
};
@interface RemoteViewController()
- (void) tryToDie;
- (void) leave;
- (void) readFromSocket:(int) i;
- (void) sendIdRequest;
- (void) doStateChangeForced:(BOOL)forced;
- (void) shipUnAckedStatesV1;
- (void) shipUnAckedStatesV2;
- (CGPoint) getPointInImageSpace:(UIView*)image forPoint:(CGPoint)p;
- (void) setDPadX:(float)x andY:(float)y andPressed:(BOOL)pressed andDirect:(BOOL)direct;
- (void)updateButtonsForTouches;
- (void) updateDPadBase;
- (void) axisSnappingChanged:(NSNumber*)enabled;
- (void) showPrefs;
- (void)showActivityIndicator;
@end
@implementation RemoteViewController
@synthesize processTimer=_processTimer;
@synthesize buttonBacking=_buttonBacking;
@synthesize buttonImagePunch=_buttonImagePunch;
@synthesize buttonImagePunchPressed=_buttonImagePunchPressed;
@synthesize buttonImageThrow=_buttonImageThrow;
@synthesize buttonImageThrowPressed=_buttonImageThrowPressed;
@synthesize buttonImageJump=_buttonImageJump;
@synthesize buttonImageJumpPressed = _buttonImageJumpPressed;
@synthesize buttonImageBomb=_buttonImageBomb;
@synthesize buttonImageBombPressed=_buttonImageBombPressed;
@synthesize dPadBacking=_dPadBacking;
@synthesize dPadThumbImage=_dPadThumbImage;
@synthesize dPadThumbPressedImage=_dPadThumbPressedImage;
@synthesize dPadCenterImage=_dPadCenterImage;
@synthesize bgImage=_bgImage;
@synthesize activityIndicator=_activityIndicator;
@synthesize lagMeter=_lagMeter;
@synthesize validTouches=_validTouches;
@synthesize validMovedTouches=_validMovedTouches;
static void readCallback(CFSocketRef cfSocket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info)
{
RemoteViewController *rvc = (RemoteViewController*)info;
int s = CFSocketGetNative(cfSocket);
if (s){
[rvc readFromSocket:s];
}
}
+ (RemoteViewController*) sharedRemoteViewController
{
return gRemoteViewController;
}
- (void) initCommon
{
_ping = 0.0;
_dPadStateH = 0.0;
_dPadStateV = 0.0;
_wantToDie = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
_axisSnapping = [defaults objectForKey:@"axisSnapping"]==nil?NO:[defaults boolForKey:@"axisSnapping"];
_tiltMode = [defaults objectForKey:@"tiltMode"]==nil?NO:[defaults boolForKey:@"tiltMode"];
_floating = [defaults objectForKey:@"joystickFloating"]==nil?YES:[defaults boolForKey:@"joystickFloating"];
_controllerDPadSensitivity = [defaults objectForKey:@"controllerDPadSensitivity"]==nil?DEFAULT_CONTROLLER_DPAD_SENSITIVITY:[defaults floatForKey:@"controllerDPadSensitivity"];
_tiltNeutralY = [defaults objectForKey:@"tiltNeutralY"]==nil?-0.8:[defaults floatForKey:@"tiltNeutralY"];
_tiltNeutralZ = [defaults objectForKey:@"tiltNeutralZ"]==nil?-0.7:[defaults floatForKey:@"tiltNeutralZ"];
self.validTouches = [NSMutableSet setWithCapacity:10];
self.validMovedTouches = [NSMutableSet setWithCapacity:10];
_lastContactTime = _lastNullStateTime = CACurrentMediaTime();
BOOL success = NO;
_id = -1; // aint got one
_idRequestKey = ((long)(CACurrentMediaTime()*1000.0))%10000;
// if we're reconnecting we might get acks for states we didnt send, so put something reasonable
// here or we'll screw up our lag-meter
CFTimeInterval curTime = CACurrentMediaTime();
for (int i = 0; i < 256; i++){
_stateBirthTimes[i] = curTime;
_stateLastSentTimes[i] = 0.0;
}
// Should we be trying to do a v4 or v6 address first?...
// are there downsides to preferring v6?
// try handling ipv6
{
// create our datagram socket...
CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL};
_cfSocket6 = CFSocketCreate(kCFAllocatorDefault, PF_INET6, SOCK_DGRAM, IPPROTO_UDP, kCFSocketReadCallBack, (CFSocketCallBack)&readCallback, &socketCtxt);
if (_cfSocket6 == NULL){
NSLog(@"ERROR CREATING V6 SOCKET");
abort();
}
// bind it...
struct sockaddr_in6 addr6;
memset(&addr6, 0, sizeof(addr6));
addr6.sin6_len = sizeof(addr6);
addr6.sin6_family = AF_INET6;
addr6.sin6_port = 0;
addr6.sin6_flowinfo = 0;
addr6.sin6_addr = in6addr_any;
NSData *address6 = [NSData dataWithBytes:&addr6 length:sizeof(addr6)];
if (kCFSocketSuccess != CFSocketSetAddress(_cfSocket6, (CFDataRef)address6)) {
NSLog(@"ERROR ON CFSocketSetAddress for ipv6 socket");
if (_cfSocket6) CFRelease(_cfSocket6);
_cfSocket6 = NULL;
}
if (_cfSocket6 != NULL){
_socket6 = CFSocketGetNative(_cfSocket6);
// set up a run loop source for the socket
CFRunLoopRef cfrl = CFRunLoopGetCurrent();
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _cfSocket6, 0);
CFRunLoopAddSource(cfrl, source, kCFRunLoopCommonModes);
CFRelease(source);
success = YES;
}
}
// try v4 ones...
{
// create our datagram socket...
CFSocketContext socketCtxt = {0, self, NULL, NULL, NULL};
_cfSocket4 = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP, kCFSocketReadCallBack, (CFSocketCallBack)&readCallback, &socketCtxt);;
if (_cfSocket4 == NULL){
NSLog(@"ERROR CREATING V4 SOCKET");
abort();
}
if (_cfSocket4 != NULL){
// bind it...
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_len = sizeof(addr4);
addr4.sin_family = AF_INET;
addr4.sin_port = 0;
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)];
if (kCFSocketSuccess != CFSocketSetAddress(_cfSocket4, (CFDataRef)address4)) {
NSLog(@"ERROR ON CFSocketSetAddress for ipv4 socket\n");
if (_cfSocket4) CFRelease(_cfSocket4);
_cfSocket4 = NULL;
}
if (_cfSocket4 != NULL) {
_socket4 = CFSocketGetNative(_cfSocket4);
// set up a run loop source for the socket
CFRunLoopRef cfrl = CFRunLoopGetCurrent();
CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _cfSocket4, 0);
CFRunLoopAddSource(cfrl, source, kCFRunLoopCommonModes);
CFRelease(source);
success = YES;
}
}
}
[self sendIdRequest];
self.processTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0/10.0) target:self selector:@selector(process) userInfo:nil repeats:TRUE];
if (!success){
NSLog(@"Couldn't connect.");
[self tryToDie];
}
}
- (id)initWithAddress:(struct sockaddr)addr andSize:(int)sz
{
gRemoteViewController = self;
[super init];
_newStyle = YES;
_addrCount = 1;
memcpy(&_addresses[0],&addr,sz);
_addressSizes[0] = sz;
[self initCommon];
return self;
}
- (id)initWithNetService:(NSNetService*) netService
{
_newStyle = NO;
gRemoteViewController = self;
[super init];
// make a list of all these addresses.. we'll ping them
// now and then and use whichever is fastest..
// (whats the right thing to do here?...)
NSArray *addresses = [netService addresses];
_addrCount = static_cast<unsigned int>([addresses count]);
if (_addrCount > REMOTE_VIEW_CONTROLLER_MAX_ADDRESSES) {
_addrCount = REMOTE_VIEW_CONTROLLER_MAX_ADDRESSES;
}
for (unsigned int i = 0; i < _addrCount; i++){
struct sockaddr *sa = (struct sockaddr *)[[addresses objectAtIndex:i] bytes];
if(sa->sa_family == AF_INET){
memcpy(&_addresses[i],sa,sizeof(sockaddr_in));
_addressSizes[i] = sizeof(sockaddr_in);
} else if (sa->sa_family == AF_INET6){
memcpy(&_addresses[i],sa,sizeof(sockaddr_in6));
_addressSizes[i] = sizeof(sockaddr_in6);
} else {
NSLog(@"GOT UNRECOGNIZED...!");
}
}
[self initCommon];
return self;
}
- (void) doBecomeActive
{
_lastContactTime = CACurrentMediaTime();
[self showActivityIndicator];
}
- (void) sendIdRequest
{
// lets include a name with our id-requests..
char buffer[100];
NSString *dName;
NSString *uidString;
if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
uidString = [[UIDevice currentDevice].identifierForVendor UUIDString];
} else {
uidString = nil;
}
// on newer versions we send a hash at the end of our name to uniquely identify us
// (this is less necessary here on the iOS version since most phones have unique names, but on android/etc just the device
// name is used as the name.
NSString *name = [AppController playerName];
// we use # for a special purpose so gotta clear them out...
name = [name stringByReplacingOccurrencesOfString:@"#" withString:@""];
if (_newStyle and uidString != nil) dName = [NSString stringWithFormat:@"%@#%@", name, uidString];
else dName = [UIDevice currentDevice].name;
strncpy(buffer,dName.UTF8String,sizeof(buffer));
buffer[sizeof(buffer)-1] = 0; // make sure its capped in case it overran..
int nameLen = static_cast<int>(strlen(buffer));
// we shoot ID requests out on all our addresses we have for the host..
// (then whichever one comes back first is what we use)
for (unsigned int i = 0; i < _addrCount; i++){
// only send to the addresses matching the family of the socket we made...
struct sockaddr *sa = (sockaddr*)&_addresses[i];
UInt8 data[5+nameLen];
data[0] = BS_REMOTE_MSG_ID_REQUEST;
data[1] = BS_REMOTE_PROTOCOL_VERSION; // old protocol version - cant really change this cleanly without breaking things so we now use data[4]
*(short*)&data[2] = _idRequestKey;
data[4] = 50; // this is now used for protocol version *request* - specifying 50 means we want version 2 (yes, it's ugly; i know)
strncpy((char*)data+5,buffer,nameLen);
int s;
if (sa->sa_family == AF_INET6) s = _socket6;
else if (sa->sa_family == AF_INET) s = _socket4;
else abort();
int err = static_cast<int>(sendto(s,data,5+nameLen,0,(sockaddr*)&_addresses[i],_addressSizes[i]));
if (err == -1) NSLog(@"ERROR %d on sendto for %d\n",errno,i);
}
_waitingForIDResponse = YES;
}
- (void) process
{
if (_wantToDie) {
[self tryToDie];
return;
}
CFTimeInterval t = CACurrentMediaTime();
// if we're trying to leave but havn't received an ack, keep sending disconnects out
if (_wantToLeave) {
// give up after a short while
if (t - _leavingStartTime > 2.0) {
[self tryToDie];
return;
}
// shoot off another disconnect notice
if (_id != -1) {
UInt8 data[2] = {BS_REMOTE_MSG_DISCONNECT,_id};
if (_haveV4) {
send(_socket4,data,sizeof(data),0);
}
if (_haveV6) {
send(_socket6, data, sizeof(data), 0);
}
}
}
// if we've got states we havn't heard an ack for yet, keep shipping 'em out
UInt8 stateDiff = _requestedState - _nextState;
// if they've requested a state we don't have yet, we don't need to resend anything
if (stateDiff < 128){
// .. however we wanna shoot states at the server every now and then even if we have no new states,
// to keep from timing out and such..
if (t - _lastNullStateTime > 3.0){
[self doStateChangeForced:YES];
_lastNullStateTime = t;
}
} else {
// ok we've got at least one state we havn't heard confirmation for yet.. lets ship 'em out..
if (_usingProtocolV2) [self shipUnAckedStatesV2];
else [self shipUnAckedStatesV1];
}
// if we don't have an ID yet, keep sending off those requests...
if (_id == -1){
[self sendIdRequest];
}
// update our lag meter every so often
if (t - _lastLagUpdateTime > 2.0){
float smoothing = 0.5;
_averageLag = smoothing * _averageLag + (1.0 - smoothing) * _currentLag;
// lets show half of our the round-trip time as lag.. (the actual delay
// in-game is just our packets getting to them; not the round trip)
float val = _averageLag*0.5;
if (val < 0.1) _lagMeter.textColor = [UIColor colorWithRed:0.5 green:1.0 blue:0.5 alpha:1.0];
else if (val < 0.2) _lagMeter.textColor = [UIColor colorWithRed:1.0 green:0.7 blue:0.4 alpha:1.0];
else _lagMeter.textColor = [UIColor colorWithRed:1.0 green:0.4 blue:0.4 alpha:1.0];
_lagMeter.text = [NSString stringWithFormat:@"lag: %.2f",val];
_currentLag = 0.0;
_lastLagUpdateTime = t;
}
}
- (void) readFromSocket:(int) s {
unsigned char buffer[10];
sockaddr_in6 addr;
socklen_t l = sizeof(addr);
int amt = static_cast<int>(recvfrom(s,buffer,sizeof(buffer),0,(sockaddr*)&addr,&l));
if (amt == -1){
//connrefused on a udp socket means the other end is dead
if (errno == ECONNREFUSED){
[AppController debugPrint:@"The game has shut down."];
[self tryToDie];
return;
//break;
}
if (!_wantToLeave and !_wantToDie){
# if DEBUG
NSLog(@"ERROR ON RECVFROM: %d; DYING!\n",errno);
# endif // DEBUG
[AppController debugPrint:@"Network error;"];
[AppController debugPrint:@"Try restarting BombSquad."];
}
[self tryToDie];
return;
}
if (amt > 0) {
switch(buffer[0]) {
case BS_REMOTE_MSG_ID_RESPONSE:
{
if (amt == 3) {
if (!_waitingForIDResponse) {
break;
}
int s;
if (((sockaddr*)&addr)->sa_family == AF_INET and not _haveV4){
s = _socket4;
} else if (not _haveV6) {
s = _socket6;
} else {
break;
}
_nextState = 0; // start over with this ID
if (connect(s, (sockaddr*)&addr, l) != 0) {
NSLog(@"Warning: socket connect failed with error %d\n.",errno);
break;
} else {
if (((sockaddr*)&addr)->sa_family == AF_INET){
_haveV4 = TRUE;
} else {
_haveV6 = TRUE;
}
}
_connected = YES;
_waitingForIDResponse = NO;
[self.activityIndicator removeFromSuperview];
self.activityIndicator = nil;
}
// hooray we have an id.. we're now officially 'joined'
_id = buffer[1];
// we told them we support protocol v2.. if they respond with 100, they do too.
_usingProtocolV2 = (buffer[2] == 100);
break;
}
case BS_REMOTE_MSG_STATE_ACK:
{
if (amt == 2){
// take note that we heard from them for time-out purposes
CFTimeInterval time = CACurrentMediaTime();
_lastContactTime = time;
// if we've got an activity indicator up, kill it
if (self.activityIndicator != nil) {
[self.activityIndicator removeFromSuperview];
self.activityIndicator = nil;
}
// take note of the next state they want...
// move ours up to that point (if we havn't yet)
UInt8 stateDiff = buffer[1] - _requestedState;
if (stateDiff > 0 and stateDiff < 128) {
_requestedState += (stateDiff-1);
CFTimeInterval lag = time - _stateBirthTimes[_requestedState];
if (lag > _currentLag) {
_currentLag = lag;
}
_requestedState++;
assert(_requestedState == buffer[1]);
}
}
break;
}
case BS_REMOTE_MSG_DISCONNECT_ACK:
// means we were trying to disconnect and have been successful.
if (amt == 1){
[self tryToDie];
}
break;
case BS_REMOTE_MSG_DISCONNECT:
{
if (amt == 2){
if (buffer[1] == BS_REMOTE_ERROR_VERSION_MISMATCH) {
[AppController debugPrint:@"Version Mismatch;"];
[AppController debugPrint:@"Make sure BombSquad and BombSquad Remote"];
[AppController debugPrint:@"are the latest versions."];
} else if (buffer[1] == BS_REMOTE_ERROR_GAME_SHUTTING_DOWN) {
[AppController debugPrint:@"The game has shut down."];
} else if (buffer[1] == BS_REMOTE_ERROR_NOT_ACCEPTING_CONNECTIONS) {
[AppController debugPrint:@"The game is not accepting connections."];
} else {
if (!_wantToDie and !_wantToLeave) {
[AppController debugPrint:@"Disconnected by server."];
}
}
[self tryToDie];
}
break;
}
default:
NSLog(@"UNKNOWN MSG IN TYPE %d\n",buffer[0]);
break;
}
}
}
- (void) shipUnAckedStatesV2
{
CFTimeInterval curTime = CACurrentMediaTime();
_lastSendTime = curTime;
// ok we need to ship out everything from their last requested state
// to our current state.. (clamping at a reasonable value)
if (_id != -1){
UInt8 statesToSend = _nextState-_requestedState;
if (statesToSend > 11) statesToSend = 11;
if (statesToSend < 1) return;
UInt8 data[150];
data[0] = BS_REMOTE_MSG_STATE2;
data[1] = _id;
data[2] = statesToSend; // number of states we have here
UInt8 s = _nextState - statesToSend;
data[3] = s; // starting index
// pack em in
int retransmitCount = 0;
UInt8 *val = (UInt8*)(data+4);
for (int i = 0; i < statesToSend; i++){
val[0] = _statesV2[s] & 0xFF;
val[1] = (_statesV2[s] >> 8) & 0xFF;
val[2] = (_statesV2[s] >> 16) & 0xFF;
if (_stateLastSentTimes[s] != 0.0) retransmitCount++;
_stateLastSentTimes[s] = curTime;
s++;
val += 3;
}
if (_haveV4){
int err = static_cast<int>(send(_socket4,data,4+3*statesToSend,0));
if (err == -1) NSLog(@"ERROR %d on v4 sendto\n",errno);
}
if (_haveV6){
int err = static_cast<int>(send(_socket6,data,4+3*statesToSend,0));
if (err == -1) NSLog(@"ERROR %d on v6 sendto\n",errno);
}
}
}
- (void) shipUnAckedStatesV1
{
CFTimeInterval curTime = CACurrentMediaTime();
_lastSendTime = curTime;
// ok we need to ship out everything from their last requested state
// to our current state.. (clamping at a reasonable value)
if (_id != -1){
UInt8 statesToSend = _nextState-_requestedState;
if (statesToSend > 11) statesToSend = 11;
if (statesToSend < 1) return;
UInt8 data[100];
data[0] = BS_REMOTE_MSG_STATE;
data[1] = _id;
data[2] = statesToSend; // number of states we have here
UInt8 s = _nextState - statesToSend;
data[3] = s; // starting index
// pack em in
int retransmitCount = 0;
UInt16 *val = (UInt16*)(data+4);
for (int i = 0; i < statesToSend; i++){
*val = _statesV1[s];
if (_stateLastSentTimes[s] != 0.0) retransmitCount++;
_stateLastSentTimes[s] = curTime;
s++;
val++;
}
if (_haveV4){
int err = static_cast<int>(send(_socket4,data,4+2*statesToSend,0));
if (err == -1) NSLog(@"ERROR %d on v4 sendto\n",errno);
}
if (_haveV6){
int err = static_cast<int>(send(_socket6,data,4+2*statesToSend,0));
if (err == -1) NSLog(@"ERROR %d on v6 sendto\n",errno);
}
}
}
- (void) _doStateChangeV2Forced:(BOOL)force
{
if (_wantToDie){
[self tryToDie];
return;
}
// compile our state value
UInt32 s = _buttonStateV2; // buttons
int hVal = (int)(256.0f*(0.5f+_dPadStateH*0.5f));
if (hVal < 0) hVal = 0;
else if (hVal > 255) hVal = 255;
int vVal = (int)(256.0f*(0.5f+_dPadStateV*0.5f));
if (vVal < 0) vVal = 0;
else if (vVal > 255) vVal = 255;
s |= hVal << 8;
s |= vVal << 16;
// if our compiled state value hasn't changed, don't send.
// (analog joystick noise can send a bunch of redundant states through here)
// The exception is if forced is true, which is the case with packets that
// double as keepalives.
if (s == _lastSentState and not force) return;
_stateBirthTimes[_nextState] = CACurrentMediaTime();
_stateLastSentTimes[_nextState] = 0;
_statesV2[_nextState++] = s;
_lastSentState = s;
// if we're pretty up to date as far as state acks, lets go ahead
// and send out this state immediately..
// (keeps us nice and responsive on low latency networks)
UInt8 unackedCount = _nextState-_requestedState;
if (unackedCount < 3){
[self shipUnAckedStatesV2];
}
}
- (void) _doStateChangeV1Forced:(BOOL)force {
if (_wantToDie){
[self tryToDie];
return;
}
// compile our state value
int s = _buttonStateV1; // buttons
s |= (_dPadStateH>0)<<5; // sign bit
s |= ((int)(round(fmin(1.0,fabs(_dPadStateH))*15.0))) << 6; // mag
s |= (_dPadStateV>0)<<10; // sign bit
s |= ((int)(round(fmin(1.0,fabs(_dPadStateV))*15.0))) << 11; // mag
// if our compiled state value hasn't changed, don't send.
// (analog joystick noise can send a bunch of redundant states through here)
// The exception is if forced is true, which is the case with packets that
// double as keepalives.
if (s == _lastSentState and not force){
return;
}
_stateBirthTimes[_nextState] = CACurrentMediaTime();
_stateLastSentTimes[_nextState] = 0;
_statesV1[_nextState++] = s;
_lastSentState = s;
// if we're pretty up to date as far as state acks, lets go ahead
// and send out this state immediately..
// (keeps us nice and responsive on low latency networks)
UInt8 unackedCount = _nextState-_requestedState;
if (unackedCount < 3){
[self shipUnAckedStatesV1];
}
}
- (void) doStateChangeForced:(BOOL)force {
if (_usingProtocolV2) [self _doStateChangeV2Forced:force];
else [self _doStateChangeV1Forced:force];
}
- (void) handleUpPress {
_dPadStateV = -1.0;
[self doStateChangeForced:NO];
}
- (void) handleUpRelease {
_dPadStateV = 0.0;
[self doStateChangeForced:NO];
}
- (void) handleDownPress {
_dPadStateV = 1.0;
[self doStateChangeForced:NO];
}
- (void) handleDownRelease {
_dPadStateV = 0.0;
[self doStateChangeForced:NO];
}
- (void) handleLeftPress {
_dPadStateH = -1.0;
[self doStateChangeForced:NO];
}
- (void) handleLeftRelease {
_dPadStateH = 0.0;
[self doStateChangeForced:NO];
}
- (void) handleRightPress {
_dPadStateH = 1.0;
[self doStateChangeForced:NO];
}
- (void) handleRightRelease {
_dPadStateH = 0.0;
[self doStateChangeForced:NO];
}
- (void) handlePunchPress {
_buttonStateV1 |= BS_REMOTE_STATE_PUNCH;
_buttonStateV2 |= BS_REMOTE_STATE2_PUNCH;
[self doStateChangeForced:NO];
self.buttonImagePunchPressed.hidden = NO;
self.buttonImagePunch.hidden = YES;
}
- (void) handlePunchRelease {
_buttonStateV1 &= ~BS_REMOTE_STATE_PUNCH;
_buttonStateV2 &= ~BS_REMOTE_STATE2_PUNCH;
[self doStateChangeForced:NO];
self.buttonImagePunchPressed.hidden = YES;
self.buttonImagePunch.hidden = NO;
}
- (void) handleJumpPress {
_buttonStateV1 |= BS_REMOTE_STATE_JUMP;
_buttonStateV2 |= BS_REMOTE_STATE2_JUMP;
[self doStateChangeForced:NO];
self.buttonImageJump.hidden = YES;
self.buttonImageJumpPressed.hidden = NO;
}
- (void) handleJumpRelease {
_buttonStateV1 &= ~BS_REMOTE_STATE_JUMP;
_buttonStateV2 &= ~BS_REMOTE_STATE2_JUMP;
[self doStateChangeForced:NO];
self.buttonImageJump.hidden = NO;
self.buttonImageJumpPressed.hidden = YES;
}
- (void) handleThrowPress {
_buttonStateV1 |= BS_REMOTE_STATE_THROW;
_buttonStateV2 |= BS_REMOTE_STATE2_THROW;
[self doStateChangeForced:NO];
self.buttonImageThrow.hidden = YES;
self.buttonImageThrowPressed.hidden = NO;
}
- (void) handleThrowRelease {
_buttonStateV1 &= ~BS_REMOTE_STATE_THROW;
_buttonStateV2 &= ~BS_REMOTE_STATE2_THROW;
[self doStateChangeForced:NO];
self.buttonImageThrow.hidden = NO;
self.buttonImageThrowPressed.hidden = YES;
}
- (void) handleBombPress {
_buttonStateV1 |= BS_REMOTE_STATE_BOMB;
_buttonStateV2 |= BS_REMOTE_STATE2_BOMB;
[self doStateChangeForced:NO];
self.buttonImageBomb.hidden = YES;
self.buttonImageBombPressed.hidden = NO;
}
- (void) handleBombRelease {
_buttonStateV1 &= ~BS_REMOTE_STATE_BOMB;
_buttonStateV2 &= ~BS_REMOTE_STATE2_BOMB;
[self doStateChangeForced:NO];
self.buttonImageBomb.hidden = NO;
self.buttonImageBombPressed.hidden = YES;
}
- (void) handleRun1Press {
_run1Pressed = true;
if (_run1Pressed || _run2Pressed || _run3Pressed || _run4Pressed)
_buttonStateV2 |= BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleRun1Release {
_run1Pressed = false;
if (!_run1Pressed and !_run2Pressed and !_run3Pressed and !_run4Pressed)
_buttonStateV2 &= ~BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleRun2Press {
_run2Pressed = true;
if (_run1Pressed || _run2Pressed || _run3Pressed || _run4Pressed)
_buttonStateV2 |= BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleRun2Release {
_run2Pressed = false;
if (!_run1Pressed and !_run2Pressed and !_run3Pressed and !_run4Pressed)
_buttonStateV2 &= ~BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleRun3Press {
_run3Pressed = true;
if (_run1Pressed || _run2Pressed || _run3Pressed || _run4Pressed)
_buttonStateV2 |= BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleRun3Release {
_run3Pressed = false;
if (!_run1Pressed and !_run2Pressed and !_run3Pressed and !_run4Pressed)
_buttonStateV2 &= ~BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleRun4Press {
_run4Pressed = true;
if (_run1Pressed || _run2Pressed || _run3Pressed || _run4Pressed)
_buttonStateV2 |= BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleRun4Release {
_run4Pressed = false;
if (!_run1Pressed and !_run2Pressed and !_run3Pressed and !_run4Pressed)
_buttonStateV2 &= ~BS_REMOTE_STATE2_RUN;
[self doStateChangeForced:NO];
}
- (void) handleMenu {
// send 2 state-changes (menu-down and menu-up)
_buttonStateV1 |= BS_REMOTE_STATE_MENU;
_buttonStateV2 |= BS_REMOTE_STATE2_MENU;
[self doStateChangeForced:NO];
_buttonStateV1 &= ~BS_REMOTE_STATE_MENU;
_buttonStateV2 &= ~BS_REMOTE_STATE2_MENU;
[self doStateChangeForced:NO];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setMultipleTouchEnabled:YES];
float width = self.view.bounds.size.width;
float height = self.view.bounds.size.height;
if (@available(iOS 11.0, *)) {
width = width - UIApplication.sharedApplication.keyWindow.safeAreaInsets.left;
}
UIImageView *i;
CGRect f;
self.buttonBacking = [[[UIView alloc] init] autorelease];
self.buttonImagePunch = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonPunch.png"]] autorelease];
self.buttonImagePunchPressed = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonPunchPressed.png"]] autorelease];
self.buttonImageThrow = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonThrow.png"]] autorelease];
self.buttonImageThrowPressed = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonThrowPressed.png"]] autorelease];
self.buttonImageJump = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonJump.png"]] autorelease];
self.buttonImageJumpPressed = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonJumpPressed.png"]] autorelease];
self.buttonImageBomb = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonBomb.png"]] autorelease];
self.buttonImageBombPressed = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"buttonBombPressed.png"]] autorelease];
self.dPadBacking = [[[UIView alloc] init] autorelease];
self.dPadThumbImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"thumb.png"]] autorelease];
self.dPadThumbPressedImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"thumbPressed.png"]] autorelease];
self.dPadCenterImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"center.png"]] autorelease];
self.bgImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"controllerBG.png"]] autorelease];
_bgImage.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_bgImage.frame = self.view.bounds;
_bgImage.opaque = YES;
[self.view addSubview:_bgImage];
CGFloat lagMeterXAxis = (width-60)/2.0;
CGFloat lagMeterYAxis = height-12;
if (@available(iOS 11.0, *)) {
lagMeterYAxis = lagMeterYAxis -UIApplication.sharedApplication.keyWindow.safeAreaInsets.bottom;
}
self.lagMeter = [[UILabel alloc] init];
_lagMeter.frame = CGRectMake(lagMeterXAxis,lagMeterYAxis,60,12);
_lagMeter.textAlignment = NSTextAlignmentCenter;
_lagMeter.textColor = [UIColor clearColor];
_lagMeter.backgroundColor = [UIColor clearColor];
_lagMeter.font = [UIFont boldSystemFontOfSize:10];
_lagMeter.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
_lastLagUpdateTime = CACurrentMediaTime();
[self.view addSubview:_lagMeter];
_lagMeter.text = @"testing";
UIButton *b;
float buttonWidth = 80;
float buttonHeight = 60;
// dpad
{
CGRect fBase;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
fBase = CGRectMake(0,height/2-120,200,200);
}
else if (@available(iOS 11.0, *)) {
fBase = CGRectMake(UIApplication.sharedApplication.keyWindow.safeAreaInsets.left*2,height*0.65-120,200,200);
}
else{
//fBase = CGRectMake(0,height - 240,200,200);
fBase = CGRectMake(0,height*0.65-120,200,200);
}
UIView *v = self.dPadBacking;
// backing
v.frame = fBase;
v.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[self.view addSubview:v];
float thumbSize = 128;
float centerSize = 256;
float ins;
// center
i = self.dPadCenterImage;
f = fBase;
ins = (fBase.size.width-centerSize)*0.5;
f = CGRectInset(f,ins,ins);
f.origin.x -= _dPadBacking.frame.origin.x;
f.origin.y -= _dPadBacking.frame.origin.y;
i.frame = f;
i.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[_dPadBacking addSubview:i];