Debian Codegraph @

src/services/castlegameservice.pas

raw
1 {
2 Copyright 2015-2018 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Integration with game service (Google Play Games or Apple Game Center) (TGameService). }
17 unit CastleGameService;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses Classes,
24 CastleStringUtils, CastleTimeUtils;
25
26 type
27 { Event for @link(TGameService.OnPlayerBestScoreReceived). }
28 TPlayerBestScoreEvent = procedure (Sender: TObject; const LeaderboardId: string; const Score: Int64) of object;
29
30 { User choice at "save game" dialog displayed by @link(TGameService.ShowSaveGames).
31 Used as a parameter for @link(TGameService.OnSaveGameChosen) event. }
32 TSaveGameChoice = (sgCancel, sgNew, sgExisting);
33
34 { Event for @link(TGameService.OnSaveGameChosen). }
35 TSaveGameChosenEvent = procedure (Sender: TObject; const Choice: TSaveGameChoice; const SaveGameName: string) of object;
36
37 { Event for @link(TGameService.OnSaveGameLoaded).
38 @param Success Whether we loaded the savegame successfully.
39 @param Content The savegame content, if Success. If not Success, this is the error message. }
40 TSaveGameLoadedEvent = procedure (Sender: TObject; const Success: boolean; const Content: string) of object;
41
42 { Status of TGameService sign-in. }
43 TGameServiceStatus = (
44 // Not signed-in to the service.
45 gsSignedOut,
46 // Not signed-in to the service, but during signing-in.
47 gsSigningIn,
48 // Signed-in to the service. All game service methods work now.
49 gsSignedIn,
50 // During signing-out from the service. You should not call other methods on the service now.
51 gsSigningOut
52 );
53
54 { Integration with a game service,
55 that can be used to show achievements, leaderboards, and store save games "in the cloud".
56 This integrates with
57
58 @unorderedList(
59 @itemSpacing Compact
60 @item Google Play Games on Android
61 @item Apple Game Center on iOS.
62 )
63
64 Usage:
65
66 @orderedList(
67 @item(Include the necessary integration code in your Android / iOS project.
68
69 For Android, add the "google_play_games" service inside CastleEngineManifest.xml.
70 See @url(https://github.com/castle-engine/castle-engine/blob/master/tools/build-tool/data/android/integrated-services/google_play_games/README.adoc
71 Android "google_play_games" service docs).
72
73 For iOS, add the "apple_game_center" service inside CastleEngineManifest.xml.
74 See @url(https://github.com/castle-engine/castle-engine/blob/master/tools/build-tool/data/ios/services/apple_game_center/README.adoc
75 iOS "apple_game_center" service docs).)
76
77 @item(Create an instance of this class.
78 Only a single instance of this class makes sense right now,
79 both Android and iOS only allow using a single game service connection
80 from a given game.)
81
82 @item(Call @link(TGameService.Initialize).
83 You usually do it from @link(TCastleApplication.OnInitialize).
84 The @link(TGameService.Initialize) must be called before calling any other method
85 of this class.)
86
87 @item(Call other methods of this class as you see fit --
88 to manage achievements, leaderboards and so on.)
89
90 @item(The user must be "signed in" to the game service.
91
92 The methods that display some user-interface will automatically attempt
93 to sign-in the user if needed. These include @link(ShowAchievements),
94 @link(ShowLeaderboard), @link(ShowSaveGames).
95 So you don't have to do anything before you call them.
96
97 All other methods will @italic(not sign-in the user automatically).
98 For example, @link(Achievement) or @link(SubmitScore) or
99 @link(SaveGameLoad) or @link(SaveGameSave).
100 You should always make sure that the user is signed-in before calling them.
101 To do this, pass AutoStartSignInFlow parameter as @true to @link(Initialize)
102 or call the @link(RequestSignedIn RequestSignedIn(true)).
103 And then wait for the @link(Status) property to change to gsSignedIn
104 (you can register @link(OnStatusChanged) to be notified about changes).
105
106 Note that some platforms (like new Google Play Games v2) may automatically
107 sign-in the user always. Try not to rely on it, if you want to work
108 in all cases (and with all supported platforms).
109 )
110 )
111 }
112 TGameService = class(TComponent)
113 private
114 FOnPlayerBestScoreReceived: TPlayerBestScoreEvent;
115 FInitialized,
116 FInitializedAutoStartSignInFlow,
117 FInitializedSaveGames: boolean;
118 FOnSaveGameChosen: TSaveGameChosenEvent;
119 FOnSaveGameLoaded: TSaveGameLoadedEvent;
120 FOnStatusChanged: TNotifyEvent;
121 FStatus: TGameServiceStatus;
122 function MessageReceived(const Received: TCastleStringList;
123 const ReceivedStream: TMemoryStream): boolean;
124 procedure ReinitializeJavaActivity(Sender: TObject);
125 protected
126 procedure DoSignedInChanged; virtual; deprecated 'use DoStatusChanged';
127 procedure DoStatusChanged; virtual;
128 procedure DoPlayerBestScoreReceived(const LeaderboardId: string; const Score: Int64); virtual;
129 procedure DoSaveGameChosen(const Choice: TSaveGameChoice; const SaveGameName: string); virtual;
130 procedure DoSaveGameLoaded(const Success: boolean; const Content: string); virtual;
131 public
132 constructor Create(AOwner: TComponent); override;
133 destructor Destroy; override;
134
135 { Connect to the service, optionally try to sign-in player.
136
137 If the player already connected this application with
138 Google Play Games (Android) or Apple Game Center (iOS),
139 (s)he will be signed-in automatically.
140 If not, player will be asked to sign-in (which means asking to accept permissions
141 on Android) only if AutoStartSignInFlow.
142 So if you want to avoid the initial Google Play Games dialog on Android,
143 just always pass AutoStartSignInFlow=false.
144
145 Calling this when already initialized is harmless (will not do anything).
146
147 In theory, you can call this at any point in your application.
148 But you probably want to call it early, e.g. from Application.OnInitialize,
149 otherwise user will not be signed-in automatically.
150 Most calls (like sending the leaderboars or achievements) will be ignored until
151 you call this.
152
153 @param(SaveGames Indicates whether you want to use save games feature.
154 You can then use @link(ShowSaveGames), @link(SaveGameSave), @link(SaveGameLoad)
155 methods. See also the description of this feature in Google Play Games:
156 https://developers.google.com/games/services/common/concepts/savedgames.) }
157 procedure Initialize(const AutoStartSignInFlow: boolean = true;
158 const SaveGames: boolean = false);
159
160 { Was the @link(Initialize) called. }
161 property Initialized: boolean read FInitialized;
162
163 { Current status of signing-in. }
164 property Status: TGameServiceStatus read FStatus;
165
166 { Is user currently signed-in. Just a shortcut for @code(Status = gsSignedIn) check. }
167 function SignedIn: boolean;
168
169 { Report the given achievement as achieved.
170
171 For Google Play Games (Android):
172 Use Google Developer Console to define achievements for your game,
173 and use their ids with this method. The achievement ids are autogenerated by Google,
174 they look like @code(CgkIvYuzpZsIEAIQAQ).
175
176 For Apple Game Center (iOS):
177 Use iTunes Connect to define achievements for your game,
178 and use their ids with this method. The achievement ids are chosen by you,
179 so you can choose something readable like 'boss_defeated'.
180 }
181 procedure Achievement(const AchievementId: string);
182
183 { Report a score in given leaderboard.
184 Use Google Developer Console (Android) or iTunes Connect (iOS)
185 to create leaderboards for your game, use their ids here.
186
187 TODO: Not implemented for Apple Game Center (iOS) yet. }
188 procedure SubmitScore(const LeaderboardId: string; const Score: Int64);
189
190 { Get the best score, if available, for given leaderboard.
191
192 This may (after some time, asynchronously) call
193 OnPlayerBestScoreReceived with this score.
194
195 Note that no error is signalled if loading the score fails for any reason.
196 This includes failing to load because user is not connected
197 to the game service (this method doesn't connect automatically;
198 wait for OnStatusChanged before calling this, if you need).
199
200 TODO: Not implemented for Apple Game Center (iOS) yet. }
201 procedure RequestPlayerBestScore(const LeaderboardId: string);
202
203 { Request sign-in or sign-out.
204 The operation will be done asynchronously (it will in most cases require
205 some network communication).
206
207 Watch for changes to the @link(Status) property.
208 You can register an event on @link(OnStatusChanged) to be notified about this. }
209 procedure RequestSignedIn(const Value: boolean);
210
211 { Show the user achievements, using the default UI.
212 Automatically connects (signs-in) player to game services,
213 if not connected yet. }
214 procedure ShowAchievements;
215
216 { Show the given leaderboard, using the default UI.
217 The leaderboard should be created in the Games configuration
218 of the Google Developer Console (Android) or iTunes Connect (iOS).
219 Automatically connects (signs-in) player to game services,
220 if not connected yet. }
221 procedure ShowLeaderboard(const LeaderboardId: string);
222
223 { Show the existing @italic(saved games) stored in the cloud
224 for this user. This can be used to offer user a choice in which slot
225 to save the game, or from which slot to load the game.
226
227 Note that it's not necessary to use this method to manage savegames.
228 E.g. if you want, you can just choose a constant savegame name for your game,
229 and use SaveGameSave and SaveGameLoad with this name. This would imply
230 that each game service user (Google Play Games user or Apple Game Center user)
231 has only one savegame in the cloud for your game.
232
233 The user may choose an existing savegame, or indicate creation
234 of a new savegame (if parameter AllowAddButton is @true). In response,
235 the callback OnSaveGameChosen will be called.
236 It will either
237
238 @orderedList(
239 @item(indicate the name of an existing savegame user has chosen,)
240 @item(or that user wants to create a new savegame,)
241 @item(or that user cancelled the dialog.)
242 )
243
244 Using this requires initializing the game service first,
245 by calling the @link(Initialize) with @code(SaveGames) parameter set to @true.
246 Just like @link(ShowAchievements) and @link(ShowLeaderboard),
247 this method automatically signs-in player to game service,
248 if not signed-in yet.
249
250 Note that @italic(the OnSaveGameChosen callback
251 is not called if the user cancels the sign-in operation), and therefore
252 cancels the savegame choice this way. The same remark applies to all
253 reasons why sign-in may fail (network problems etc.).
254 If this is a problem for your logic (e.g. if you want to "wait"
255 until OnSaveGameChosen is called), then never call ShowSaveGames
256 when @link(SignedIn) is @false. Instead, call RequestSignedIn, wait until
257 SignedIn changed to @true (which may be "never", in case of network problems
258 or user cancelling!), and only then call ShowSaveGames.
259
260 TODO: Not implemented for Apple Game Center (iOS) yet.
261
262 @param(Title Dialog title to display.)
263 @param(AllowAddButton Enable user to choose "new save game".)
264 @param(AllowDelete Enable user to delete savegames from the dialog.)
265 @param(MaxNumberOfSaveGamesToShow Maximum number of savegames to show.
266 Use -1 to just show all savegames.)
267 }
268 procedure ShowSaveGames(const Title: string; const AllowAddButton, AllowDelete: boolean;
269 const MaxNumberOfSaveGamesToShow: Integer);
270 deprecated 'avoid this, as this is unlikely to be implemented on other platforms than Android';
271
272 { Save a savegame identified by the given name.
273 See the SaveGameLoad documentation about the conflict resolution
274 and valid savegame names.
275
276 The Contents should be a valid UTF-8 string. For implementation
277 reasons, you should not save arbitrary binary data this way, for now
278 (or it could result in exceptions about being unable to encode/decode UTF-8
279 sequences).
280
281 Description and PlayedTime are shown to player in ShowSaveGames.
282 PlayedTime may also be used for conflict resolution (if the savegame
283 on the server was modified in the meantime, without loading it in this game).
284
285 No callback is called in response now, the game is saved in the background.
286
287 This does not connect player to game service, if it's not connected
288 already. An error when saving is not reported back to Pascal, for now.
289 (The assumption here is that you will keep a local savegame anyway,
290 in case user does not connect to game service. So inability to save
291 the savegame to the cloud is not alarming, and does not require any special
292 reaction. Please submit a request if you'd like to have a callback
293 about it.) }
294 procedure SaveGameSave(const SaveGameName, Contents, Description: string;
295 const PlayedTime: TFloatTime);
296
297 { Load a savegame identified by the given name.
298 If the savegame does not exist, it will be automatically created.
299
300 If the server requires conflict resolution,
301 the most recently modified savegame is used with Google Play Games,
302 see RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED docs.
303
304 Valid savegame names are defined by Google Play Games:
305 Must be between 1 and 100 non-URL-reserved characters (a-z, A-Z, 0-9,
306 or the symbols "-", ".", "_", or "~").
307
308 In response, the callback OnSaveGameLoaded will be @italic(always) called,
309 with the loaded savegame contents (as a string),
310 or the error message.
311
312 This does not connect player to game service (like Google Play Games),
313 if it's not connected already.
314
315 An error will be reported to OnSaveGameLoaded callback
316 if trying to load fails for any reason.
317 This includes the case when loading fails because user is not connected
318 to game service yet (this method @italic(does not) connect user
319 automatically; wait for OnStatusChanged before calling this method,
320 if you need it). }
321 procedure SaveGameLoad(const SaveGameName: string);
322 published
323 { Event called when @link(Status) changed, for example because
324 @link(RequestSignedIn) was called, or because user signs-in automatically
325 (which may happen if you used AutoStartSignInFlow with @link(Initialize),
326 or if user was signed-in in this application previously). }
327 property OnStatusChanged: TNotifyEvent read FOnStatusChanged write FOnStatusChanged;
328
329 property OnSignedInChanged: TNotifyEvent read FOnStatusChanged write FOnStatusChanged stored false;
330 {$ifdef FPC}deprecated 'use OnStatusChanged';{$endif}
331
332 { Event received in response to @link(RequestPlayerBestScore). }
333 property OnPlayerBestScoreReceived: TPlayerBestScoreEvent read FOnPlayerBestScoreReceived write FOnPlayerBestScoreReceived;
334
335 { Event received in response to @link(ShowSaveGames). }
336 property OnSaveGameChosen: TSaveGameChosenEvent read FOnSaveGameChosen write FOnSaveGameChosen;
337
338 { Event received in response to @link(SaveGameLoad).
339 See TSaveGameLoadedEvent for documentation of parameters. }
340 property OnSaveGameLoaded: TSaveGameLoadedEvent read FOnSaveGameLoaded write FOnSaveGameLoaded;
341 end;
342
343 function GameServiceStatusToStr(const Status: TGameServiceStatus): String;
344
345 implementation
346
347 uses SysUtils,
348 CastleUtils, CastleMessaging, CastleApplicationProperties, CastleLog;
349
350 constructor TGameService.Create(AOwner: TComponent);
351 begin
352 inherited;
353 Messaging.OnReceive.Add({$ifdef FPC}@{$endif} MessageReceived);
354 ApplicationProperties.OnInitializeJavaActivity.Add(
355 {$ifdef FPC}@{$endif} ReinitializeJavaActivity);
356 end;
357
358 destructor TGameService.Destroy;
359 begin
360 if Messaging <> nil then
361 Messaging.OnReceive.Remove({$ifdef FPC}@{$endif} MessageReceived);
362 if ApplicationProperties(false) <> nil then
363 ApplicationProperties(false).OnInitializeJavaActivity.Remove(
364 {$ifdef FPC}@{$endif} ReinitializeJavaActivity);
365 inherited;
366 end;
367
368 procedure TGameService.ReinitializeJavaActivity(Sender: TObject);
369 begin
370 { in case Java activity got killed and is created again, reinitialize services }
371 if FInitialized then
372 begin
373 FStatus := gsSignedOut;
374 Initialize(FInitializedAutoStartSignInFlow, FInitializedSaveGames);
375 end;
376 end;
377
378 procedure TGameService.DoStatusChanged;
379 begin
380 if Assigned(OnStatusChanged) then
381 OnStatusChanged(Self);
382 {$warnings off} // calling deprecated to keep it working
383 DoSignedInChanged;
384 {$warnings on}
385 end;
386
387 procedure TGameService.DoSignedInChanged;
388 begin
389 end;
390
391 function TGameService.SignedIn: boolean;
392 begin
393 Result := FStatus = gsSignedIn;
394 end;
395
396 procedure TGameService.DoPlayerBestScoreReceived(const LeaderboardId: string; const Score: Int64);
397 begin
398 if Assigned(OnPlayerBestScoreReceived) then
399 OnPlayerBestScoreReceived(Self, LeaderboardId, Score);
400 end;
401
402 procedure TGameService.DoSaveGameChosen(const Choice: TSaveGameChoice; const SaveGameName: string);
403 begin
404 if Assigned(OnSaveGameChosen) then
405 OnSaveGameChosen(Self, Choice, SaveGameName);
406 end;
407
408 procedure TGameService.DoSaveGameLoaded(const Success: boolean; const Content: string);
409 begin
410 if Assigned(OnSaveGameLoaded) then
411 OnSaveGameLoaded(Self, Success, Content);
412 end;
413
414 function TGameService.MessageReceived(const Received: TCastleStringList;
415 const ReceivedStream: TMemoryStream): boolean;
416 var
417 StatusInt: Int64;
418 begin
419 Result := false;
420
421 if (Received.Count = 3) and
422 (Received[0] = 'best-score') then
423 begin
424 DoPlayerBestScoreReceived(Received[1], StrToInt64(Received[2]));
425 Result := true;
426 end else
427
428 if (Received.Count = 2) and
429 (Received[0] = 'game-service-status') then
430 begin
431 StatusInt := StrToIntDef(Received[1], -1);
432 if (StatusInt >= Ord(Low(TGameServiceStatus))) and
433 (StatusInt <= Ord(High(TGameServiceStatus))) then
434 begin
435 FStatus := TGameServiceStatus(StatusInt);
436 DoStatusChanged;
437 end else
438 WritelnWarning('Invalid game-service-status parameter "%s"', [Received[1]]);
439 Result := true;
440 end else
441
442 if (Received.Count = 2) and
443 (Received[0] = 'chosen-save-game') then
444 begin
445 DoSaveGameChosen(sgExisting, Received[1]);
446 Result := true;
447 end;
448
449 if (Received.Count = 1) and
450 (Received[0] = 'chosen-save-game-new') then
451 begin
452 DoSaveGameChosen(sgNew, '');
453 Result := true;
454 end;
455
456 if (Received.Count = 1) and
457 (Received[0] = 'chosen-save-game-cancel') then
458 begin
459 DoSaveGameChosen(sgCancel, '');
460 Result := true;
461 end;
462
463 if (Received.Count = 3) and
464 (Received[0] = 'save-game-loaded') then
465 begin
466 DoSaveGameLoaded(StrToBool(Received[1]), Received[2]);
467 Result := true;
468 end;
469 end;
470
471 procedure TGameService.Initialize(const AutoStartSignInFlow: boolean;
472 const SaveGames: boolean);
473 begin
474 { at first Initialize call, remember AutoStartSignInFlow }
475 if not FInitialized then
476 begin
477 FInitializedAutoStartSignInFlow := AutoStartSignInFlow;
478 FInitializedSaveGames := SaveGames;
479 end;
480 FInitialized := true;
481 Messaging.Send(['game-service-initialize',
482 TMessaging.BoolToStr(AutoStartSignInFlow),
483 TMessaging.BoolToStr(SaveGames)
484 ]);
485 end;
486
487 procedure TGameService.Achievement(const AchievementId: string);
488 begin
489 { Report invalid AchievementId right now, otherwise Google Play will report
490 this error too. It's better to have it error on all platforms. }
491 if AchievementId = '' then
492 raise Exception.Create('Achievement name cannot be empty');
493 Messaging.Send(['achievement', AchievementId]);
494 end;
495
496 procedure TGameService.SubmitScore(const LeaderboardId: string; const Score: Int64);
497 begin
498 Messaging.Send(['submit-score', LeaderboardId, IntToStr(Score)]);
499 end;
500
501 procedure TGameService.RequestPlayerBestScore(const LeaderboardId: string);
502 begin
503 Messaging.Send(['request-player-best-score', LeaderboardId]);
504 end;
505
506 procedure TGameService.RequestSignedIn(const Value: boolean);
507 begin
508 Messaging.Send(['game-service-sign-in', TMessaging.BoolToStr(Value)]);
509 end;
510
511 procedure TGameService.ShowAchievements;
512 begin
513 Messaging.Send(['show', 'achievements']);
514 end;
515
516 procedure TGameService.ShowLeaderboard(const LeaderboardId: string);
517 begin
518 Messaging.Send(['show', 'leaderboard', LeaderboardId]);
519 end;
520
521 procedure TGameService.ShowSaveGames(const Title: string; const AllowAddButton, AllowDelete: boolean;
522 const MaxNumberOfSaveGamesToShow: Integer);
523 begin
524 Messaging.Send(['show', 'save-games', Title,
525 TMessaging.BoolToStr(AllowAddButton),
526 TMessaging.BoolToStr(AllowDelete),
527 IntToStr(MaxNumberOfSaveGamesToShow)
528 ]);
529 end;
530
531 procedure TGameService.SaveGameLoad(const SaveGameName: string);
532 begin
533 Messaging.Send(['save-game-load', SaveGameName]);
534 end;
535
536 procedure TGameService.SaveGameSave(const SaveGameName, Contents, Description: string;
537 const PlayedTime: TFloatTime);
538 begin
539 Messaging.Send(['save-game-save', SaveGameName, Contents, Description, TMessaging.TimeToStr(PlayedTime)]);
540 end;
541
542 { routines ------------------------------------------------------------------- }
543
544 function GameServiceStatusToStr(const Status: TGameServiceStatus): String;
545 const
546 Names: array [TGameServiceStatus] of string =
547 (
548 'Signed Out',
549 'Signing In...',
550 'Signed In',
551 'Signing Out..'
552 );
553 begin
554 Result := Names[Status];
555 end;
556
557 end.