game_center.mm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*************************************************************************/
  2. /* game_center.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifdef GAME_CENTER_ENABLED
  31. #include "game_center.h"
  32. #import "app_delegate.h"
  33. #import <GameKit/GameKit.h>
  34. GameCenter *GameCenter::instance = NULL;
  35. void GameCenter::_bind_methods() {
  36. ClassDB::bind_method(D_METHOD("is_authenticated"), &GameCenter::is_authenticated);
  37. ClassDB::bind_method(D_METHOD("post_score"), &GameCenter::post_score);
  38. ClassDB::bind_method(D_METHOD("award_achievement"), &GameCenter::award_achievement);
  39. ClassDB::bind_method(D_METHOD("reset_achievements"), &GameCenter::reset_achievements);
  40. ClassDB::bind_method(D_METHOD("request_achievements"), &GameCenter::request_achievements);
  41. ClassDB::bind_method(D_METHOD("request_achievement_descriptions"), &GameCenter::request_achievement_descriptions);
  42. ClassDB::bind_method(D_METHOD("show_game_center"), &GameCenter::show_game_center);
  43. ClassDB::bind_method(D_METHOD("request_identity_verification_signature"), &GameCenter::request_identity_verification_signature);
  44. ClassDB::bind_method(D_METHOD("get_pending_event_count"), &GameCenter::get_pending_event_count);
  45. ClassDB::bind_method(D_METHOD("pop_pending_event"), &GameCenter::pop_pending_event);
  46. };
  47. void GameCenter::return_connect_error(const char *p_error_description) {
  48. authenticated = false;
  49. Dictionary ret;
  50. ret["type"] = "authentication";
  51. ret["result"] = "error";
  52. ret["error_code"] = 0;
  53. ret["error_description"] = p_error_description;
  54. pending_events.push_back(ret);
  55. }
  56. void GameCenter::connect() {
  57. //if this class isn't available, game center isn't implemented
  58. if ((NSClassFromString(@"GKLocalPlayer")) == nil) {
  59. return_connect_error("GameCenter not available");
  60. return;
  61. }
  62. GKLocalPlayer *player = [GKLocalPlayer localPlayer];
  63. if (![player respondsToSelector:@selector(authenticateHandler)]) {
  64. return_connect_error("GameCenter doesn't respond to 'authenticateHandler'");
  65. return;
  66. }
  67. ViewController *root_controller = (ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController;
  68. if (!root_controller) {
  69. return_connect_error("Window doesn't have root ViewController");
  70. return;
  71. }
  72. // This handler is called several times. First when the view needs to be shown, then again
  73. // after the view is cancelled or the user logs in. Or if the user's already logged in, it's
  74. // called just once to confirm they're authenticated. This is why no result needs to be specified
  75. // in the presentViewController phase. In this case, more calls to this function will follow.
  76. player.authenticateHandler = (^(UIViewController *controller, NSError *error) {
  77. if (controller) {
  78. [root_controller presentViewController:controller animated:YES completion:nil];
  79. } else {
  80. Dictionary ret;
  81. ret["type"] = "authentication";
  82. if (player.isAuthenticated) {
  83. ret["result"] = "ok";
  84. ret["player_id"] = [player.playerID UTF8String];
  85. GameCenter::get_singleton()->authenticated = true;
  86. } else {
  87. ret["result"] = "error";
  88. ret["error_code"] = (int64_t)error.code;
  89. ret["error_description"] = [error.localizedDescription UTF8String];
  90. GameCenter::get_singleton()->authenticated = false;
  91. };
  92. pending_events.push_back(ret);
  93. };
  94. });
  95. };
  96. bool GameCenter::is_authenticated() {
  97. return authenticated;
  98. };
  99. Error GameCenter::post_score(Variant p_score) {
  100. Dictionary params = p_score;
  101. ERR_FAIL_COND_V(!params.has("score") || !params.has("category"), ERR_INVALID_PARAMETER);
  102. float score = params["score"];
  103. String category = params["category"];
  104. NSString *cat_str = [[[NSString alloc] initWithUTF8String:category.utf8().get_data()] autorelease];
  105. GKScore *reporter = [[[GKScore alloc] initWithLeaderboardIdentifier:cat_str] autorelease];
  106. reporter.value = score;
  107. ERR_FAIL_COND_V([GKScore respondsToSelector:@selector(reportScores)], ERR_UNAVAILABLE);
  108. [GKScore reportScores:@[ reporter ]
  109. withCompletionHandler:^(NSError *error) {
  110. Dictionary ret;
  111. ret["type"] = "post_score";
  112. if (error == nil) {
  113. ret["result"] = "ok";
  114. } else {
  115. ret["result"] = "error";
  116. ret["error_code"] = (int64_t)error.code;
  117. ret["error_description"] = [error.localizedDescription UTF8String];
  118. };
  119. pending_events.push_back(ret);
  120. }];
  121. return OK;
  122. };
  123. Error GameCenter::award_achievement(Variant p_params) {
  124. Dictionary params = p_params;
  125. ERR_FAIL_COND_V(!params.has("name") || !params.has("progress"), ERR_INVALID_PARAMETER);
  126. String name = params["name"];
  127. float progress = params["progress"];
  128. NSString *name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease];
  129. GKAchievement *achievement = [[[GKAchievement alloc] initWithIdentifier:name_str] autorelease];
  130. ERR_FAIL_COND_V(!achievement, FAILED);
  131. ERR_FAIL_COND_V([GKAchievement respondsToSelector:@selector(reportAchievements)], ERR_UNAVAILABLE);
  132. achievement.percentComplete = progress;
  133. achievement.showsCompletionBanner = NO;
  134. if (params.has("show_completion_banner")) {
  135. achievement.showsCompletionBanner = params["show_completion_banner"] ? YES : NO;
  136. }
  137. [GKAchievement reportAchievements:@[ achievement ]
  138. withCompletionHandler:^(NSError *error) {
  139. Dictionary ret;
  140. ret["type"] = "award_achievement";
  141. if (error == nil) {
  142. ret["result"] = "ok";
  143. } else {
  144. ret["result"] = "error";
  145. ret["error_code"] = (int64_t)error.code;
  146. };
  147. pending_events.push_back(ret);
  148. }];
  149. return OK;
  150. };
  151. void GameCenter::request_achievement_descriptions() {
  152. [GKAchievementDescription loadAchievementDescriptionsWithCompletionHandler:^(NSArray *descriptions, NSError *error) {
  153. Dictionary ret;
  154. ret["type"] = "achievement_descriptions";
  155. if (error == nil) {
  156. ret["result"] = "ok";
  157. PoolStringArray names;
  158. PoolStringArray titles;
  159. PoolStringArray unachieved_descriptions;
  160. PoolStringArray achieved_descriptions;
  161. PoolIntArray maximum_points;
  162. Array hidden;
  163. Array replayable;
  164. for (int i = 0; i < [descriptions count]; i++) {
  165. GKAchievementDescription *description = [descriptions objectAtIndex:i];
  166. const char *str = [description.identifier UTF8String];
  167. names.push_back(String::utf8(str != NULL ? str : ""));
  168. str = [description.title UTF8String];
  169. titles.push_back(String::utf8(str != NULL ? str : ""));
  170. str = [description.unachievedDescription UTF8String];
  171. unachieved_descriptions.push_back(String::utf8(str != NULL ? str : ""));
  172. str = [description.achievedDescription UTF8String];
  173. achieved_descriptions.push_back(String::utf8(str != NULL ? str : ""));
  174. maximum_points.push_back(description.maximumPoints);
  175. hidden.push_back(description.hidden == YES);
  176. replayable.push_back(description.replayable == YES);
  177. }
  178. ret["names"] = names;
  179. ret["titles"] = titles;
  180. ret["unachieved_descriptions"] = unachieved_descriptions;
  181. ret["achieved_descriptions"] = achieved_descriptions;
  182. ret["maximum_points"] = maximum_points;
  183. ret["hidden"] = hidden;
  184. ret["replayable"] = replayable;
  185. } else {
  186. ret["result"] = "error";
  187. ret["error_code"] = (int64_t)error.code;
  188. };
  189. pending_events.push_back(ret);
  190. }];
  191. };
  192. void GameCenter::request_achievements() {
  193. [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) {
  194. Dictionary ret;
  195. ret["type"] = "achievements";
  196. if (error == nil) {
  197. ret["result"] = "ok";
  198. PoolStringArray names;
  199. PoolRealArray percentages;
  200. for (int i = 0; i < [achievements count]; i++) {
  201. GKAchievement *achievement = [achievements objectAtIndex:i];
  202. const char *str = [achievement.identifier UTF8String];
  203. names.push_back(String::utf8(str != NULL ? str : ""));
  204. percentages.push_back(achievement.percentComplete);
  205. }
  206. ret["names"] = names;
  207. ret["progress"] = percentages;
  208. } else {
  209. ret["result"] = "error";
  210. ret["error_code"] = (int64_t)error.code;
  211. };
  212. pending_events.push_back(ret);
  213. }];
  214. };
  215. void GameCenter::reset_achievements() {
  216. [GKAchievement resetAchievementsWithCompletionHandler:^(NSError *error) {
  217. Dictionary ret;
  218. ret["type"] = "reset_achievements";
  219. if (error == nil) {
  220. ret["result"] = "ok";
  221. } else {
  222. ret["result"] = "error";
  223. ret["error_code"] = (int64_t)error.code;
  224. };
  225. pending_events.push_back(ret);
  226. }];
  227. };
  228. Error GameCenter::show_game_center(Variant p_params) {
  229. ERR_FAIL_COND_V(!NSProtocolFromString(@"GKGameCenterControllerDelegate"), FAILED);
  230. Dictionary params = p_params;
  231. GKGameCenterViewControllerState view_state = GKGameCenterViewControllerStateDefault;
  232. if (params.has("view")) {
  233. String view_name = params["view"];
  234. if (view_name == "default") {
  235. view_state = GKGameCenterViewControllerStateDefault;
  236. } else if (view_name == "leaderboards") {
  237. view_state = GKGameCenterViewControllerStateLeaderboards;
  238. } else if (view_name == "achievements") {
  239. view_state = GKGameCenterViewControllerStateAchievements;
  240. } else if (view_name == "challenges") {
  241. view_state = GKGameCenterViewControllerStateChallenges;
  242. } else {
  243. return ERR_INVALID_PARAMETER;
  244. }
  245. }
  246. GKGameCenterViewController *controller = [[GKGameCenterViewController alloc] init];
  247. ERR_FAIL_COND_V(!controller, FAILED);
  248. ViewController *root_controller = (ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController;
  249. ERR_FAIL_COND_V(!root_controller, FAILED);
  250. controller.gameCenterDelegate = root_controller;
  251. controller.viewState = view_state;
  252. if (view_state == GKGameCenterViewControllerStateLeaderboards) {
  253. controller.leaderboardIdentifier = nil;
  254. if (params.has("leaderboard_name")) {
  255. String name = params["leaderboard_name"];
  256. NSString *name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease];
  257. controller.leaderboardIdentifier = name_str;
  258. }
  259. }
  260. [root_controller presentViewController:controller animated:YES completion:nil];
  261. return OK;
  262. };
  263. Error GameCenter::request_identity_verification_signature() {
  264. ERR_FAIL_COND_V(!is_authenticated(), ERR_UNAUTHORIZED);
  265. GKLocalPlayer *player = [GKLocalPlayer localPlayer];
  266. [player generateIdentityVerificationSignatureWithCompletionHandler:^(NSURL *publicKeyUrl, NSData *signature, NSData *salt, uint64_t timestamp, NSError *error) {
  267. Dictionary ret;
  268. ret["type"] = "identity_verification_signature";
  269. if (error == nil) {
  270. ret["result"] = "ok";
  271. ret["public_key_url"] = [publicKeyUrl.absoluteString UTF8String];
  272. ret["signature"] = [[signature base64EncodedStringWithOptions:0] UTF8String];
  273. ret["salt"] = [[salt base64EncodedStringWithOptions:0] UTF8String];
  274. ret["timestamp"] = timestamp;
  275. ret["player_id"] = [player.playerID UTF8String];
  276. } else {
  277. ret["result"] = "error";
  278. ret["error_code"] = (int64_t)error.code;
  279. ret["error_description"] = [error.localizedDescription UTF8String];
  280. };
  281. pending_events.push_back(ret);
  282. }];
  283. return OK;
  284. };
  285. void GameCenter::game_center_closed() {
  286. Dictionary ret;
  287. ret["type"] = "show_game_center";
  288. ret["result"] = "ok";
  289. pending_events.push_back(ret);
  290. }
  291. int GameCenter::get_pending_event_count() {
  292. return pending_events.size();
  293. };
  294. Variant GameCenter::pop_pending_event() {
  295. Variant front = pending_events.front()->get();
  296. pending_events.pop_front();
  297. return front;
  298. };
  299. GameCenter *GameCenter::get_singleton() {
  300. return instance;
  301. };
  302. GameCenter::GameCenter() {
  303. ERR_FAIL_COND(instance != NULL);
  304. instance = this;
  305. authenticated = false;
  306. };
  307. GameCenter::~GameCenter(){};
  308. #endif