Debian Codegraph @

src/services/castleads.pas

raw
1 {
2 Copyright 2015-2022 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 { Ads (advertisements) in game (TAds). }
17 unit CastleAds;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses Classes, CastleRectangles, CastleStringUtils;
24
25 const
26 { Test banner ad "unit id". You can use it with @link(TAds.InitializeAdMob) for testing purposes
27 (but eventually you want to create your own, to show non-testing ads!).
28
29 From https://developers.google.com/admob/android/test-ads }
30 TestAdMobBannerUnitId = 'ca-app-pub-3940256099942544/6300978111';
31
32 { Test interstitial static ad "unit id". You can use it with @link(TAds.InitializeAdMob) for testing purposes
33 (but eventually you want to create your own, to show non-testing ads!).
34
35 From https://developers.google.com/admob/android/test-ads }
36 TestAdMobInterstitialUnitId = 'ca-app-pub-3940256099942544/1033173712';
37
38 { Test interstitial video ad "unit id". You can use it with @link(TAds.InitializeAdMob) for testing purposes
39 (but eventually you want to create your own, to show non-testing ads!).
40
41 From https://developers.google.com/admob/android/test-ads }
42 TestAdMobInterstitialVideoUnitId = 'ca-app-pub-3940256099942544/8691691433';
43
44 { Test rewarded video ad "unit id". You can use it with @link(TAds.InitializeAdMob) for testing purposes
45 (but eventually you want to create your own, to show non-testing ads!).
46
47 From https://developers.google.com/admob/android/test-ads }
48 TestAdMobRewardedUnitId = 'ca-app-pub-3940256099942544/5224354917';
49
50 type
51 TAdNetwork = (anAdMob, anChartboost, anStartApp);
52
53 TFullScreenAdType = (atInterstitialStatic, atInterstitialVideo, atReward);
54
55 TAdWatchStatus = (wsWatched, wsUnknownError, wsNetworkNotAvailable, wsNoAdsAvailable,
56 wsUserAborted, wsAdNotReady, wsAdNetworkNotInitialized, wsInvalidRequest,
57 wsAdTypeUnsupported, wsApplicationReinitialized);
58
59 TAdClosedEvent = procedure (const Sender: TObject; const WatchedStatus: TAdWatchStatus) of object;
60
61 { Advertisements in game.
62 Right now only on Android (does nothing on other platforms,
63 as CastleMessaging does nothing on non-Android platforms).
64
65 Usage:
66
67 @orderedList(
68 @item(Create an instance of this class (only a single instance allowed).)
69
70 @item(Initialize at least one ad network using one of the
71 @code(InitializeXxx) methods. Usually you want to call the initialization
72 from @link(TCastleApplication.OnInitialize).)
73
74 @item(Use remaining methods of this class to show / hide ads, like
75 @link(ShowFullScreenAd), @link(ShowBanner), @link(HideBanner).)
76
77 @item(To include the necessary integration code in your Android project,
78 declare your Android project type as "integrated" with
79 the appropriate services (admob, chartboost, startapp...)
80 inside CastleEngineManifest.xml .
81 See https://castle-engine.io/android-Project-Services-Integrated-with-Castle-Game-Engine .)
82 )
83 }
84 TAds = class(TComponent)
85 private
86 type
87 TAdNetworkHandler = class abstract
88 strict private
89 FParent: TAds;
90 FBannerShowing: boolean;
91 FBannerGravity: Integer;
92 function MessageReceived(const Received: TCastleStringList;
93 const ReceivedStream: TMemoryStream): boolean;
94 procedure FullScreenAdClosed(const WatchedStatus: TAdWatchStatus);
95 strict protected
96 FFullScreenAdVisible: boolean;
97 procedure ReinitializeJavaActivity(Sender: TObject); virtual;
98 public
99 constructor Create(const AParent: TAds);
100 destructor Destroy; override;
101 property Parent: TAds read FParent;
102 class function Name: string; virtual; abstract;
103 procedure ShowBanner(const Gravity: Integer); virtual;
104 procedure HideBanner; virtual;
105 procedure ShowFullScreenAd(const AdType: TFullScreenAdType;
106 const WaitUntilLoaded: boolean); virtual;
107 end;
108
109 TAdMobHandler = class(TAdNetworkHandler)
110 strict private
111 FBannerUnitId, FInterstitialUnitId, FRewardedUnitId, FTestDeviceIdsGlued: string;
112 strict protected
113 procedure ReinitializeJavaActivity(Sender: TObject); override;
114 public
115 constructor Create(const AParent: TAds;
116 const ABannerUnitId, AInterstitialUnitId, ARewardedUnitId: string;
117 const TestDeviceIds: array of string);
118
119 class function Name: string; override;
120 procedure ShowBanner(const Gravity: Integer); override;
121 procedure HideBanner; override;
122 procedure ShowFullScreenAd(const AdType: TFullScreenAdType;
123 const WaitUntilLoaded: boolean); override;
124 end;
125
126 TChartboostHandler = class(TAdNetworkHandler)
127 strict private
128 FAppId, FAppSignature: string;
129 strict protected
130 procedure ReinitializeJavaActivity(Sender: TObject); override;
131 public
132 constructor Create(const AParent: TAds;
133 const AnAppId, AnAppSignature: string);
134 class function Name: string; override;
135 procedure ShowFullScreenAd(const AdType: TFullScreenAdType;
136 const WaitUntilLoaded: boolean); override;
137 end;
138
139 TStartappHandler = class(TAdNetworkHandler)
140 strict private
141 FAppId: string;
142 strict protected
143 procedure ReinitializeJavaActivity(Sender: TObject); override;
144 public
145 constructor Create(const AParent: TAds;
146 const AnAppId: string);
147 class function Name: string; override;
148 procedure ShowFullScreenAd(const AdType: TFullScreenAdType;
149 const WaitUntilLoaded: boolean); override;
150 end;
151 var
152 FBannerSize: TRectangle;
153 FNetworks: array [TAdNetwork] of TAdNetworkHandler;
154 FOnFullScreenAdClosed: TAdClosedEvent;
155 protected
156 procedure FullScreenAdClosed(const WatchedStatus: TAdWatchStatus); virtual;
157 public
158 constructor Create(AOwner: TComponent); override;
159 destructor Destroy; override;
160
161 { Initialize AdMob ads. You need to create the unit ids on AdMob website
162 (or use TestAdMobBannerUnitId, TestAdMobInterstitialUnitId for testing).
163
164 TestDeviceIds may be empty, or it may contain a list of devices
165 where you always want to see test ads --- even with real (non-test) ad units.
166 This is useful when you test ads in your application (with real ad units,
167 on a real phone). Paste here the list of your devices
168 (see https://developers.google.com/mobile-ads-sdk/docs/admob/android/quick-start ,
169 you can see your device ids in "adb logcat" output) in order to avoid
170 getting banned for clicking on your own ads.
171
172 Usually called from @link(TCastleApplication.OnInitialize). }
173 procedure InitializeAdMob(const BannerUnitId, InterstitialUnitId, RewardedUnitId: string;
174 const TestDeviceIds: array of string); overload;
175
176 procedure InitializeAdMob(const BannerUnitId, InterstitialUnitId: string;
177 const TestDeviceIds: array of string); overload;
178
179 { Initialize StartApp ads.
180 You need to register your game on http://startapp.com/ to get app id.
181
182 Usually called from @link(TCastleApplication.OnInitialize). }
183 procedure InitializeStartapp(const AppId: string);
184
185 { Initialize Chartboost ads.
186 You need to register your game on http://chartboost.com/ to get app id and signature.
187
188 Usually called from @link(TCastleApplication.OnInitialize). }
189 procedure InitializeChartboost(const AppId, AppSignature: string);
190
191 { Show full-screen ad, interstitial (in-between) or reward ad.
192
193 Not all ad networks support (or differentiate between) all full-screen
194 ad types possible in TFullScreenAdType enumeration.
195 So we eventually show other sensible ad type instead.
196
197 If WaitUntilLoaded, then we wait until the ad contents are fetched
198 (be sure to show some "loading" state to user, as it may take a while
199 in case of a slow network). If not WaitUntilLoaded, then we immediately
200 resign if ad is not loaded yet. Not all ad implementations support this
201 setting reliably, so this is only a suggestion.
202
203 In any case, after this method is called, we make sure to call callback
204 OnFullScreenAdClosed sometime. }
205 procedure ShowFullScreenAd(const AdNetwork: TAdNetwork;
206 const AdType: TFullScreenAdType;
207 const WaitUntilLoaded: boolean);
208
209 { Show banner ad.
210 Banners are not supported by all ad networks (only AdMob now),
211 in case they are unsupported this call is silently ignored. }
212 procedure ShowBanner(const AdNetwork: TAdNetwork;
213 const HorizontalGravity: THorizontalPosition;
214 const VerticalGravity: TVerticalPosition);
215
216 { Hide banner ad.
217 Banners are not supported by all ad networks (only AdMob now),
218 in case they are unsupported this call is silently ignored. }
219 procedure HideBanner(const AdNetwork: TAdNetwork);
220
221 property OnFullScreenAdClosed: TAdClosedEvent
222 read FOnFullScreenAdClosed write FOnFullScreenAdClosed;
223
224 property BannerSize: TRectangle read FBannerSize;
225 end;
226
227 implementation
228
229 uses SysUtils, StrUtils,
230 CastleUtils, CastleMessaging, CastleLog, CastleApplicationProperties;
231
232 { TAdNetworkHandler ---------------------------------------------------------- }
233
234 constructor TAds.TAdNetworkHandler.Create(const AParent: TAds);
235 begin
236 inherited Create;
237 FParent := AParent;
238 Messaging.OnReceive.Add({$ifdef FPC}@{$endif} MessageReceived);
239 ApplicationProperties.OnInitializeJavaActivity.Add({$ifdef FPC}@{$endif} ReinitializeJavaActivity);
240 end;
241
242 destructor TAds.TAdNetworkHandler.Destroy;
243 begin
244 if Messaging <> nil then
245 Messaging.OnReceive.Remove({$ifdef FPC}@{$endif} MessageReceived);
246 if ApplicationProperties(false) <> nil then
247 ApplicationProperties(false).OnInitializeJavaActivity.Remove({$ifdef FPC}@{$endif} ReinitializeJavaActivity);
248 inherited;
249 end;
250
251 function TAds.TAdNetworkHandler.MessageReceived(const Received: TCastleStringList;
252 const ReceivedStream: TMemoryStream): boolean;
253 var
254 AdWatchStatusInt: Integer;
255 WatchStatus: TAdWatchStatus;
256 begin
257 Result := false;
258
259 if (Received.Count = 2) and
260 (Received[0] = 'ads-' + Name + '-full-screen-ad-closed') then
261 begin
262 if Received[1] = 'true' then
263 WatchStatus := wsWatched
264 else
265 if Received[1] = 'false' then
266 WatchStatus := wsUnknownError
267 else
268 begin
269 if not TryStrToInt(Received[1], AdWatchStatusInt) then
270 raise Exception.CreateFmt('Invalid ad watch status: %s', [Received[1]]);
271 if not Between(AdWatchStatusInt, 0, Ord(High(TAdWatchStatus))) then
272 raise Exception.CreateFmt('Invalid ad watch status: %d', [AdWatchStatusInt]);
273 WatchStatus := TAdWatchStatus(AdWatchStatusInt);
274 end;
275 FullScreenAdClosed(WatchStatus);
276 Result := true;
277 end else
278
279 if (Received.Count = 5) and
280 (Received[0] = 'ads-' + Name + '-banner-size') then
281 begin
282 Result := true;
283 try
284 Parent.FBannerSize := Rectangle(
285 StrToInt(Received[1]),
286 StrToInt(Received[2]),
287 StrToInt(Received[3]),
288 StrToInt(Received[4])
289 );
290 except
291 on EConvertError do
292 WritelnWarning('Ads', 'Cannot process banner size from ' + GlueStrings(Received, NL));
293 end;
294 end;
295 end;
296
297 procedure TAds.TAdNetworkHandler.ShowBanner(const Gravity: Integer);
298 begin
299 FBannerShowing := true;
300 FBannerGravity := Gravity;
301 end;
302
303 procedure TAds.TAdNetworkHandler.HideBanner;
304 begin
305 FBannerShowing := false;
306 end;
307
308 procedure TAds.TAdNetworkHandler.ShowFullScreenAd(const AdType: TFullScreenAdType;
309 const WaitUntilLoaded: boolean);
310 begin
311 { if the network doesn't support showing full-screen ads, pretend it's shown,
312 in case user code waits for OnFullScreenAdClosed. }
313 FullScreenAdClosed(wsAdTypeUnsupported);
314 end;
315
316 procedure TAds.TAdNetworkHandler.ReinitializeJavaActivity(Sender: TObject);
317 begin
318 { this is important if the Java application was killed, but native code survived,
319 while waiting for ad to finish. Reproduce: turn on "kill app when sending to bg"
320 in Android debug options, then use "watch ad" and return to game. }
321 if FFullScreenAdVisible then
322 FullScreenAdClosed(wsApplicationReinitialized);
323 Parent.FBannerSize := TRectangle.Empty;
324 { reshow banner, if necessary }
325 if FBannerShowing then
326 ShowBanner(FBannerGravity);
327 end;
328
329 procedure TAds.TAdNetworkHandler.FullScreenAdClosed(const WatchedStatus: TAdWatchStatus);
330 begin
331 FFullScreenAdVisible := false;
332 Parent.FullScreenAdClosed(WatchedStatus);
333 end;
334
335 { TAdMobHandler -------------------------------------------------------------- }
336
337 constructor TAds.TAdMobHandler.Create(const AParent: TAds;
338 const ABannerUnitId, AInterstitialUnitId, ARewardedUnitId: string;
339 const TestDeviceIds: array of string);
340 begin
341 inherited Create(AParent);
342 FTestDeviceIdsGlued := GlueStrings(TestDeviceIds, ',');
343 FBannerUnitId := ABannerUnitId;
344 FInterstitialUnitId := AInterstitialUnitId;
345 FRewardedUnitId := ARewardedUnitId;
346 ReinitializeJavaActivity(nil);
347 end;
348
349 procedure TAds.TAdMobHandler.ReinitializeJavaActivity(Sender: TObject);
350 begin
351 Messaging.Send(['ads-' + Name + '-initialize', FBannerUnitId, FInterstitialUnitId, FRewardedUnitId, FTestDeviceIdsGlued]);
352 inherited;
353 end;
354
355 class function TAds.TAdMobHandler.Name: string;
356 begin
357 Result := 'admob';
358 end;
359
360 procedure TAds.TAdMobHandler.ShowBanner(const Gravity: Integer);
361 begin
362 inherited;
363 Messaging.Send(['ads-' + Name + '-banner-show', IntToStr(Gravity)]);
364 end;
365
366 procedure TAds.TAdMobHandler.HideBanner;
367 begin
368 Messaging.Send(['ads-' + Name + '-banner-hide']);
369 inherited;
370 end;
371
372 procedure TAds.TAdMobHandler.ShowFullScreenAd(const AdType: TFullScreenAdType; const WaitUntilLoaded: boolean);
373 var
374 AdTypeName: String;
375 WaitUntilLoadedStr: String;
376 begin
377 FFullScreenAdVisible := true;
378
379 AdTypeName := IfThen(AdType = atReward, 'reward', 'interstitial');
380 WaitUntilLoadedStr := IfThen(WaitUntilLoaded, 'wait-until-loaded', 'no-wait');
381 Messaging.Send(['ads-' + Name + '-show-' + AdTypeName, WaitUntilLoadedStr]);
382 end;
383
384 { TChartboostHandler --------------------------------------------------------- }
385
386 constructor TAds.TChartboostHandler.Create(const AParent: TAds;
387 const AnAppId, AnAppSignature: string);
388 begin
389 inherited Create(AParent);
390 FAppId := AnAppId;
391 FAppSignature := AnAppSignature;
392 ReinitializeJavaActivity(nil);
393 end;
394
395 procedure TAds.TChartboostHandler.ReinitializeJavaActivity(Sender: TObject);
396 begin
397 Messaging.Send(['ads-' + Name + '-initialize', FAppId, FAppSignature]);
398 inherited;
399 end;
400
401 class function TAds.TChartboostHandler.Name: string;
402 begin
403 Result := 'chartboost';
404 end;
405
406 procedure TAds.TChartboostHandler.ShowFullScreenAd(const AdType: TFullScreenAdType;
407 const WaitUntilLoaded: boolean);
408 begin
409 FFullScreenAdVisible := true;
410 Messaging.Send(['ads-' + Name + '-show-interstitial']);
411 end;
412
413 { TStartappHandler --------------------------------------------------------- }
414
415 constructor TAds.TStartappHandler.Create(const AParent: TAds;
416 const AnAppId: string);
417 begin
418 inherited Create(AParent);
419 FAppId := AnAppId;
420 ReinitializeJavaActivity(nil);
421 end;
422
423 procedure TAds.TStartappHandler.ReinitializeJavaActivity(Sender: TObject);
424 begin
425 Messaging.Send(['ads-' + Name + '-initialize', FAppId]);
426 inherited;
427 end;
428
429 class function TAds.TStartappHandler.Name: string;
430 begin
431 Result := 'startapp';
432 end;
433
434 procedure TAds.TStartappHandler.ShowFullScreenAd(const AdType: TFullScreenAdType;
435 const WaitUntilLoaded: boolean);
436 begin
437 FFullScreenAdVisible := true;
438 Messaging.Send(['ads-' + Name + '-show-interstitial']);
439 end;
440
441 { TAds ----------------------------------------------------------------------- }
442
443 constructor TAds.Create(AOwner: TComponent);
444 begin
445 inherited;
446 FBannerSize := TRectangle.Empty;
447 end;
448
449 destructor TAds.Destroy;
450 var
451 AdNetwork: TAdNetwork;
452 begin
453 for AdNetwork := Low(AdNetwork) to High(AdNetwork) do
454 FreeAndNil(FNetworks[AdNetwork]);
455 inherited;
456 end;
457
458 procedure TAds.InitializeAdMob(const BannerUnitId, InterstitialUnitId, RewardedUnitId: string;
459 const TestDeviceIds: array of string);
460 begin
461 if FNetworks[anAdMob] <> nil then
462 FreeAndNil(FNetworks[anAdMob]);
463 FNetworks[anAdMob] := TAdMobHandler.Create(Self,
464 BannerUnitId, InterstitialUnitId, RewardedUnitId, TestDeviceIds);
465 end;
466
467 procedure TAds.InitializeAdMob(const BannerUnitId, InterstitialUnitId: string;
468 const TestDeviceIds: array of string);
469 begin
470 InitializeAdMob(BannerUnitId, InterstitialUnitId, '', TestDeviceIds);
471 end;
472
473 procedure TAds.InitializeStartapp(const AppId: string);
474 begin
475 if FNetworks[anStartApp] <> nil then
476 FreeAndNil(FNetworks[anStartApp]);
477 FNetworks[anStartApp] := TStartAppHandler.Create(Self, AppId);
478 end;
479
480 procedure TAds.InitializeChartboost(const AppId, AppSignature: string);
481 begin
482 if FNetworks[anChartboost] <> nil then
483 FreeAndNil(FNetworks[anChartboost]);
484 FNetworks[anChartboost] := TChartboostHandler.Create(Self, AppId, AppSignature);
485 end;
486
487 procedure TAds.FullScreenAdClosed(const WatchedStatus: TAdWatchStatus);
488 begin
489 if Assigned(OnFullScreenAdClosed) then
490 OnFullScreenAdClosed(Self, WatchedStatus);
491 end;
492
493 procedure TAds.ShowFullScreenAd(const AdNetwork: TAdNetwork;
494 const AdType: TFullScreenAdType; const WaitUntilLoaded: boolean);
495 begin
496 {$ifdef ANDROID}
497 if FNetworks[AdNetwork] <> nil then
498 FNetworks[AdNetwork].ShowFullScreenAd(AdType, WaitUntilLoaded)
499 else
500 { if the network is not initialized, pretend it's shown,
501 in case user code waits for OnFullScreenAdClosed. }
502 FullScreenAdClosed(wsAdNetworkNotInitialized);
503 {$else}
504 { since this is not supported on non-Android now, just make
505 FullScreenAdClosed(false) immediately, to avoid the app waiting
506 for OnFullScreenAdClosed forever. }
507 FullScreenAdClosed(wsAdNetworkNotInitialized);
508 {$endif}
509 end;
510
511 procedure TAds.ShowBanner(const AdNetwork: TAdNetwork;
512 const HorizontalGravity: THorizontalPosition;
513 const VerticalGravity: TVerticalPosition);
514
515 function GravityToInt(
516 const HorizontalGravity: THorizontalPosition;
517 const VerticalGravity: TVerticalPosition): Integer;
518 const
519 { Gravity constants for some messages, for example to indicate ad placement.
520 Equal to constants on
521 http://developer.android.com/reference/android/view/Gravity.html .
522 @groupBegin }
523 GravityLeft = $00000003; //< Push object to the left of its container, not changing its size.
524 GravityRight = $00000005; //< Push object to the right of its container, not changing its size.
525 GravityTop = $00000030; //< Push object to the top of its container, not changing its size.
526 GravityBottom = $00000050; //< Push object to the bottom of its container, not changing its size.
527 GravityCenterHorizontal = $00000001; //< Place object in the horizontal center of its container, not changing its size.
528 GravityCenterVertical = $00000010; //< Place object in the vertical center of its container, not changing its size.
529 //GravityNo = 0; //< Constant indicating that no gravity has been set.
530 { @groupEnd }
531 begin
532 Result := 0;
533 case HorizontalGravity of
534 hpLeft: Result := Result or GravityLeft;
535 hpRight: Result := Result or GravityRight;
536 hpMiddle: Result := Result or GravityCenterHorizontal;
537 {$ifndef COMPILER_CASE_ANALYSIS}
538 else raise EInternalError.Create('ShowBanner:HorizontalGravity?');
539 {$endif}
540 end;
541 case VerticalGravity of
542 vpTop: Result := Result or GravityTop;
543 vpBottom: Result := Result or GravityBottom;
544 vpMiddle: Result := Result or GravityCenterVertical;
545 {$ifndef COMPILER_CASE_ANALYSIS}
546 else raise EInternalError.Create('ShowBanner:VerticalGravity?');
547 {$endif}
548 end;
549 end;
550
551 begin
552 if FNetworks[AdNetwork] <> nil then
553 FNetworks[AdNetwork].ShowBanner(GravityToInt(HorizontalGravity, VerticalGravity));
554 end;
555
556 procedure TAds.HideBanner(const AdNetwork: TAdNetwork);
557 begin
558 if FNetworks[AdNetwork] <> nil then
559 FNetworks[AdNetwork].HideBanner;
560 end;
561
562 end.