| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 |
- #import <GameKit/GameKit.h>
- #import <UIKit/UIKit.h>
- extern "C" UIViewController *UnityGetGLViewController(void);
- typedef void (*RankCallback)(int, const char *);
- typedef void (*PlayerCallback)(const char *);
- typedef void (*ProfileCallback)(const char *, const char *, const void *, int);
- namespace {
- enum Board { BestNight, TotalScore, BoardCount };
- NSString *const keys[] = { @"BestNightRankID", @"TotalScoreRankID" };
- NSInteger desired[BoardCount], confirmed[BoardCount];
- bool submitting[BoardCount], installed, resolvingAuth;
- NSUInteger session;
- NSString *account;
- PlayerCallback signedIn;
- ProfileCallback profileChanged;
- NSUInteger photoRequest;
- void (^afterAuth)(void);
- void RefreshPlayerProfile()
- {
- NSUInteger request = ++photoRequest;
- if (!profileChanged) return;
- GKLocalPlayer *player = GKLocalPlayer.localPlayer;
- if (!player.isAuthenticated) {
- profileChanged(nullptr, nullptr, nullptr, 0);
- return;
- }
- NSString *playerID = [player.gamePlayerID copy];
- NSString *name = player.displayName.length ? player.displayName : player.alias;
- // Publish the name immediately. A negative length means the photo is still pending.
- profileChanged(playerID.UTF8String, name.UTF8String, nullptr, -1);
- [player loadPhotoForSize:GKPhotoSizeNormal withCompletionHandler:^(UIImage *image, NSError *error) {
- dispatch_async(dispatch_get_main_queue(), ^{
- if (request != photoRequest || !profileChanged || !player.isAuthenticated ||
- ![playerID isEqualToString:player.gamePlayerID] || (!image && error)) return;
- NSData *png = image ? UIImagePNGRepresentation(image) : nil;
- profileChanged(playerID.UTF8String, name.UTF8String, png.bytes, (int)png.length);
- });
- }];
- }
- NSString *BoardID(int board)
- {
- id value = [NSBundle.mainBundle objectForInfoDictionaryKey:keys[board]];
- if (![value isKindOfClass:NSString.class]) return nil;
- return [value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
- }
- bool ValidBoards()
- {
- NSString *night = BoardID(BestNight), *score = BoardID(TotalScore);
- return night.length && score.length && ![night isEqualToString:score];
- }
- void Flush()
- {
- GKLocalPlayer *player = GKLocalPlayer.localPlayer;
- if (!player.isAuthenticated || ![account isEqualToString:player.gamePlayerID] || !ValidBoards()) return;
- for (int i = 0; i < BoardCount; ++i) {
- NSInteger value = desired[i];
- if (submitting[i] || value <= confirmed[i]) continue;
- submitting[i] = true;
- NSUInteger generation = session;
- [GKLeaderboard submitScore:value context:0 player:player leaderboardIDs:@[BoardID(i)]
- completionHandler:^(NSError *error) {
- dispatch_async(dispatch_get_main_queue(), ^{
- if (session != generation) return;
- submitting[i] = false;
- if (error) {
- NSLog(@"[TowerDevil] Game Center score submission failed: %@", error.localizedDescription);
- return; // The saved profile is retried on the next sync or leaderboard visit.
- }
- confirmed[i] = value;
- if (desired[i] > value) Flush();
- });
- }];
- }
- }
- void Authenticate()
- {
- if (installed) return;
- installed = true;
- resolvingAuth = true;
- GKLocalPlayer.localPlayer.authenticateHandler = ^(UIViewController *controller, NSError *error) {
- dispatch_async(dispatch_get_main_queue(), ^{
- if (controller) {
- UIViewController *host = UnityGetGLViewController();
- while (host.presentedViewController && host.presentedViewController != controller)
- host = host.presentedViewController;
- if (host && !controller.presentingViewController)
- [host presentViewController:controller animated:YES completion:nil];
- return;
- }
- resolvingAuth = false;
- GKLocalPlayer *player = GKLocalPlayer.localPlayer;
- NSString *current = player.isAuthenticated ? player.gamePlayerID : nil;
- if (current != account && ![current isEqualToString:account]) {
- account = [current copy];
- ++session;
- for (int i = 0; i < BoardCount; ++i) {
- desired[i] = confirmed[i] = 0;
- submitting[i] = false;
- }
- }
- if (current.length && signedIn) signedIn(current.UTF8String);
- RefreshPlayerProfile();
- void (^pending)(void) = afterAuth;
- afterAuth = nil;
- if (pending) pending();
- });
- };
- }
- void Reply(int request, RankCallback callback, NSDictionary *result)
- {
- NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil];
- NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- callback(request, json.UTF8String);
- }
- NSDictionary *Row(GKLeaderboardEntry *entry, bool mine)
- {
- return @{@"rank": @(entry.rank), @"name": entry.player.displayName ?: @"",
- @"score": @(entry.score), @"mine": @(mine)};
- }
- void Load(int board, int request, RankCallback callback)
- {
- if (!ValidBoards()) {
- Reply(request, callback, @{@"error": @"Game Center leaderboard IDs are missing or invalid."});
- return;
- }
- if (!GKLocalPlayer.localPlayer.isAuthenticated) {
- Reply(request, callback, @{@"error": @"Sign in to Game Center in iOS Settings, then try again."});
- return;
- }
- Flush();
- NSUInteger generation = session;
- NSString *identifier = BoardID(board);
- [GKLeaderboard loadLeaderboardsWithIDs:@[identifier] completionHandler:^(NSArray<GKLeaderboard *> *boards, NSError *error) {
- GKLeaderboard *leaderboard = boards.firstObject;
- if (error || ![leaderboard.baseLeaderboardID isEqualToString:identifier]) {
- dispatch_async(dispatch_get_main_queue(), ^{
- Reply(request, callback, @{@"error": @"This leaderboard is unavailable. Try again later."});
- });
- return;
- }
- [leaderboard loadEntriesForPlayerScope:GKLeaderboardPlayerScopeGlobal timeScope:GKLeaderboardTimeScopeAllTime
- range:NSMakeRange(1, 10) completionHandler:^(GKLeaderboardEntry *local, NSArray<GKLeaderboardEntry *> *entries,
- NSInteger total, NSError *loadError) {
- dispatch_async(dispatch_get_main_queue(), ^{
- if (loadError || session != generation || !GKLocalPlayer.localPlayer.isAuthenticated) {
- Reply(request, callback, @{@"error": @"Could not load standings. Try again."});
- return;
- }
- NSMutableArray *rows = [NSMutableArray array];
- bool includesLocal = false;
- for (GKLeaderboardEntry *entry in entries) {
- bool mine = [entry.player.gamePlayerID isEqualToString:account];
- [rows addObject:Row(entry, mine)];
- includesLocal |= mine;
- }
- if (!includesLocal && local.rank > 0 && local.rank <= total) [rows addObject:Row(local, true)];
- Reply(request, callback, @{@"entries": rows});
- });
- }];
- }];
- }
- } // namespace
- extern "C" void TDGameCenterObserveProfile(ProfileCallback callback)
- {
- dispatch_async(dispatch_get_main_queue(), ^{
- profileChanged = callback;
- RefreshPlayerProfile();
- });
- }
- extern "C" void TDGameCenterSync(const char *owner, int bestNight, int totalScore, PlayerCallback player)
- {
- NSString *ownerID = owner ? [NSString stringWithUTF8String:owner] : nil;
- dispatch_async(dispatch_get_main_queue(), ^{
- signedIn = player;
- Authenticate();
- if (!account.length || ![account isEqualToString:ownerID]) return;
- desired[BestNight] = bestNight;
- desired[TotalScore] = totalScore;
- Flush();
- });
- }
- extern "C" void TDGameCenterLoad(int board, int request, RankCallback callback)
- {
- dispatch_async(dispatch_get_main_queue(), ^{
- Authenticate();
- if (resolvingAuth) afterAuth = ^{ Load(board, request, callback); };
- else Load(board, request, callback);
- });
- }
|