TowerDevilGameCenter.mm 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #import <GameKit/GameKit.h>
  2. #import <UIKit/UIKit.h>
  3. extern "C" UIViewController *UnityGetGLViewController(void);
  4. typedef void (*RankCallback)(int, const char *);
  5. typedef void (*PlayerCallback)(const char *);
  6. typedef void (*ProfileCallback)(const char *, const char *, const void *, int);
  7. namespace {
  8. enum Board { BestNight, TotalScore, BoardCount };
  9. NSString *const keys[] = { @"BestNightRankID", @"TotalScoreRankID" };
  10. NSInteger desired[BoardCount], confirmed[BoardCount];
  11. bool submitting[BoardCount], installed, resolvingAuth;
  12. NSUInteger session;
  13. NSString *account;
  14. PlayerCallback signedIn;
  15. ProfileCallback profileChanged;
  16. NSUInteger photoRequest;
  17. void (^afterAuth)(void);
  18. void RefreshPlayerProfile()
  19. {
  20. NSUInteger request = ++photoRequest;
  21. if (!profileChanged) return;
  22. GKLocalPlayer *player = GKLocalPlayer.localPlayer;
  23. if (!player.isAuthenticated) {
  24. profileChanged(nullptr, nullptr, nullptr, 0);
  25. return;
  26. }
  27. NSString *playerID = [player.gamePlayerID copy];
  28. NSString *name = player.displayName.length ? player.displayName : player.alias;
  29. // Publish the name immediately. A negative length means the photo is still pending.
  30. profileChanged(playerID.UTF8String, name.UTF8String, nullptr, -1);
  31. [player loadPhotoForSize:GKPhotoSizeNormal withCompletionHandler:^(UIImage *image, NSError *error) {
  32. dispatch_async(dispatch_get_main_queue(), ^{
  33. if (request != photoRequest || !profileChanged || !player.isAuthenticated ||
  34. ![playerID isEqualToString:player.gamePlayerID] || (!image && error)) return;
  35. NSData *png = image ? UIImagePNGRepresentation(image) : nil;
  36. profileChanged(playerID.UTF8String, name.UTF8String, png.bytes, (int)png.length);
  37. });
  38. }];
  39. }
  40. NSString *BoardID(int board)
  41. {
  42. id value = [NSBundle.mainBundle objectForInfoDictionaryKey:keys[board]];
  43. if (![value isKindOfClass:NSString.class]) return nil;
  44. return [value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
  45. }
  46. bool ValidBoards()
  47. {
  48. NSString *night = BoardID(BestNight), *score = BoardID(TotalScore);
  49. return night.length && score.length && ![night isEqualToString:score];
  50. }
  51. void Flush()
  52. {
  53. GKLocalPlayer *player = GKLocalPlayer.localPlayer;
  54. if (!player.isAuthenticated || ![account isEqualToString:player.gamePlayerID] || !ValidBoards()) return;
  55. for (int i = 0; i < BoardCount; ++i) {
  56. NSInteger value = desired[i];
  57. if (submitting[i] || value <= confirmed[i]) continue;
  58. submitting[i] = true;
  59. NSUInteger generation = session;
  60. [GKLeaderboard submitScore:value context:0 player:player leaderboardIDs:@[BoardID(i)]
  61. completionHandler:^(NSError *error) {
  62. dispatch_async(dispatch_get_main_queue(), ^{
  63. if (session != generation) return;
  64. submitting[i] = false;
  65. if (error) {
  66. NSLog(@"[TowerDevil] Game Center score submission failed: %@", error.localizedDescription);
  67. return; // The saved profile is retried on the next sync or leaderboard visit.
  68. }
  69. confirmed[i] = value;
  70. if (desired[i] > value) Flush();
  71. });
  72. }];
  73. }
  74. }
  75. void Authenticate()
  76. {
  77. if (installed) return;
  78. installed = true;
  79. resolvingAuth = true;
  80. GKLocalPlayer.localPlayer.authenticateHandler = ^(UIViewController *controller, NSError *error) {
  81. dispatch_async(dispatch_get_main_queue(), ^{
  82. if (controller) {
  83. UIViewController *host = UnityGetGLViewController();
  84. while (host.presentedViewController && host.presentedViewController != controller)
  85. host = host.presentedViewController;
  86. if (host && !controller.presentingViewController)
  87. [host presentViewController:controller animated:YES completion:nil];
  88. return;
  89. }
  90. resolvingAuth = false;
  91. GKLocalPlayer *player = GKLocalPlayer.localPlayer;
  92. NSString *current = player.isAuthenticated ? player.gamePlayerID : nil;
  93. if (current != account && ![current isEqualToString:account]) {
  94. account = [current copy];
  95. ++session;
  96. for (int i = 0; i < BoardCount; ++i) {
  97. desired[i] = confirmed[i] = 0;
  98. submitting[i] = false;
  99. }
  100. }
  101. if (current.length && signedIn) signedIn(current.UTF8String);
  102. RefreshPlayerProfile();
  103. void (^pending)(void) = afterAuth;
  104. afterAuth = nil;
  105. if (pending) pending();
  106. });
  107. };
  108. }
  109. void Reply(int request, RankCallback callback, NSDictionary *result)
  110. {
  111. NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil];
  112. NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  113. callback(request, json.UTF8String);
  114. }
  115. NSDictionary *Row(GKLeaderboardEntry *entry, bool mine)
  116. {
  117. return @{@"rank": @(entry.rank), @"name": entry.player.displayName ?: @"",
  118. @"score": @(entry.score), @"mine": @(mine)};
  119. }
  120. void Load(int board, int request, RankCallback callback)
  121. {
  122. if (!ValidBoards()) {
  123. Reply(request, callback, @{@"error": @"Game Center leaderboard IDs are missing or invalid."});
  124. return;
  125. }
  126. if (!GKLocalPlayer.localPlayer.isAuthenticated) {
  127. Reply(request, callback, @{@"error": @"Sign in to Game Center in iOS Settings, then try again."});
  128. return;
  129. }
  130. Flush();
  131. NSUInteger generation = session;
  132. NSString *identifier = BoardID(board);
  133. [GKLeaderboard loadLeaderboardsWithIDs:@[identifier] completionHandler:^(NSArray<GKLeaderboard *> *boards, NSError *error) {
  134. GKLeaderboard *leaderboard = boards.firstObject;
  135. if (error || ![leaderboard.baseLeaderboardID isEqualToString:identifier]) {
  136. dispatch_async(dispatch_get_main_queue(), ^{
  137. Reply(request, callback, @{@"error": @"This leaderboard is unavailable. Try again later."});
  138. });
  139. return;
  140. }
  141. [leaderboard loadEntriesForPlayerScope:GKLeaderboardPlayerScopeGlobal timeScope:GKLeaderboardTimeScopeAllTime
  142. range:NSMakeRange(1, 10) completionHandler:^(GKLeaderboardEntry *local, NSArray<GKLeaderboardEntry *> *entries,
  143. NSInteger total, NSError *loadError) {
  144. dispatch_async(dispatch_get_main_queue(), ^{
  145. if (loadError || session != generation || !GKLocalPlayer.localPlayer.isAuthenticated) {
  146. Reply(request, callback, @{@"error": @"Could not load standings. Try again."});
  147. return;
  148. }
  149. NSMutableArray *rows = [NSMutableArray array];
  150. bool includesLocal = false;
  151. for (GKLeaderboardEntry *entry in entries) {
  152. bool mine = [entry.player.gamePlayerID isEqualToString:account];
  153. [rows addObject:Row(entry, mine)];
  154. includesLocal |= mine;
  155. }
  156. if (!includesLocal && local.rank > 0 && local.rank <= total) [rows addObject:Row(local, true)];
  157. Reply(request, callback, @{@"entries": rows});
  158. });
  159. }];
  160. }];
  161. }
  162. } // namespace
  163. extern "C" void TDGameCenterObserveProfile(ProfileCallback callback)
  164. {
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. profileChanged = callback;
  167. RefreshPlayerProfile();
  168. });
  169. }
  170. extern "C" void TDGameCenterSync(const char *owner, int bestNight, int totalScore, PlayerCallback player)
  171. {
  172. NSString *ownerID = owner ? [NSString stringWithUTF8String:owner] : nil;
  173. dispatch_async(dispatch_get_main_queue(), ^{
  174. signedIn = player;
  175. Authenticate();
  176. if (!account.length || ![account isEqualToString:ownerID]) return;
  177. desired[BestNight] = bestNight;
  178. desired[TotalScore] = totalScore;
  179. Flush();
  180. });
  181. }
  182. extern "C" void TDGameCenterLoad(int board, int request, RankCallback callback)
  183. {
  184. dispatch_async(dispatch_get_main_queue(), ^{
  185. Authenticate();
  186. if (resolvingAuth) afterAuth = ^{ Load(board, request, callback); };
  187. else Load(board, request, callback);
  188. });
  189. }