gdcore-tools 2.0.0-beta6 → 2.0.0-beta8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Runtime/Cordova/config.xml +4 -0
- package/dist/Runtime/Cordova/package.json +12 -20
- package/dist/Runtime/CustomRuntimeObject.js +1 -1
- package/dist/Runtime/CustomRuntimeObject.js.map +2 -2
- package/dist/Runtime/CustomRuntimeObjectInstanceContainer.js +1 -1
- package/dist/Runtime/CustomRuntimeObjectInstanceContainer.js.map +2 -2
- package/dist/Runtime/Extensions/3D/A_RuntimeObject3D.js +1 -1
- package/dist/Runtime/Extensions/3D/A_RuntimeObject3D.js.map +2 -2
- package/dist/Runtime/Extensions/3D/AmbientLight.js +1 -1
- package/dist/Runtime/Extensions/3D/AmbientLight.js.map +2 -2
- package/dist/Runtime/Extensions/3D/CustomRuntimeObject3D.js +1 -1
- package/dist/Runtime/Extensions/3D/CustomRuntimeObject3D.js.map +2 -2
- package/dist/Runtime/Extensions/3D/DirectionalLight.js +1 -1
- package/dist/Runtime/Extensions/3D/DirectionalLight.js.map +2 -2
- package/dist/Runtime/Extensions/3D/ExponentialFog.js +1 -1
- package/dist/Runtime/Extensions/3D/ExponentialFog.js.map +2 -2
- package/dist/Runtime/Extensions/3D/HemisphereLight.js +1 -1
- package/dist/Runtime/Extensions/3D/HemisphereLight.js.map +2 -2
- package/dist/Runtime/Extensions/3D/JsExtension.js +419 -228
- package/dist/Runtime/Extensions/3D/LinearFog.js +1 -1
- package/dist/Runtime/Extensions/3D/LinearFog.js.map +2 -2
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject.js +1 -1
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject.js.map +2 -2
- package/dist/Runtime/Extensions/AdvancedWindow/electron-advancedwindowtools.js +1 -1
- package/dist/Runtime/Extensions/AdvancedWindow/electron-advancedwindowtools.js.map +2 -2
- package/dist/Runtime/Extensions/AnchorBehavior/anchorruntimebehavior.js +1 -1
- package/dist/Runtime/Extensions/AnchorBehavior/anchorruntimebehavior.js.map +2 -2
- package/dist/Runtime/Extensions/BBText/JsExtension.js +45 -42
- package/dist/Runtime/Extensions/BBText/bbtextruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/BBText/bbtextruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/BitmapText/JsExtension.js +40 -49
- package/dist/Runtime/Extensions/BitmapText/bitmaptextruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/BitmapText/bitmaptextruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/Effects/bevel-pixi-filter.js +1 -1
- package/dist/Runtime/Extensions/Effects/bevel-pixi-filter.js.map +2 -2
- package/dist/Runtime/Extensions/Effects/color-replace-pixi-filter.js +1 -1
- package/dist/Runtime/Extensions/Effects/color-replace-pixi-filter.js.map +2 -2
- package/dist/Runtime/Extensions/Effects/drop-shadow-pixi-filter.js +1 -1
- package/dist/Runtime/Extensions/Effects/drop-shadow-pixi-filter.js.map +2 -2
- package/dist/Runtime/Extensions/Effects/glow-pixi-filter.js +1 -1
- package/dist/Runtime/Extensions/Effects/glow-pixi-filter.js.map +2 -2
- package/dist/Runtime/Extensions/Effects/outline-pixi-filter.js +1 -1
- package/dist/Runtime/Extensions/Effects/outline-pixi-filter.js.map +2 -2
- package/dist/Runtime/Extensions/ExampleJsExtension/JsExtension.js +18 -21
- package/dist/Runtime/Extensions/Firebase/B_firebasetools/C_firebasetools.js +1 -1
- package/dist/Runtime/Extensions/Firebase/B_firebasetools/C_firebasetools.js.map +2 -2
- package/dist/Runtime/Extensions/JsExtensionTypes.d.ts +8 -2
- package/dist/Runtime/Extensions/Leaderboards/leaderboardstools.js +1 -1
- package/dist/Runtime/Extensions/Leaderboards/leaderboardstools.js.map +2 -2
- package/dist/Runtime/Extensions/Lighting/JsExtension.js +50 -38
- package/dist/Runtime/Extensions/Lighting/lightruntimeobject-pixi-renderer.js +1 -1
- package/dist/Runtime/Extensions/Lighting/lightruntimeobject-pixi-renderer.js.map +2 -2
- package/dist/Runtime/Extensions/Multiplayer/JsExtension.js +15 -0
- package/dist/Runtime/Extensions/Multiplayer/multiplayerobjectruntimebehavior.js +1 -1
- package/dist/Runtime/Extensions/Multiplayer/multiplayerobjectruntimebehavior.js.map +2 -2
- package/dist/Runtime/Extensions/Multiplayer/multiplayertools.js.map +2 -2
- package/dist/Runtime/Extensions/PanelSpriteObject/panelspriteruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/PanelSpriteObject/panelspriteruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/ParticleSystem/particleemitterobject-pixi-renderer.js +1 -1
- package/dist/Runtime/Extensions/ParticleSystem/particleemitterobject-pixi-renderer.js.map +2 -2
- package/dist/Runtime/Extensions/ParticleSystem/particleemitterobject.js +1 -1
- package/dist/Runtime/Extensions/ParticleSystem/particleemitterobject.js.map +2 -2
- package/dist/Runtime/Extensions/Physics2Behavior/JsExtension.js +76 -24
- package/dist/Runtime/Extensions/Physics2Behavior/physics2runtimebehavior.js +1 -1
- package/dist/Runtime/Extensions/Physics2Behavior/physics2runtimebehavior.js.map +2 -2
- package/dist/Runtime/Extensions/PlayerAuthentication/playerauthenticationtools.js +1 -1
- package/dist/Runtime/Extensions/PlayerAuthentication/playerauthenticationtools.js.map +2 -2
- package/dist/Runtime/Extensions/PrimitiveDrawing/shapepainterruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/PrimitiveDrawing/shapepainterruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/Spine/JsExtension.js +45 -36
- package/dist/Runtime/Extensions/Spine/spineruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/Spine/spineruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/TextInput/JsExtension.js +52 -55
- package/dist/Runtime/Extensions/TextInput/textinputruntimeobject-pixi-renderer.js +1 -1
- package/dist/Runtime/Extensions/TextInput/textinputruntimeobject-pixi-renderer.js.map +2 -2
- package/dist/Runtime/Extensions/TextInput/textinputruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/TextInput/textinputruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/TextObject/textruntimeobject-pixi-renderer.js +1 -1
- package/dist/Runtime/Extensions/TextObject/textruntimeobject-pixi-renderer.js.map +2 -2
- package/dist/Runtime/Extensions/TextObject/textruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/TextObject/textruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/TileMap/JsExtension.js +430 -261
- package/dist/Runtime/Extensions/TileMap/TileMapRuntimeManager.js +1 -1
- package/dist/Runtime/Extensions/TileMap/TileMapRuntimeManager.js.map +2 -2
- package/dist/Runtime/Extensions/TileMap/collision/TransformedTileMap.js +1 -1
- package/dist/Runtime/Extensions/TileMap/collision/TransformedTileMap.js.map +2 -2
- package/dist/Runtime/Extensions/TileMap/helper/TileMapHelper.js +1 -1
- package/dist/Runtime/Extensions/TileMap/helper/TileMapHelper.js.map +1 -1
- package/dist/Runtime/Extensions/TileMap/helper/dts/model/TileMapModel.d.ts.map +1 -1
- package/dist/Runtime/Extensions/TileMap/helper/dts/render/TileMapPixiHelper.d.ts +1 -0
- package/dist/Runtime/Extensions/TileMap/helper/dts/render/TileMapPixiHelper.d.ts.map +1 -1
- package/dist/Runtime/Extensions/TileMap/simpletilemapruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/TileMap/simpletilemapruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/TileMap/tilemapcollisionmaskruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/TileMap/tilemapcollisionmaskruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/TileMap/tilemapruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/TileMap/tilemapruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/TiledSpriteObject/tiledspriteruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/TiledSpriteObject/tiledspriteruntimeobject.js.map +2 -2
- package/dist/Runtime/Extensions/Video/JsExtension.js +35 -44
- package/dist/Runtime/Extensions/Video/videoruntimeobject.js +1 -1
- package/dist/Runtime/Extensions/Video/videoruntimeobject.js.map +2 -2
- package/dist/Runtime/ResourceLoader.js +1 -1
- package/dist/Runtime/ResourceLoader.js.map +2 -2
- package/dist/Runtime/RuntimeInstanceContainer.js.map +2 -2
- package/dist/Runtime/debugger-client/hot-reloader.js +2 -2
- package/dist/Runtime/debugger-client/hot-reloader.js.map +2 -2
- package/dist/Runtime/events-tools/inputtools.js +1 -1
- package/dist/Runtime/events-tools/inputtools.js.map +2 -2
- package/dist/Runtime/events-tools/objecttools.js +1 -1
- package/dist/Runtime/events-tools/objecttools.js.map +2 -2
- package/dist/Runtime/gd.js +1 -1
- package/dist/Runtime/gd.js.map +2 -2
- package/dist/Runtime/howler-sound-manager/howler-sound-manager.js +1 -1
- package/dist/Runtime/howler-sound-manager/howler-sound-manager.js.map +2 -2
- package/dist/Runtime/inputmanager.js +1 -1
- package/dist/Runtime/inputmanager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/CustomRuntimeObject2DPixiRenderer.js +1 -1
- package/dist/Runtime/pixi-renderers/CustomRuntimeObject2DPixiRenderer.js.map +2 -2
- package/dist/Runtime/pixi-renderers/pixi-filters-tools.js +1 -1
- package/dist/Runtime/pixi-renderers/pixi-filters-tools.js.map +2 -2
- package/dist/Runtime/pixi-renderers/runtimegame-pixi-renderer.js +1 -1
- package/dist/Runtime/pixi-renderers/runtimegame-pixi-renderer.js.map +2 -2
- package/dist/Runtime/pixi-renderers/spriteruntimeobject-pixi-renderer.js +1 -1
- package/dist/Runtime/pixi-renderers/spriteruntimeobject-pixi-renderer.js.map +2 -2
- package/dist/Runtime/runtimegame.js +1 -1
- package/dist/Runtime/runtimegame.js.map +1 -1
- package/dist/Runtime/runtimeobject.js +1 -1
- package/dist/Runtime/runtimeobject.js.map +2 -2
- package/dist/Runtime/spriteruntimeobject.js +1 -1
- package/dist/Runtime/spriteruntimeobject.js.map +2 -2
- package/dist/Runtime/types/project-data.d.ts +5 -0
- package/dist/lib/libGD.cjs +1 -1
- package/dist/lib/libGD.d.cts +5 -0
- package/dist/lib/libGD.wasm +0 -0
- package/dist/loaders.cjs +3 -1
- package/dist/loaders.d.cts +2 -0
- package/gd.d.ts +74 -30
- package/package.json +3 -3
|
@@ -287,11 +287,9 @@ module.exports = {
|
|
|
287
287
|
// Everything that is stored inside the object is in "content" and is automatically
|
|
288
288
|
// saved/loaded to JSON.
|
|
289
289
|
var dummyObject = new gd.ObjectJsImplementation();
|
|
290
|
-
dummyObject.updateProperty = function (
|
|
291
|
-
objectContent
|
|
292
|
-
|
|
293
|
-
newValue
|
|
294
|
-
) {
|
|
290
|
+
dummyObject.updateProperty = function (propertyName, newValue) {
|
|
291
|
+
const objectContent = this.content;
|
|
292
|
+
|
|
295
293
|
if (propertyName === 'My first property') {
|
|
296
294
|
objectContent.property1 = newValue;
|
|
297
295
|
return true;
|
|
@@ -311,8 +309,9 @@ module.exports = {
|
|
|
311
309
|
|
|
312
310
|
return false;
|
|
313
311
|
};
|
|
314
|
-
dummyObject.getProperties = function (
|
|
312
|
+
dummyObject.getProperties = function () {
|
|
315
313
|
var objectProperties = new gd.MapStringPropertyDescriptor();
|
|
314
|
+
const objectContent = this.content;
|
|
316
315
|
|
|
317
316
|
objectProperties
|
|
318
317
|
.getOrCreate('My first property')
|
|
@@ -336,17 +335,14 @@ module.exports = {
|
|
|
336
335
|
|
|
337
336
|
return objectProperties;
|
|
338
337
|
};
|
|
339
|
-
dummyObject.
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
})
|
|
346
|
-
);
|
|
338
|
+
dummyObject.content = {
|
|
339
|
+
property1: 'Hello world',
|
|
340
|
+
property2: true,
|
|
341
|
+
property3: 123,
|
|
342
|
+
myImage: '',
|
|
343
|
+
};
|
|
347
344
|
|
|
348
345
|
dummyObject.updateInitialInstanceProperty = function (
|
|
349
|
-
objectContent,
|
|
350
346
|
instance,
|
|
351
347
|
propertyName,
|
|
352
348
|
newValue
|
|
@@ -362,7 +358,7 @@ module.exports = {
|
|
|
362
358
|
|
|
363
359
|
return false;
|
|
364
360
|
};
|
|
365
|
-
dummyObject.getInitialInstanceProperties = function (
|
|
361
|
+
dummyObject.getInitialInstanceProperties = function (instance) {
|
|
366
362
|
var instanceProperties = new gd.MapStringPropertyDescriptor();
|
|
367
363
|
|
|
368
364
|
instanceProperties
|
|
@@ -507,12 +503,13 @@ module.exports = {
|
|
|
507
503
|
* This is called to update the PIXI object on the scene editor
|
|
508
504
|
*/
|
|
509
505
|
update() {
|
|
506
|
+
const object = gd.castObject(
|
|
507
|
+
this._associatedObjectConfiguration,
|
|
508
|
+
gd.ObjectJsImplementation
|
|
509
|
+
);
|
|
510
|
+
|
|
510
511
|
// Read a property from the object
|
|
511
|
-
|
|
512
|
-
.getProperties()
|
|
513
|
-
.get('My first property')
|
|
514
|
-
.getValue();
|
|
515
|
-
this._pixiObject.text = property1Value;
|
|
512
|
+
this._pixiObject.text = object.content.property1;
|
|
516
513
|
|
|
517
514
|
// Read position and angle from the instance
|
|
518
515
|
this._pixiObject.position.x =
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(e){const
|
|
1
|
+
var gdjs;(function(e){const t=new e.Logger("Firebase (setup)");let c;(function(n){let p;(function(r){r.onAppCreated=[],r._setupFirebase=async u=>{try{var i=JSON.parse(u.getGame().getExtensionProperty("Firebase","FirebaseConfig"))}catch(a){t.error("The Firebase configuration is invalid! Error: "+a);return}if(typeof i=="object"){firebase.apps.length!==0&&await firebase.app().delete(),firebase.initializeApp(i);for(let a of r.onAppCreated)try{a()}catch(g){t.error("An error occurred while running a callback: "+g)}}},e.registerFirstRuntimeSceneLoadedCallback(r._setupFirebase)})(p=n.firebaseTools||(n.firebaseTools={}))})(c=e.evtTools||(e.evtTools={}))})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=C_firebasetools.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../GDevelop/Extensions/Firebase/B_firebasetools/C_firebasetools.ts"],
|
|
4
|
-
"sourcesContent": ["namespace gdjs {\n const logger = new gdjs.Logger('Firebase (setup)');\n export namespace evtTools {\n /**\n * Firebase Event Tools\n * @namespace\n */\n export namespace firebaseTools {\n /**\n * An array of callbacks to call when the app gets initialized.\n */\n export const onAppCreated: Array<() => void> = [];\n\n /**\n * Sets up the Firebase SDK. Only exported for testing purposes.\n * @internal\n */\n export const _setupFirebase = async (runtimeScene: gdjs.RuntimeScene) => {\n try {\n var firebaseConfig = JSON.parse(\n //@ts-expect-error We have a try catch to catch this potential error.\n runtimeScene\n .getGame()\n .getExtensionProperty('Firebase', 'FirebaseConfig')\n );\n } catch (e) {\n logger.error('The Firebase configuration is invalid! Error: ' + e);\n return;\n }\n if (typeof firebaseConfig !== 'object') return;\n if (firebase.apps.length !== 0) await firebase.app().delete();\n firebase.initializeApp(firebaseConfig);\n for (let func of onAppCreated) func();\n };\n\n gdjs.registerFirstRuntimeSceneLoadedCallback(_setupFirebase);\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,oBACxB,GAAU,GAAV,UAAU,EAAV,CAKE,GAAU,GAAV,UAAU,EAAV,CAIE,AAAM,eAAkC,GAMlC,iBAAiB,KAAO,IAAoC,CACvE,GAAI,CACF,GAAI,GAAiB,KAAK,MAExB,EACG,UACA,qBAAqB,WAAY,yBAE/B,EAAP,CACA,EAAO,MAAM,iDAAmD,GAChE,OAEF,GAAI,MAAO,IAAmB,SAC9B,CAAI,SAAS,KAAK,SAAW,GAAG,KAAM,UAAS,MAAM,SACrD,SAAS,cAAc,GACvB,OAAS,KAAQ,
|
|
4
|
+
"sourcesContent": ["namespace gdjs {\n const logger = new gdjs.Logger('Firebase (setup)');\n export namespace evtTools {\n /**\n * Firebase Event Tools\n * @namespace\n */\n export namespace firebaseTools {\n /**\n * An array of callbacks to call when the app gets initialized.\n */\n export const onAppCreated: Array<() => void> = [];\n\n /**\n * Sets up the Firebase SDK. Only exported for testing purposes.\n * @internal\n */\n export const _setupFirebase = async (runtimeScene: gdjs.RuntimeScene) => {\n try {\n var firebaseConfig = JSON.parse(\n //@ts-expect-error We have a try catch to catch this potential error.\n runtimeScene\n .getGame()\n .getExtensionProperty('Firebase', 'FirebaseConfig')\n );\n } catch (e) {\n logger.error('The Firebase configuration is invalid! Error: ' + e);\n return;\n }\n if (typeof firebaseConfig !== 'object') return;\n if (firebase.apps.length !== 0) await firebase.app().delete();\n firebase.initializeApp(firebaseConfig);\n for (let func of onAppCreated) {\n try {\n func();\n } catch (e) {\n logger.error('An error occurred while running a callback: ' + e);\n }\n }\n };\n\n gdjs.registerFirstRuntimeSceneLoadedCallback(_setupFirebase);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,oBACxB,GAAU,GAAV,UAAU,EAAV,CAKE,GAAU,GAAV,UAAU,EAAV,CAIE,AAAM,eAAkC,GAMlC,iBAAiB,KAAO,IAAoC,CACvE,GAAI,CACF,GAAI,GAAiB,KAAK,MAExB,EACG,UACA,qBAAqB,WAAY,yBAE/B,EAAP,CACA,EAAO,MAAM,iDAAmD,GAChE,OAEF,GAAI,MAAO,IAAmB,SAC9B,CAAI,SAAS,KAAK,SAAW,GAAG,KAAM,UAAS,MAAM,SACrD,SAAS,cAAc,GACvB,OAAS,KAAQ,gBACf,GAAI,CACF,UACO,EAAP,CACA,EAAO,MAAM,+CAAiD,MAKpE,EAAK,wCAAwC,oBAlC9B,2CALF,iCAFT",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -14,9 +14,12 @@ class RenderedInstance {
|
|
|
14
14
|
_associatedObjectConfiguration: gd.ObjectConfiguration;
|
|
15
15
|
_pixiContainer: PIXI.Container;
|
|
16
16
|
_pixiResourcesLoader: Class<PixiResourcesLoader>;
|
|
17
|
-
_pixiObject: PIXI.DisplayObject;
|
|
17
|
+
_pixiObject: PIXI.DisplayObject | null;
|
|
18
18
|
wasUsed: boolean;
|
|
19
19
|
|
|
20
|
+
/** Set to true when onRemovedFromScene is called. Allows to cancel promises/asynchronous operations (notably: waiting for a resource load). */
|
|
21
|
+
_wasDestroyed: boolean;
|
|
22
|
+
|
|
20
23
|
constructor(
|
|
21
24
|
project: gdProject,
|
|
22
25
|
instance: gdInitialInstance,
|
|
@@ -89,10 +92,13 @@ class Rendered3DInstance {
|
|
|
89
92
|
_pixiContainer: PIXI.Container;
|
|
90
93
|
_threeGroup: THREE.Group;
|
|
91
94
|
_pixiResourcesLoader: Class<PixiResourcesLoader>;
|
|
92
|
-
_pixiObject: PIXI.DisplayObject;
|
|
95
|
+
_pixiObject: PIXI.DisplayObject | null;
|
|
93
96
|
_threeObject: THREE.Object3D | null;
|
|
94
97
|
wasUsed: boolean;
|
|
95
98
|
|
|
99
|
+
/** Set to true when onRemovedFromScene is called. Allows to cancel promises/asynchronous operations (notably: waiting for a resource load). */
|
|
100
|
+
_wasDestroyed: boolean;
|
|
101
|
+
|
|
96
102
|
constructor(
|
|
97
103
|
project: gdProject,
|
|
98
104
|
instance: gdInitialInstance,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(i){const o=new i.Logger("Leaderboards");let G;(function(j){let O;(function(c){let D=!1,k=!0;i.registerRuntimeScenePostEventsCallback(()=>{D=!1}),c.hasPlayerJustClosedLeaderboardView=()=>D;const B=t=>{const e=new jsSHA("SHA-256","TEXT",{encoding:"UTF8"});return e.update(t),e.getHash("B64")},I="https://gd.games";class R{constructor(){this.lastScoreSavingStartedAt=null;this.lastScoreSavingSucceededAt=null;this.lastSavingPromise=null;this._currentlySavingScore=null;this._currentlySavingPlayerName=null;this._currentlySavingPlayerId=null;this._lastSavedScore=null;this._lastSavedPlayerName=null;this._lastSavedPlayerId=null;this.lastSavedLeaderboardEntry=null;this.lastSaveError=null;this.hasScoreBeenSaved=!1;this.hasScoreSavingErrored=!1}isSaving(){return!!this.lastSavingPromise&&!this.hasScoreBeenSaved&&!this.hasScoreSavingErrored}_isSameAsLastScore({playerName:e,playerId:r,score:n}){return(!!e&&this._lastSavedPlayerName===e||!!r&&this._lastSavedPlayerId===r)&&this._lastSavedScore===n}_isAlreadySavingThisScore({playerName:e,playerId:r,score:n}){return this.isSaving()?(!!e&&this._currentlySavingPlayerName===e||!!r&&this._currentlySavingPlayerId===r)&&this._currentlySavingScore===n:!1}_isTooSoonToSaveAnotherScore(){return!!this.lastScoreSavingStartedAt&&Date.now()-this.lastScoreSavingStartedAt<500}startSaving({playerName:e,playerId:r,score:n}){if(this._isAlreadySavingThisScore({playerName:e,playerId:r,score:n}))throw o.warn("There is already a request to save with this player name and this score. Ignoring this one."),new Error("Ignoring this saving request.");if(this._isSameAsLastScore({playerName:e,playerId:r,score:n}))throw o.warn("The player and score to be sent are the same as previous one. Ignoring this one."),this._setError("SAME_AS_PREVIOUS"),new Error("Ignoring this saving request.");if(this._isTooSoonToSaveAnotherScore())throw o.warn("Last entry was sent too little time ago. Ignoring this one."),this._setError("TOO_FAST"),this.lastScoreSavingStartedAt=Date.now(),new Error("Ignoring this saving request.");let a;const g=new Promise(s=>{a=s});return this.lastScoreSavingStartedAt=Date.now(),this.lastSavingPromise=g,this.hasScoreBeenSaved=!1,this.hasScoreSavingErrored=!1,this._currentlySavingScore=n,e&&(this._currentlySavingPlayerName=e),r&&(this._currentlySavingPlayerId=r),{closeSaving:s=>{if(g!==this.lastSavingPromise){o.info("Score saving result received, but another save was launched in the meantime - ignoring the result of this one."),a();return}this.lastScoreSavingSucceededAt=Date.now(),this._lastSavedScore=this._currentlySavingScore,this._lastSavedPlayerName=this._currentlySavingPlayerName,this._lastSavedPlayerId=this._currentlySavingPlayerId,this.lastSavedLeaderboardEntry=s,this.hasScoreBeenSaved=!0,a()},closeSavingWithError:s=>{if(g!==this.lastSavingPromise){o.info("Score saving result received, but another save was launched in the meantime - ignoring the result of this one."),a();return}this._setError(s),a()}}}_setError(e){this.lastSaveError=e,this.hasScoreBeenSaved=!1,this.hasScoreSavingErrored=!0}}let u={},C,l=null,M=!1,E=!1,f=!1,A=null,T=null;const h=document.createElement("div");h.style.backgroundColor="#000000",h.style.display="flex",h.style.height="100%",h.style.width="100%",h.style.justifyContent="center",h.style.alignItems="center",h.style.position="relative",h.style.zIndex="2";const _=document.createElement("img");_.setAttribute("width","50px"),_.setAttribute("src","data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCI+CjxjaXJjbGUgb3BhY2l0eT0nMC4yNScgY3g9IjEyIiBjeT0iMTIiIHI9IjEwIiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iNCI+PC9jaXJjbGU+CjxwYXRoIG9wYWNpdHk9JzAuNzUnIGZpbGw9IiNGRkZGRkYiIGQ9Ik00IDEyYTggOCAwIDAxOC04VjBDNS4zNzMgMCAwIDUuMzczIDAgMTJoNHptMiA1LjI5MUE3Ljk2MiA3Ljk2MiAwIDAxNCAxMkgwYzAgMy4wNDIgMS4xMzUgNS44MjQgMyA3LjkzOGwzLTIuNjQ3eiI+PC9wYXRoPgo8L3N2Zz4=");try{_.animate([{transform:"rotate(0deg)"},{transform:"rotate(359deg)"}],{duration:3e3,iterations:1/0})}catch{o.warn("Animation not supported, loader will be fixed.")}h.appendChild(_);const P=function({hasSucceeded:t}){const e=a=>t?a.lastScoreSavingSucceededAt:a.lastScoreSavingStartedAt,r=Object.values(u).filter(a=>!!e(a));if(r.length===0)return null;let n=r[0];return r.forEach(a=>{const g=e(a),s=e(n);g&&s&&g>s&&(n=a)}),n},x=async function({leaderboardId:t,playerName:e,authenticatedPlayerData:r,score:n,runtimeScene:a}){const s=`${a.getGame().isUsingGDevelopDevelopmentEnvironment()?"https://api-dev.gdevelop.io":"https://api.gdevelop.io"}/play`,d=a.getGame(),S={score:n,sessionId:d.getSessionId(),clientPlayerId:d.getPlayerId(),location:typeof window!="undefined"&&window.location?window.location.href:""},p={"Content-Type":"application/json"};let w=`${s}/game/${i.projectData.properties.projectUuid}/leaderboard/${t}/entry`;r?(p.Authorization=`player-game-token ${r.playerToken}`,w+=`?playerId=${r.playerId}`):S.playerName=c.formatPlayerName(e);const b=JSON.stringify(S);p.Digest=B(b);try{const v=await fetch(w,{body:b,method:"POST",headers:p});if(!v.ok){const y=v.status.toString();throw o.error("Server responded with an error:",y,v.statusText),y}try{return await v.json()}catch(y){throw o.warn("An error occurred when reading response but score has been saved:",y),"SAVED_ENTRY_CANT_BE_READ"}}catch(v){throw o.error("Error while submitting a leaderboard score:",v),"REQUEST_NOT_SENT"}};c.setPreferSendConnectedPlayerScore=(t,e)=>{k=e},c.savePlayerScore=(t,e,r,n)=>k&&i.playerAuthentication.isAuthenticated()?c.saveConnectedPlayerScore(t,e,r):new i.PromiseTask((async()=>{const a=u[e]=u[e]||new R;try{const{closeSaving:g,closeSavingWithError:s}=a.startSaving({playerName:n,score:r});try{const d=await x({leaderboardId:e,playerName:n,score:r,runtimeScene:t});g(d)}catch(d){s(d)}}catch{}})()),c.saveConnectedPlayerScore=(t,e,r)=>new i.PromiseTask((async()=>{const n=i.playerAuthentication.getUserId(),a=i.playerAuthentication.getUserToken();if(!n||!a){o.warn("Cannot save a score for a connected player if the player is not connected.");return}const g=u[e]=u[e]||new R;try{const{closeSaving:s,closeSavingWithError:d}=g.startSaving({playerId:n,score:r});try{const S=await x({leaderboardId:e,authenticatedPlayerData:{playerId:n,playerToken:a},score:r,runtimeScene:t});s(S)}catch(S){d(S)}}catch{}})()),c.isSaving=function(t){if(t)return u[t]?u[t].isSaving():!1;const e=P({hasSucceeded:!1});return e?e.isSaving():!1},c.hasBeenSaved=function(t){if(t)return u[t]?u[t].hasScoreBeenSaved:!1;const e=P({hasSucceeded:!0});return e?e.hasScoreBeenSaved:!1},c.hasSavingErrored=function(t){if(t)return u[t]?u[t].hasScoreSavingErrored:!1;const e=P({hasSucceeded:!1});return e?e.hasScoreSavingErrored:!1},c.getLastSaveError=function(t){if(t)return u[t]?u[t].lastSaveError:"NO_DATA_ERROR";const e=P({hasSucceeded:!1});return e?e.lastSaveError:"NO_DATA_ERROR"},c.formatPlayerName=function(t){return!t||typeof t!="string"||typeof t=="string"&&t.length===0?"":t.trim().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s/g,"_").replace(/[^\w|-]/g,"").slice(0,30)};const $=function(t){return fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}).then(e=>e.ok?!0:(o.error(`Error while fetching leaderboard view, server returned: ${e.status} ${e.statusText}`),!1),e=>(o.error("Error while fetching leaderboard view:",e),!1))},H=function(t,e,r){switch(typeof r.data=="string"?r.data:r.data.id){case"playerAuthenticated":i.playerAuthentication.login({runtimeScene:t,userId:r.data.userId,username:r.data.username,userToken:r.data.userToken});break;case"openPlayerAuthentication":i.playerAuthentication.openAuthenticationWindow(t).promise.then(({status:a})=>{if(!l||!l.contentWindow){o.warn("Unable to transmit the new login status to the leaderboard view.");return}if(a==="errored"){l.contentWindow.postMessage({id:"onPlayerAuthenticationErrored"},I);return}const g=i.playerAuthentication.getUserId(),s=i.playerAuthentication.getUserToken();if(a==="dismissed"||!g||!s){l.contentWindow.postMessage({id:"onPlayerAuthenticationDismissed"},I);return}l.contentWindow.postMessage({id:"onPlayerAuthenticated",playerId:g,playerUsername:i.playerAuthentication.getUsername(),playerToken:s},I)});break;case"closeLeaderboardView":D=!0,c.closeLeaderboardView(t);break;case"leaderboardViewLoaded":if(e&&(A&&clearTimeout(A),L(!1,t,{callOnErrorIfDomElementContainerMissing:!1})),!l){m(t,"The leaderboard view couldn't be found. Doing nothing.");return}l.style.opacity="1",f=!0,E=!1;break}},m=function(t,e){o.error(e),M=!0,E=!1,c.closeLeaderboardView(t)},U=t=>{A&&clearTimeout(A),A=setTimeout(()=>{f||m(t,"Leaderboard page did not send message in time. Closing leaderboard view.")},15e3)},L=function(t,e,r){const n=e.getGame().getRenderer().getDomElementContainer();if(!n)return r.callOnErrorIfDomElementContainerMissing&&m(e,"The div element covering the game couldn't be found, the leaderboard cannot be displayed."),!1;if(t)n.children&&n.children.length>0?n.insertBefore(h,n.children[0]):n.appendChild(h),l&&(l.style.opacity="0");else try{n.removeChild(h),l&&(l.style.opacity="1")}catch{}return!0},F=function(t){const e=document.createElement("iframe");return e.src=t,e.id="leaderboard-view",e.style.position="absolute",e.style.opacity="0",e.style.pointerEvents="all",e.style.backgroundColor="#FFFFFF",e.style.top="0px",e.style.height="100%",e.style.left="0px",e.style.width="100%",e.style.border="none",e};c.displayLeaderboard=async function(t,e,r){if(e===C){if(E){o.warn(`Already loading the view for the requested loader (${e}), ignoring.`);return}if(f){o.warn(`Already loaded the view for the requested loader (${e}), ignoring.`);return}}C=e,M=!1,f=!1,E=!0,r&&L(!0,t,{callOnErrorIfDomElementContainerMissing:!0});const n=u[e];n&&n.lastSavingPromise&&await n.lastSavingPromise;const a=n?n.lastSavedLeaderboardEntry:null,g=i.projectData.properties.projectUuid,s=t.getGame().isUsingGDevelopDevelopmentEnvironment(),d=new URLSearchParams;d.set("inGameEmbedded","true"),s&&d.set("dev","true"),a&&(d.set("playerLeaderboardEntryId",a.id),a.claimSecret&&d.set("playerLeaderboardEntryClaimSecret",a.claimSecret));const S=i.playerAuthentication.getUserId(),p=i.playerAuthentication.getUserToken();S&&p&&(d.set("playerId",S),d.set("playerToken",p),d.set("playerUsername",i.playerAuthentication.getUsername()));const w=`${I}/games/${g}/leaderboard/${e}?${d}`;try{const b=await $(w);if(e!==C){o.warn(`Received a response for leaderboard ${e} though the last leaderboard requested is ${C}, ignoring this response.`);return}if(!b){m(t,"Leaderboard data could not be fetched. Closing leaderboard view if there is one.");return}if(l)U(t),r&&L(!0,t,{callOnErrorIfDomElementContainerMissing:!1}),l.src=w;else{const v=t.getGame().getRenderer().getDomElementContainer();if(!v){m(t,"The div element covering the game couldn't be found, the leaderboard cannot be displayed.");return}U(t),l=F(w),typeof window!="undefined"&&(T=y=>{H(t,r,y)},window.addEventListener("message",T,!0)),v.appendChild(l)}}catch(b){o.error(b),m(t,"An error occurred when fetching leaderboard data. Closing leaderboard view if there is one.")}},c.isLeaderboardViewErrored=function(){return M},c.isLeaderboardViewLoaded=function(){return f},c.isLeaderboardViewLoading=function(){return E},c.closeLeaderboardView=function(t){try{if(L(!1,t,{callOnErrorIfDomElementContainerMissing:!1}),!l){o.info("The iframe displaying the current leaderboard couldn't be found, the leaderboard view must be already closed.");return}const e=t.getGame().getRenderer().getDomElementContainer();if(!e){o.info("The div element covering the game couldn't be found, the leaderboard view must be already closed.");return}typeof window!="undefined"&&(window.removeEventListener("message",T,!0),T=null),e.removeChild(l),l=null}finally{f=!1;const e=t.getGame().getRenderer().getCanvas();e&&e.focus()}}})(O=j.leaderboards||(j.leaderboards={}))})(G=i.evtTools||(i.evtTools={}))})(gdjs||(gdjs={}));
|
|
1
|
+
var gdjs;(function(i){const o=new i.Logger("Leaderboards");let G;(function(j){let O;(function(c){let D=!1,k=!0;i.registerRuntimeScenePostEventsCallback(()=>{D=!1}),c.hasPlayerJustClosedLeaderboardView=()=>D;const B=t=>{const e=new jsSHA("SHA-256","TEXT",{encoding:"UTF8"});return e.update(t),e.getHash("B64")},I="https://gd.games";class R{constructor(){this.lastScoreSavingStartedAt=null;this.lastScoreSavingSucceededAt=null;this.lastSavingPromise=null;this._currentlySavingScore=null;this._currentlySavingPlayerName=null;this._currentlySavingPlayerId=null;this._lastSavedScore=null;this._lastSavedPlayerName=null;this._lastSavedPlayerId=null;this.lastSavedLeaderboardEntry=null;this.lastSaveError=null;this.hasScoreBeenSaved=!1;this.hasScoreSavingErrored=!1}isSaving(){return!!this.lastSavingPromise&&!this.hasScoreBeenSaved&&!this.hasScoreSavingErrored}_isSameAsLastScore({playerName:e,playerId:r,score:n}){return(!!e&&this._lastSavedPlayerName===e||!!r&&this._lastSavedPlayerId===r)&&this._lastSavedScore===n}_isAlreadySavingThisScore({playerName:e,playerId:r,score:n}){return this.isSaving()?(!!e&&this._currentlySavingPlayerName===e||!!r&&this._currentlySavingPlayerId===r)&&this._currentlySavingScore===n:!1}_isTooSoonToSaveAnotherScore(){return!!this.lastScoreSavingStartedAt&&Date.now()-this.lastScoreSavingStartedAt<500}startSaving({playerName:e,playerId:r,score:n}){if(this._isAlreadySavingThisScore({playerName:e,playerId:r,score:n}))throw o.warn("There is already a request to save with this player name and this score. Ignoring this one."),new Error("Ignoring this saving request.");if(this._isSameAsLastScore({playerName:e,playerId:r,score:n}))throw o.warn("The player and score to be sent are the same as previous one. Ignoring this one."),this._setError("SAME_AS_PREVIOUS"),new Error("Ignoring this saving request.");if(this._isTooSoonToSaveAnotherScore())throw o.warn("Last entry was sent too little time ago. Ignoring this one."),this._setError("TOO_FAST"),this.lastScoreSavingStartedAt=Date.now(),new Error("Ignoring this saving request.");let a;const g=new Promise(s=>{a=s});return this.lastScoreSavingStartedAt=Date.now(),this.lastSavingPromise=g,this.hasScoreBeenSaved=!1,this.hasScoreSavingErrored=!1,this._currentlySavingScore=n,e&&(this._currentlySavingPlayerName=e),r&&(this._currentlySavingPlayerId=r),{closeSaving:s=>{if(g!==this.lastSavingPromise){o.info("Score saving result received, but another save was launched in the meantime - ignoring the result of this one."),a();return}this.lastScoreSavingSucceededAt=Date.now(),this._lastSavedScore=this._currentlySavingScore,this._lastSavedPlayerName=this._currentlySavingPlayerName,this._lastSavedPlayerId=this._currentlySavingPlayerId,this.lastSavedLeaderboardEntry=s,this.hasScoreBeenSaved=!0,a()},closeSavingWithError:s=>{if(g!==this.lastSavingPromise){o.info("Score saving result received, but another save was launched in the meantime - ignoring the result of this one."),a();return}this._setError(s),a()}}}_setError(e){this.lastSaveError=e,this.hasScoreBeenSaved=!1,this.hasScoreSavingErrored=!0}}let u={},C,l=null,M=!1,E=!1,f=!1,A=null,T=null;const h=document.createElement("div");h.style.backgroundColor="#000000",h.style.display="flex",h.style.height="100%",h.style.width="100%",h.style.justifyContent="center",h.style.alignItems="center",h.style.position="relative",h.style.zIndex="2";const _=document.createElement("img");_.setAttribute("width","50px"),_.setAttribute("src","data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCI+CjxjaXJjbGUgb3BhY2l0eT0nMC4yNScgY3g9IjEyIiBjeT0iMTIiIHI9IjEwIiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iNCI+PC9jaXJjbGU+CjxwYXRoIG9wYWNpdHk9JzAuNzUnIGZpbGw9IiNGRkZGRkYiIGQ9Ik00IDEyYTggOCAwIDAxOC04VjBDNS4zNzMgMCAwIDUuMzczIDAgMTJoNHptMiA1LjI5MUE3Ljk2MiA3Ljk2MiAwIDAxNCAxMkgwYzAgMy4wNDIgMS4xMzUgNS44MjQgMyA3LjkzOGwzLTIuNjQ3eiI+PC9wYXRoPgo8L3N2Zz4=");try{_.animate([{transform:"rotate(0deg)"},{transform:"rotate(359deg)"}],{duration:3e3,iterations:1/0})}catch{o.warn("Animation not supported, loader will be fixed.")}h.appendChild(_);const P=function({hasSucceeded:t}){const e=a=>t?a.lastScoreSavingSucceededAt:a.lastScoreSavingStartedAt,r=Object.values(u).filter(a=>!!e(a));if(r.length===0)return null;let n=r[0];return r.forEach(a=>{const g=e(a),s=e(n);g&&s&&g>s&&(n=a)}),n},x=async function({leaderboardId:t,playerName:e,authenticatedPlayerData:r,score:n,runtimeScene:a}){const s=`${a.getGame().isUsingGDevelopDevelopmentEnvironment()?"https://api-dev.gdevelop.io":"https://api.gdevelop.io"}/play`,d=a.getGame(),S={score:n,sessionId:d.getSessionId(),clientPlayerId:d.getPlayerId(),location:typeof window!="undefined"&&window.location?window.location.href:""},p={"Content-Type":"application/json"};let w=`${s}/game/${i.projectData.properties.projectUuid}/leaderboard/${t}/entry`;r?(p.Authorization=`player-game-token ${r.playerToken}`,w+=`?playerId=${r.playerId}`):S.playerName=c.formatPlayerName(e);const b=JSON.stringify(S);p.Digest=B(b);try{const v=await fetch(w,{body:b,method:"POST",headers:p});if(!v.ok){const y=v.status.toString();throw o.error("Server responded with an error:",y,v.statusText),y}try{return await v.json()}catch(y){throw o.warn("An error occurred when reading response but score has been saved:",y),"SAVED_ENTRY_CANT_BE_READ"}}catch(v){throw o.error("Error while submitting a leaderboard score:",v),"REQUEST_NOT_SENT"}};c.setPreferSendConnectedPlayerScore=(t,e)=>{k=e},c.savePlayerScore=(t,e,r,n)=>k&&i.playerAuthentication.isAuthenticated()?c.saveConnectedPlayerScore(t,e,r):new i.PromiseTask((async()=>{const a=u[e]=u[e]||new R;try{const{closeSaving:g,closeSavingWithError:s}=a.startSaving({playerName:n,score:r});try{const d=await x({leaderboardId:e,playerName:n,score:r,runtimeScene:t});g(d)}catch(d){s(d)}}catch{}})()),c.saveConnectedPlayerScore=(t,e,r)=>new i.PromiseTask((async()=>{const n=i.playerAuthentication.getUserId(),a=i.playerAuthentication.getUserToken();if(!n||!a){o.warn("Cannot save a score for a connected player if the player is not connected.");return}const g=u[e]=u[e]||new R;try{const{closeSaving:s,closeSavingWithError:d}=g.startSaving({playerId:n,score:r});try{const S=await x({leaderboardId:e,authenticatedPlayerData:{playerId:n,playerToken:a},score:r,runtimeScene:t});s(S)}catch(S){d(S)}}catch{}})()),c.isSaving=function(t){if(t)return u[t]?u[t].isSaving():!1;const e=P({hasSucceeded:!1});return e?e.isSaving():!1},c.hasBeenSaved=function(t){if(t)return u[t]?u[t].hasScoreBeenSaved:!1;const e=P({hasSucceeded:!0});return e?e.hasScoreBeenSaved:!1},c.hasSavingErrored=function(t){if(t)return u[t]?u[t].hasScoreSavingErrored:!1;const e=P({hasSucceeded:!1});return e?e.hasScoreSavingErrored:!1},c.getLastSaveError=function(t){if(t)return u[t]?u[t].lastSaveError:"NO_DATA_ERROR";const e=P({hasSucceeded:!1});return e?e.lastSaveError:"NO_DATA_ERROR"},c.formatPlayerName=function(t){return!t||typeof t!="string"||typeof t=="string"&&t.length===0?"":t.trim().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\s/g,"_").replace(/[^\w|-]/g,"").slice(0,30)};const $=function(t){return fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}).then(e=>e.ok?!0:(o.error(`Error while fetching leaderboard view, server returned: ${e.status} ${e.statusText}`),!1),e=>(o.error("Error while fetching leaderboard view:",e),!1))},H=function(t,e,r){switch(typeof r.data=="string"?r.data:r.data.id){case"playerAuthenticated":i.playerAuthentication.login({runtimeScene:t,userId:r.data.userId,username:r.data.username,userToken:r.data.userToken});break;case"openPlayerAuthentication":i.playerAuthentication.openAuthenticationWindow(t,r.data.options).promise.then(({status:a})=>{if(!l||!l.contentWindow){o.warn("Unable to transmit the new login status to the leaderboard view.");return}if(a==="errored"){l.contentWindow.postMessage({id:"onPlayerAuthenticationErrored"},I);return}const g=i.playerAuthentication.getUserId(),s=i.playerAuthentication.getUserToken();if(a==="dismissed"||!g||!s){l.contentWindow.postMessage({id:"onPlayerAuthenticationDismissed"},I);return}l.contentWindow.postMessage({id:"onPlayerAuthenticated",playerId:g,playerUsername:i.playerAuthentication.getUsername(),playerToken:s},I)});break;case"closeLeaderboardView":D=!0,c.closeLeaderboardView(t);break;case"leaderboardViewLoaded":if(e&&(A&&clearTimeout(A),L(!1,t,{callOnErrorIfDomElementContainerMissing:!1})),!l){m(t,"The leaderboard view couldn't be found. Doing nothing.");return}l.style.opacity="1",f=!0,E=!1;break}},m=function(t,e){o.error(e),M=!0,E=!1,c.closeLeaderboardView(t)},U=t=>{A&&clearTimeout(A),A=setTimeout(()=>{f||m(t,"Leaderboard page did not send message in time. Closing leaderboard view.")},15e3)},L=function(t,e,r){const n=e.getGame().getRenderer().getDomElementContainer();if(!n)return r.callOnErrorIfDomElementContainerMissing&&m(e,"The div element covering the game couldn't be found, the leaderboard cannot be displayed."),!1;if(t)n.children&&n.children.length>0?n.insertBefore(h,n.children[0]):n.appendChild(h),l&&(l.style.opacity="0");else try{n.removeChild(h),l&&(l.style.opacity="1")}catch{}return!0},F=function(t){const e=document.createElement("iframe");return e.src=t,e.id="leaderboard-view",e.style.position="absolute",e.style.opacity="0",e.style.pointerEvents="all",e.style.backgroundColor="#FFFFFF",e.style.top="0px",e.style.height="100%",e.style.left="0px",e.style.width="100%",e.style.border="none",e};c.displayLeaderboard=async function(t,e,r){if(e===C){if(E){o.warn(`Already loading the view for the requested loader (${e}), ignoring.`);return}if(f){o.warn(`Already loaded the view for the requested loader (${e}), ignoring.`);return}}C=e,M=!1,f=!1,E=!0,r&&L(!0,t,{callOnErrorIfDomElementContainerMissing:!0});const n=u[e];n&&n.lastSavingPromise&&await n.lastSavingPromise;const a=n?n.lastSavedLeaderboardEntry:null,g=i.projectData.properties.projectUuid,s=t.getGame().isUsingGDevelopDevelopmentEnvironment(),d=new URLSearchParams;d.set("inGameEmbedded","true"),s&&d.set("dev","true"),a&&(d.set("playerLeaderboardEntryId",a.id),a.claimSecret&&d.set("playerLeaderboardEntryClaimSecret",a.claimSecret));const S=i.playerAuthentication.getUserId(),p=i.playerAuthentication.getUserToken();S&&p&&(d.set("playerId",S),d.set("playerToken",p),d.set("playerUsername",i.playerAuthentication.getUsername()));const w=`${I}/games/${g}/leaderboard/${e}?${d}`;try{const b=await $(w);if(e!==C){o.warn(`Received a response for leaderboard ${e} though the last leaderboard requested is ${C}, ignoring this response.`);return}if(!b){m(t,"Leaderboard data could not be fetched. Closing leaderboard view if there is one.");return}if(l)U(t),r&&L(!0,t,{callOnErrorIfDomElementContainerMissing:!1}),l.src=w;else{const v=t.getGame().getRenderer().getDomElementContainer();if(!v){m(t,"The div element covering the game couldn't be found, the leaderboard cannot be displayed.");return}U(t),l=F(w),typeof window!="undefined"&&(T=y=>{H(t,r,y)},window.addEventListener("message",T,!0)),v.appendChild(l)}}catch(b){o.error(b),m(t,"An error occurred when fetching leaderboard data. Closing leaderboard view if there is one.")}},c.isLeaderboardViewErrored=function(){return M},c.isLeaderboardViewLoaded=function(){return f},c.isLeaderboardViewLoading=function(){return E},c.closeLeaderboardView=function(t){try{if(L(!1,t,{callOnErrorIfDomElementContainerMissing:!1}),!l){o.info("The iframe displaying the current leaderboard couldn't be found, the leaderboard view must be already closed.");return}const e=t.getGame().getRenderer().getDomElementContainer();if(!e){o.info("The div element covering the game couldn't be found, the leaderboard view must be already closed.");return}typeof window!="undefined"&&(window.removeEventListener("message",T,!0),T=null),e.removeChild(l),l=null}finally{f=!1;const e=t.getGame().getRenderer().getCanvas();e&&e.focus()}}})(O=j.leaderboards||(j.leaderboards={}))})(G=i.evtTools||(i.evtTools={}))})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=leaderboardstools.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../GDevelop/Extensions/Leaderboards/leaderboardstools.ts"],
|
|
4
|
-
"sourcesContent": ["/// <reference path=\"sha256.d.ts\" />\n\n// TODO EBO Replace runtimeScene to instanceContainer.\nnamespace gdjs {\n const logger = new gdjs.Logger('Leaderboards');\n export namespace evtTools {\n export namespace leaderboards {\n let _hasPlayerJustClosedLeaderboardView = false;\n let _preferSendConnectedPlayerScore = true;\n\n gdjs.registerRuntimeScenePostEventsCallback(() => {\n // Set it back to false for the next frame.\n _hasPlayerJustClosedLeaderboardView = false;\n });\n\n /**\n * Returns true if the player has just closed the leaderboard view.\n */\n export const hasPlayerJustClosedLeaderboardView = () =>\n _hasPlayerJustClosedLeaderboardView;\n\n const computeDigest = (payload: string): string => {\n const shaObj = new jsSHA('SHA-256', 'TEXT', { encoding: 'UTF8' });\n shaObj.update(payload);\n return shaObj.getHash('B64');\n };\n\n const leaderboardHostBaseUrl = 'https://gd.games';\n // const leaderboardHostBaseUrl = 'http://localhost:4000';\n\n type PublicLeaderboardEntry = {\n id: string;\n claimSecret?: string;\n };\n\n /**\n * Hold the state of the save of a score for a leaderboard.\n */\n class ScoreSavingState {\n lastScoreSavingStartedAt: number | null = null;\n lastScoreSavingSucceededAt: number | null = null;\n\n /** The promise that will be resolved when the score saving is done (successfully or not). */\n lastSavingPromise: Promise<void> | null = null;\n\n // Score that is being saved:\n private _currentlySavingScore: number | null = null;\n private _currentlySavingPlayerName: string | null = null;\n private _currentlySavingPlayerId: string | null = null;\n\n // Last score saved with success:\n private _lastSavedScore: number | null = null;\n private _lastSavedPlayerName: string | null = null;\n private _lastSavedPlayerId: string | null = null;\n\n /** The id of the entry in the leaderboard, for the last score saved with success. */\n lastSavedLeaderboardEntry: PublicLeaderboardEntry | null = null;\n\n /** Last error that happened when saving the score (useful if `hasScoreSavingErrored` is true). */\n lastSaveError: string | null = null;\n\n /** `true` if the last save has finished and succeeded. */\n hasScoreBeenSaved: boolean = false;\n\n /** `true` if the last save has finished and failed (check `lastSaveError` then). */\n hasScoreSavingErrored: boolean = false;\n\n isSaving(): boolean {\n return (\n !!this.lastSavingPromise &&\n !this.hasScoreBeenSaved &&\n !this.hasScoreSavingErrored\n );\n }\n\n private _isSameAsLastScore({\n playerName,\n playerId,\n score,\n }: {\n playerName?: string;\n playerId?: string;\n score: number;\n }): boolean {\n return (\n ((!!playerName && this._lastSavedPlayerName === playerName) ||\n (!!playerId && this._lastSavedPlayerId === playerId)) &&\n this._lastSavedScore === score\n );\n }\n\n private _isAlreadySavingThisScore({\n playerName,\n playerId,\n score,\n }: {\n playerName?: string;\n playerId?: string;\n score: number;\n }): boolean {\n if (!this.isSaving()) return false;\n\n return (\n ((!!playerName && this._currentlySavingPlayerName === playerName) ||\n (!!playerId && this._currentlySavingPlayerId === playerId)) &&\n this._currentlySavingScore === score\n );\n }\n\n private _isTooSoonToSaveAnotherScore(): boolean {\n return (\n !!this.lastScoreSavingStartedAt &&\n Date.now() - this.lastScoreSavingStartedAt < 500\n );\n }\n\n startSaving({\n playerName,\n playerId,\n score,\n }: {\n playerName?: string;\n playerId?: string;\n score: number;\n }): {\n closeSaving: (leaderboardEntry: PublicLeaderboardEntry) => void;\n closeSavingWithError(errorCode: string);\n } {\n if (this._isAlreadySavingThisScore({ playerName, playerId, score })) {\n logger.warn(\n 'There is already a request to save with this player name and this score. Ignoring this one.'\n );\n throw new Error('Ignoring this saving request.');\n }\n\n if (this._isSameAsLastScore({ playerName, playerId, score })) {\n logger.warn(\n 'The player and score to be sent are the same as previous one. Ignoring this one.'\n );\n this._setError('SAME_AS_PREVIOUS');\n throw new Error('Ignoring this saving request.');\n }\n\n if (this._isTooSoonToSaveAnotherScore()) {\n logger.warn(\n 'Last entry was sent too little time ago. Ignoring this one.'\n );\n this._setError('TOO_FAST');\n\n // Set the starting time to cancel all the following attempts that\n // are started too early after this one.\n this.lastScoreSavingStartedAt = Date.now();\n\n throw new Error('Ignoring this saving request.');\n }\n\n let resolveSavingPromise: () => void;\n const savingPromise = new Promise<void>((resolve) => {\n resolveSavingPromise = resolve;\n });\n\n this.lastScoreSavingStartedAt = Date.now();\n this.lastSavingPromise = savingPromise;\n this.hasScoreBeenSaved = false;\n this.hasScoreSavingErrored = false;\n this._currentlySavingScore = score;\n if (playerName) this._currentlySavingPlayerName = playerName;\n if (playerId) this._currentlySavingPlayerId = playerId;\n\n return {\n closeSaving: (leaderboardEntry) => {\n if (savingPromise !== this.lastSavingPromise) {\n logger.info(\n 'Score saving result received, but another save was launched in the meantime - ignoring the result of this one.'\n );\n\n // Still finish the promise that can be waited upon:\n resolveSavingPromise();\n return;\n }\n\n this.lastScoreSavingSucceededAt = Date.now();\n this._lastSavedScore = this._currentlySavingScore;\n this._lastSavedPlayerName = this._currentlySavingPlayerName;\n this._lastSavedPlayerId = this._currentlySavingPlayerId;\n this.lastSavedLeaderboardEntry = leaderboardEntry;\n this.hasScoreBeenSaved = true;\n\n resolveSavingPromise();\n },\n closeSavingWithError: (errorCode) => {\n if (savingPromise !== this.lastSavingPromise) {\n logger.info(\n 'Score saving result received, but another save was launched in the meantime - ignoring the result of this one.'\n );\n\n // Still finish the promise that can be waited upon:\n resolveSavingPromise();\n return;\n }\n\n this._setError(errorCode);\n resolveSavingPromise();\n },\n };\n }\n\n private _setError(errorCode: string): void {\n this.lastSaveError = errorCode;\n this.hasScoreBeenSaved = false;\n this.hasScoreSavingErrored = true;\n }\n }\n\n let _scoreSavingStateByLeaderboard: {\n [leaderboardId: string]: ScoreSavingState;\n } = {};\n\n // Leaderboard display\n let _requestedLeaderboardId: string | null;\n let _leaderboardViewIframe: HTMLIFrameElement | null = null;\n let _leaderboardViewIframeErrored: boolean = false;\n let _leaderboardViewIframeLoading: boolean = false;\n let _leaderboardViewIframeLoaded: boolean = false;\n let _errorTimeoutId: NodeJS.Timeout | null = null;\n let _leaderboardMessageListener:\n | ((event: MessageEvent) => void)\n | null = null;\n\n const _loaderContainer: HTMLDivElement = document.createElement('div');\n _loaderContainer.style.backgroundColor = '#000000';\n _loaderContainer.style.display = 'flex';\n _loaderContainer.style.height = '100%';\n _loaderContainer.style.width = '100%';\n _loaderContainer.style.justifyContent = 'center';\n _loaderContainer.style.alignItems = 'center';\n _loaderContainer.style.position = 'relative';\n _loaderContainer.style.zIndex = '2';\n const _loader = document.createElement('img');\n _loader.setAttribute('width', '50px');\n _loader.setAttribute(\n 'src',\n 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCI+CjxjaXJjbGUgb3BhY2l0eT0nMC4yNScgY3g9IjEyIiBjeT0iMTIiIHI9IjEwIiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iNCI+PC9jaXJjbGU+CjxwYXRoIG9wYWNpdHk9JzAuNzUnIGZpbGw9IiNGRkZGRkYiIGQ9Ik00IDEyYTggOCAwIDAxOC04VjBDNS4zNzMgMCAwIDUuMzczIDAgMTJoNHptMiA1LjI5MUE3Ljk2MiA3Ljk2MiAwIDAxNCAxMkgwYzAgMy4wNDIgMS4xMzUgNS44MjQgMyA3LjkzOGwzLTIuNjQ3eiI+PC9wYXRoPgo8L3N2Zz4='\n );\n try {\n _loader.animate(\n [{ transform: 'rotate(0deg)' }, { transform: 'rotate(359deg)' }],\n {\n duration: 3000,\n iterations: Infinity,\n }\n );\n } catch {\n logger.warn('Animation not supported, loader will be fixed.');\n }\n _loaderContainer.appendChild(_loader);\n\n /** Get the saving state of the leaderboard who had the last update (successful or started). */\n const getLastScoreSavingState = function ({\n hasSucceeded,\n }: {\n hasSucceeded: boolean;\n }): ScoreSavingState | null {\n const getDateField = (scoreSavingState: ScoreSavingState) =>\n hasSucceeded\n ? scoreSavingState.lastScoreSavingSucceededAt\n : scoreSavingState.lastScoreSavingStartedAt;\n const scoreSavingStates = Object.values(\n _scoreSavingStateByLeaderboard\n ).filter((scoreSavingState) => !!getDateField(scoreSavingState));\n if (scoreSavingStates.length === 0) return null;\n\n let lastScoreSavingState = scoreSavingStates[0];\n scoreSavingStates.forEach((scoreSavingState) => {\n const currentItemDate = getDateField(scoreSavingState);\n const lastItemDate = getDateField(lastScoreSavingState);\n if (\n currentItemDate &&\n lastItemDate &&\n currentItemDate > lastItemDate\n ) {\n lastScoreSavingState = scoreSavingState;\n }\n });\n return lastScoreSavingState;\n };\n\n const saveScore = async function ({\n leaderboardId,\n playerName,\n authenticatedPlayerData,\n score,\n runtimeScene,\n }: {\n leaderboardId: string;\n playerName?: string | null;\n authenticatedPlayerData?: { playerId: string; playerToken: string };\n score: number;\n runtimeScene: gdjs.RuntimeScene;\n }): Promise<PublicLeaderboardEntry> {\n const rootApi = runtimeScene\n .getGame()\n .isUsingGDevelopDevelopmentEnvironment()\n ? 'https://api-dev.gdevelop.io'\n : 'https://api.gdevelop.io';\n const baseUrl = `${rootApi}/play`;\n const game = runtimeScene.getGame();\n const payloadObject = {\n score: score,\n sessionId: game.getSessionId(),\n clientPlayerId: game.getPlayerId(),\n location:\n typeof window !== 'undefined' && (window as any).location\n ? (window as any).location.href\n : '',\n };\n const headers = {\n 'Content-Type': 'application/json',\n };\n let leaderboardEntryCreationUrl = `${baseUrl}/game/${gdjs.projectData.properties.projectUuid}/leaderboard/${leaderboardId}/entry`;\n if (authenticatedPlayerData) {\n headers[\n 'Authorization'\n ] = `player-game-token ${authenticatedPlayerData.playerToken}`;\n leaderboardEntryCreationUrl += `?playerId=${authenticatedPlayerData.playerId}`;\n } else {\n // In case playerName is empty, the backend will generate a random name.\n payloadObject['playerName'] = formatPlayerName(playerName);\n }\n const payload = JSON.stringify(payloadObject);\n headers['Digest'] = computeDigest(payload);\n\n try {\n const response = await fetch(leaderboardEntryCreationUrl, {\n body: payload,\n method: 'POST',\n headers: headers,\n });\n\n if (!response.ok) {\n const errorCode = response.status.toString();\n logger.error(\n 'Server responded with an error:',\n errorCode,\n response.statusText\n );\n\n throw errorCode;\n }\n\n try {\n const leaderboardEntry = await response.json();\n return leaderboardEntry;\n } catch (error) {\n logger.warn(\n 'An error occurred when reading response but score has been saved:',\n error\n );\n\n const errorCode = 'SAVED_ENTRY_CANT_BE_READ';\n throw errorCode;\n }\n } catch (error) {\n logger.error('Error while submitting a leaderboard score:', error);\n const errorCode = 'REQUEST_NOT_SENT';\n\n throw errorCode;\n }\n };\n\n export const setPreferSendConnectedPlayerScore = (\n runtimeScene: gdjs.RuntimeScene,\n enable: boolean\n ) => {\n _preferSendConnectedPlayerScore = enable;\n };\n\n export const savePlayerScore = (\n runtimeScene: gdjs.RuntimeScene,\n leaderboardId: string,\n score: float,\n playerName: string\n ) => {\n if (\n _preferSendConnectedPlayerScore &&\n gdjs.playerAuthentication.isAuthenticated()\n ) {\n return saveConnectedPlayerScore(runtimeScene, leaderboardId, score);\n }\n\n return new gdjs.PromiseTask(\n (async () => {\n const scoreSavingState = (_scoreSavingStateByLeaderboard[\n leaderboardId\n ] =\n _scoreSavingStateByLeaderboard[leaderboardId] ||\n new ScoreSavingState());\n\n try {\n const {\n closeSaving,\n closeSavingWithError,\n } = scoreSavingState.startSaving({ playerName, score });\n\n try {\n const leaderboardEntry = await saveScore({\n leaderboardId,\n playerName,\n score,\n runtimeScene,\n });\n closeSaving(leaderboardEntry);\n } catch (errorCode) {\n closeSavingWithError(errorCode);\n }\n } catch {\n // Do nothing: saving was rejected for a reason already logged.\n }\n })()\n );\n };\n\n export const saveConnectedPlayerScore = (\n runtimeScene: gdjs.RuntimeScene,\n leaderboardId: string,\n score: float\n ) =>\n new gdjs.PromiseTask(\n (async () => {\n const playerId = gdjs.playerAuthentication.getUserId();\n const playerToken = gdjs.playerAuthentication.getUserToken();\n if (!playerId || !playerToken) {\n logger.warn(\n 'Cannot save a score for a connected player if the player is not connected.'\n );\n return;\n }\n\n const scoreSavingState = (_scoreSavingStateByLeaderboard[\n leaderboardId\n ] =\n _scoreSavingStateByLeaderboard[leaderboardId] ||\n new ScoreSavingState());\n\n try {\n const {\n closeSaving,\n closeSavingWithError,\n } = scoreSavingState.startSaving({ playerId, score });\n\n try {\n const leaderboardEntryId = await saveScore({\n leaderboardId,\n authenticatedPlayerData: { playerId, playerToken },\n score,\n runtimeScene,\n });\n closeSaving(leaderboardEntryId);\n } catch (errorCode) {\n closeSavingWithError(errorCode);\n }\n } catch {\n // Do nothing: saving was rejected for a reason already logged.\n }\n })()\n );\n\n export const isSaving = function (leaderboardId?: string): boolean {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId].isSaving()\n : false;\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: false,\n });\n return lastScoreSavingState ? lastScoreSavingState.isSaving() : false;\n };\n\n export const hasBeenSaved = function (leaderboardId?: string): boolean {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId].hasScoreBeenSaved\n : false;\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: true,\n });\n return lastScoreSavingState\n ? lastScoreSavingState.hasScoreBeenSaved\n : false;\n };\n\n export const hasSavingErrored = function (\n leaderboardId?: string\n ): boolean {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId]\n .hasScoreSavingErrored\n : false;\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: false,\n });\n return lastScoreSavingState\n ? lastScoreSavingState.hasScoreSavingErrored\n : false;\n };\n\n export const getLastSaveError = function (\n leaderboardId?: string\n ): string | null {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId].lastSaveError\n : 'NO_DATA_ERROR';\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: false,\n });\n return lastScoreSavingState\n ? lastScoreSavingState.lastSaveError\n : 'NO_DATA_ERROR';\n };\n\n export const formatPlayerName = function (\n rawName?: string | null\n ): string {\n if (\n !rawName ||\n typeof rawName !== 'string' ||\n (typeof rawName === 'string' && rawName.length === 0)\n ) {\n return '';\n }\n return rawName\n .trim()\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/\\s/g, '_')\n .replace(/[^\\w|-]/g, '')\n .slice(0, 30);\n };\n\n const checkLeaderboardAvailability = function (\n url: string\n ): Promise<boolean> {\n return fetch(url, {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' },\n }).then(\n (response) => {\n if (!response.ok) {\n logger.error(\n `Error while fetching leaderboard view, server returned: ${response.status} ${response.statusText}`\n );\n return false;\n }\n return true;\n },\n (err) => {\n logger.error('Error while fetching leaderboard view:', err);\n return false;\n }\n );\n };\n\n const receiveMessageFromLeaderboardView = function (\n runtimeScene: gdjs.RuntimeScene,\n displayLoader: boolean,\n event: MessageEvent\n ) {\n const messageId =\n typeof event.data === 'string' ? event.data : event.data.id;\n switch (messageId) {\n case 'playerAuthenticated':\n gdjs.playerAuthentication.login({\n runtimeScene,\n userId: event.data.userId,\n username: event.data.username,\n userToken: event.data.userToken,\n });\n break;\n case 'openPlayerAuthentication':\n gdjs.playerAuthentication\n .openAuthenticationWindow(runtimeScene)\n .promise.then(({ status }) => {\n if (\n !_leaderboardViewIframe ||\n !_leaderboardViewIframe.contentWindow\n ) {\n logger.warn(\n 'Unable to transmit the new login status to the leaderboard view.'\n );\n return;\n }\n\n if (status === 'errored') {\n _leaderboardViewIframe.contentWindow.postMessage(\n {\n id: 'onPlayerAuthenticationErrored',\n },\n leaderboardHostBaseUrl\n );\n return;\n }\n\n const playerId = gdjs.playerAuthentication.getUserId();\n const playerToken = gdjs.playerAuthentication.getUserToken();\n if (status === 'dismissed' || !playerId || !playerToken) {\n _leaderboardViewIframe.contentWindow.postMessage(\n {\n id: 'onPlayerAuthenticationDismissed',\n },\n leaderboardHostBaseUrl\n );\n return;\n }\n\n _leaderboardViewIframe.contentWindow.postMessage(\n {\n id: 'onPlayerAuthenticated',\n playerId,\n playerUsername: gdjs.playerAuthentication.getUsername(),\n playerToken: playerToken,\n },\n leaderboardHostBaseUrl\n );\n });\n break;\n case 'closeLeaderboardView':\n _hasPlayerJustClosedLeaderboardView = true;\n closeLeaderboardView(runtimeScene);\n break;\n case 'leaderboardViewLoaded':\n if (displayLoader) {\n if (_errorTimeoutId) clearTimeout(_errorTimeoutId);\n displayLoaderInLeaderboardView(false, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: false,\n });\n }\n if (!_leaderboardViewIframe) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n \"The leaderboard view couldn't be found. Doing nothing.\"\n );\n return;\n }\n _leaderboardViewIframe.style.opacity = '1';\n _leaderboardViewIframeLoaded = true;\n _leaderboardViewIframeLoading = false;\n\n break;\n }\n };\n\n const handleErrorDisplayingLeaderboard = function (\n runtimeScene: gdjs.RuntimeScene,\n message: string\n ) {\n logger.error(message);\n _leaderboardViewIframeErrored = true;\n _leaderboardViewIframeLoading = false;\n closeLeaderboardView(runtimeScene);\n };\n\n const resetLeaderboardDisplayErrorTimeout = (\n runtimeScene: gdjs.RuntimeScene\n ) => {\n if (_errorTimeoutId) clearTimeout(_errorTimeoutId);\n _errorTimeoutId = setTimeout(() => {\n if (!_leaderboardViewIframeLoaded) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n 'Leaderboard page did not send message in time. Closing leaderboard view.'\n );\n }\n }, 15000);\n };\n\n const displayLoaderInLeaderboardView = function (\n yesOrNo: boolean,\n runtimeScene: gdjs.RuntimeScene,\n options: { callOnErrorIfDomElementContainerMissing: boolean }\n ): boolean {\n const domElementContainer = runtimeScene\n .getGame()\n .getRenderer()\n .getDomElementContainer();\n if (!domElementContainer) {\n if (options.callOnErrorIfDomElementContainerMissing) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n \"The div element covering the game couldn't be found, the leaderboard cannot be displayed.\"\n );\n }\n return false;\n }\n if (yesOrNo) {\n if (\n domElementContainer.children &&\n domElementContainer.children.length > 0\n ) {\n domElementContainer.insertBefore(\n _loaderContainer,\n domElementContainer.children[0]\n );\n } else {\n domElementContainer.appendChild(_loaderContainer);\n }\n if (_leaderboardViewIframe) {\n _leaderboardViewIframe.style.opacity = '0';\n }\n } else {\n try {\n domElementContainer.removeChild(_loaderContainer);\n if (_leaderboardViewIframe) {\n _leaderboardViewIframe.style.opacity = '1';\n }\n } catch {}\n }\n return true;\n };\n\n const computeLeaderboardDisplayingIframe = function (\n url: string\n ): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n iframe.src = url;\n iframe.id = 'leaderboard-view';\n iframe.style.position = 'absolute';\n // To trigger iframe loading and be able to listen to its events, use `opacity: 0` instead of `visibility: hidden` or `display: none`\n iframe.style.opacity = '0';\n iframe.style.pointerEvents = 'all';\n iframe.style.backgroundColor = '#FFFFFF';\n iframe.style.top = '0px';\n iframe.style.height = '100%';\n iframe.style.left = '0px';\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n\n return iframe;\n };\n\n export const displayLeaderboard = async function (\n runtimeScene: gdjs.RuntimeScene,\n leaderboardId: string,\n displayLoader: boolean\n ) {\n // First ensure we're not trying to display multiple times the same leaderboard (in which case\n // we \"de-duplicate\" the request to display it).\n if (leaderboardId === _requestedLeaderboardId) {\n if (_leaderboardViewIframeLoading) {\n logger.warn(\n `Already loading the view for the requested loader (${leaderboardId}), ignoring.`\n );\n return;\n }\n if (_leaderboardViewIframeLoaded) {\n logger.warn(\n `Already loaded the view for the requested loader (${leaderboardId}), ignoring.`\n );\n return;\n }\n }\n\n // We are now assured we want to display a new (or different) leaderboard: start loading it.\n _requestedLeaderboardId = leaderboardId;\n _leaderboardViewIframeErrored = false;\n _leaderboardViewIframeLoaded = false;\n _leaderboardViewIframeLoading = true;\n\n if (displayLoader) {\n displayLoaderInLeaderboardView(true, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: true,\n });\n }\n\n // If a save is being done for this leaderboard, wait for it to end so that the `lastSavedLeaderboardEntry`\n // can be saved and then used to show the player score.\n const scoreSavingState = _scoreSavingStateByLeaderboard[leaderboardId];\n if (scoreSavingState && scoreSavingState.lastSavingPromise) {\n await scoreSavingState.lastSavingPromise;\n }\n\n const lastSavedLeaderboardEntry = scoreSavingState\n ? scoreSavingState.lastSavedLeaderboardEntry\n : null;\n\n const gameId = gdjs.projectData.properties.projectUuid;\n const isDev = runtimeScene\n .getGame()\n .isUsingGDevelopDevelopmentEnvironment();\n\n const searchParams = new URLSearchParams();\n searchParams.set('inGameEmbedded', 'true');\n if (isDev) searchParams.set('dev', 'true');\n if (lastSavedLeaderboardEntry) {\n searchParams.set(\n 'playerLeaderboardEntryId',\n lastSavedLeaderboardEntry.id\n );\n if (lastSavedLeaderboardEntry.claimSecret) {\n searchParams.set(\n 'playerLeaderboardEntryClaimSecret',\n lastSavedLeaderboardEntry.claimSecret\n );\n }\n }\n const playerId = gdjs.playerAuthentication.getUserId();\n const playerToken = gdjs.playerAuthentication.getUserToken();\n if (playerId && playerToken) {\n searchParams.set('playerId', playerId);\n searchParams.set('playerToken', playerToken);\n searchParams.set(\n 'playerUsername',\n gdjs.playerAuthentication.getUsername()\n );\n }\n\n const targetUrl = `${leaderboardHostBaseUrl}/games/${gameId}/leaderboard/${leaderboardId}?${searchParams}`;\n\n try {\n const isAvailable = await checkLeaderboardAvailability(targetUrl);\n\n if (leaderboardId !== _requestedLeaderboardId) {\n logger.warn(\n `Received a response for leaderboard ${leaderboardId} though the last leaderboard requested is ${_requestedLeaderboardId}, ignoring this response.`\n );\n return;\n }\n if (!isAvailable) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n 'Leaderboard data could not be fetched. Closing leaderboard view if there is one.'\n );\n return;\n }\n\n if (_leaderboardViewIframe) {\n resetLeaderboardDisplayErrorTimeout(runtimeScene);\n if (displayLoader) {\n displayLoaderInLeaderboardView(true, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: false,\n });\n }\n _leaderboardViewIframe.src = targetUrl;\n } else {\n const domElementContainer = runtimeScene\n .getGame()\n .getRenderer()\n .getDomElementContainer();\n if (!domElementContainer) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n \"The div element covering the game couldn't be found, the leaderboard cannot be displayed.\"\n );\n return;\n }\n\n resetLeaderboardDisplayErrorTimeout(runtimeScene);\n\n _leaderboardViewIframe = computeLeaderboardDisplayingIframe(\n targetUrl\n );\n if (typeof window !== 'undefined') {\n _leaderboardMessageListener = (event: MessageEvent) => {\n receiveMessageFromLeaderboardView(\n runtimeScene,\n displayLoader,\n event\n );\n };\n (window as any).addEventListener(\n 'message',\n _leaderboardMessageListener,\n true\n );\n }\n domElementContainer.appendChild(_leaderboardViewIframe);\n }\n } catch (err) {\n logger.error(err);\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n 'An error occurred when fetching leaderboard data. Closing leaderboard view if there is one.'\n );\n }\n };\n\n export const isLeaderboardViewErrored = function (): boolean {\n return _leaderboardViewIframeErrored;\n };\n\n export const isLeaderboardViewLoaded = function (): boolean {\n return _leaderboardViewIframeLoaded;\n };\n\n export const isLeaderboardViewLoading = function (): boolean {\n return _leaderboardViewIframeLoading;\n };\n\n export const closeLeaderboardView = function (\n runtimeScene: gdjs.RuntimeScene\n ) {\n try {\n displayLoaderInLeaderboardView(false, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: false,\n });\n\n if (!_leaderboardViewIframe) {\n logger.info(\n \"The iframe displaying the current leaderboard couldn't be found, the leaderboard view must be already closed.\"\n );\n return;\n }\n const domElementContainer = runtimeScene\n .getGame()\n .getRenderer()\n .getDomElementContainer();\n if (!domElementContainer) {\n logger.info(\n \"The div element covering the game couldn't be found, the leaderboard view must be already closed.\"\n );\n return;\n }\n\n if (typeof window !== 'undefined') {\n (window as any).removeEventListener(\n 'message',\n _leaderboardMessageListener,\n true\n );\n _leaderboardMessageListener = null;\n }\n domElementContainer.removeChild(_leaderboardViewIframe);\n _leaderboardViewIframe = null;\n } finally {\n // Don't reset the loading flag (the view of another leaderboard might be loading)\n // or the error flag (we want to persist the error flag even after the view is closed),\n // but reset the flag indicating the view is loaded (if it was).\n _leaderboardViewIframeLoaded = false;\n\n const gameCanvas = runtimeScene.getGame().getRenderer().getCanvas();\n if (gameCanvas) gameCanvas.focus();\n }\n };\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAGA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBACxB,GAAU,GAAV,UAAU,EAAV,CACE,GAAU,GAAV,UAAU,EAAV,CACL,GAAI,GAAsC,GACtC,EAAkC,GAEtC,EAAK,uCAAuC,IAAM,CAEhD,EAAsC,KAM3B,qCAAqC,IAChD,EAEF,KAAM,GAAgB,AAAC,GAA4B,CACjD,KAAM,GAAS,GAAI,OAAM,UAAW,OAAQ,CAAE,SAAU,SACxD,SAAO,OAAO,GACP,EAAO,QAAQ,QAGlB,EAAyB,mBAW/B,OAAuB,C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C,GAEF,EACJ,OACA,UAAU,OACV,QAAQ,mBAAoB,IAC5B,QAAQ,MAAO,KACf,QAAQ,WAAY,IACpB,MAAM,EAAG,KAGd,KAAM,GAA+B,SACnC,EACkB,CAClB,MAAO,OAAM,EAAK,CAChB,OAAQ,MACR,QAAS,CAAE,eAAgB,sBAC1B,KACD,AAAC,GACM,EAAS,GAMP,GALL,GAAO,MACL,2DAA2D,EAAS,UAAU,EAAS,cAElF,IAIX,AAAC,GACC,GAAO,MAAM,yCAA0C,GAChD,MAKP,EAAoC,SACxC,EACA,EACA,EACA,CAGA,OADE,MAAO,GAAM,MAAS,SAAW,EAAM,KAAO,EAAM,KAAK,QAEpD,sBACH,EAAK,qBAAqB,MAAM,CAC9B,eACA,OAAQ,EAAM,KAAK,OACnB,SAAU,EAAM,KAAK,SACrB,UAAW,EAAM,KAAK,YAExB,UACG,2BACH,EAAK,qBACF,yBAAyB,
|
|
4
|
+
"sourcesContent": ["/// <reference path=\"sha256.d.ts\" />\n\n// TODO EBO Replace runtimeScene to instanceContainer.\nnamespace gdjs {\n const logger = new gdjs.Logger('Leaderboards');\n export namespace evtTools {\n export namespace leaderboards {\n let _hasPlayerJustClosedLeaderboardView = false;\n let _preferSendConnectedPlayerScore = true;\n\n gdjs.registerRuntimeScenePostEventsCallback(() => {\n // Set it back to false for the next frame.\n _hasPlayerJustClosedLeaderboardView = false;\n });\n\n /**\n * Returns true if the player has just closed the leaderboard view.\n */\n export const hasPlayerJustClosedLeaderboardView = () =>\n _hasPlayerJustClosedLeaderboardView;\n\n const computeDigest = (payload: string): string => {\n const shaObj = new jsSHA('SHA-256', 'TEXT', { encoding: 'UTF8' });\n shaObj.update(payload);\n return shaObj.getHash('B64');\n };\n\n const leaderboardHostBaseUrl = 'https://gd.games';\n // const leaderboardHostBaseUrl = 'http://localhost:4000';\n\n type PublicLeaderboardEntry = {\n id: string;\n claimSecret?: string;\n };\n\n /**\n * Hold the state of the save of a score for a leaderboard.\n */\n class ScoreSavingState {\n lastScoreSavingStartedAt: number | null = null;\n lastScoreSavingSucceededAt: number | null = null;\n\n /** The promise that will be resolved when the score saving is done (successfully or not). */\n lastSavingPromise: Promise<void> | null = null;\n\n // Score that is being saved:\n private _currentlySavingScore: number | null = null;\n private _currentlySavingPlayerName: string | null = null;\n private _currentlySavingPlayerId: string | null = null;\n\n // Last score saved with success:\n private _lastSavedScore: number | null = null;\n private _lastSavedPlayerName: string | null = null;\n private _lastSavedPlayerId: string | null = null;\n\n /** The id of the entry in the leaderboard, for the last score saved with success. */\n lastSavedLeaderboardEntry: PublicLeaderboardEntry | null = null;\n\n /** Last error that happened when saving the score (useful if `hasScoreSavingErrored` is true). */\n lastSaveError: string | null = null;\n\n /** `true` if the last save has finished and succeeded. */\n hasScoreBeenSaved: boolean = false;\n\n /** `true` if the last save has finished and failed (check `lastSaveError` then). */\n hasScoreSavingErrored: boolean = false;\n\n isSaving(): boolean {\n return (\n !!this.lastSavingPromise &&\n !this.hasScoreBeenSaved &&\n !this.hasScoreSavingErrored\n );\n }\n\n private _isSameAsLastScore({\n playerName,\n playerId,\n score,\n }: {\n playerName?: string;\n playerId?: string;\n score: number;\n }): boolean {\n return (\n ((!!playerName && this._lastSavedPlayerName === playerName) ||\n (!!playerId && this._lastSavedPlayerId === playerId)) &&\n this._lastSavedScore === score\n );\n }\n\n private _isAlreadySavingThisScore({\n playerName,\n playerId,\n score,\n }: {\n playerName?: string;\n playerId?: string;\n score: number;\n }): boolean {\n if (!this.isSaving()) return false;\n\n return (\n ((!!playerName && this._currentlySavingPlayerName === playerName) ||\n (!!playerId && this._currentlySavingPlayerId === playerId)) &&\n this._currentlySavingScore === score\n );\n }\n\n private _isTooSoonToSaveAnotherScore(): boolean {\n return (\n !!this.lastScoreSavingStartedAt &&\n Date.now() - this.lastScoreSavingStartedAt < 500\n );\n }\n\n startSaving({\n playerName,\n playerId,\n score,\n }: {\n playerName?: string;\n playerId?: string;\n score: number;\n }): {\n closeSaving: (leaderboardEntry: PublicLeaderboardEntry) => void;\n closeSavingWithError(errorCode: string);\n } {\n if (this._isAlreadySavingThisScore({ playerName, playerId, score })) {\n logger.warn(\n 'There is already a request to save with this player name and this score. Ignoring this one.'\n );\n throw new Error('Ignoring this saving request.');\n }\n\n if (this._isSameAsLastScore({ playerName, playerId, score })) {\n logger.warn(\n 'The player and score to be sent are the same as previous one. Ignoring this one.'\n );\n this._setError('SAME_AS_PREVIOUS');\n throw new Error('Ignoring this saving request.');\n }\n\n if (this._isTooSoonToSaveAnotherScore()) {\n logger.warn(\n 'Last entry was sent too little time ago. Ignoring this one.'\n );\n this._setError('TOO_FAST');\n\n // Set the starting time to cancel all the following attempts that\n // are started too early after this one.\n this.lastScoreSavingStartedAt = Date.now();\n\n throw new Error('Ignoring this saving request.');\n }\n\n let resolveSavingPromise: () => void;\n const savingPromise = new Promise<void>((resolve) => {\n resolveSavingPromise = resolve;\n });\n\n this.lastScoreSavingStartedAt = Date.now();\n this.lastSavingPromise = savingPromise;\n this.hasScoreBeenSaved = false;\n this.hasScoreSavingErrored = false;\n this._currentlySavingScore = score;\n if (playerName) this._currentlySavingPlayerName = playerName;\n if (playerId) this._currentlySavingPlayerId = playerId;\n\n return {\n closeSaving: (leaderboardEntry) => {\n if (savingPromise !== this.lastSavingPromise) {\n logger.info(\n 'Score saving result received, but another save was launched in the meantime - ignoring the result of this one.'\n );\n\n // Still finish the promise that can be waited upon:\n resolveSavingPromise();\n return;\n }\n\n this.lastScoreSavingSucceededAt = Date.now();\n this._lastSavedScore = this._currentlySavingScore;\n this._lastSavedPlayerName = this._currentlySavingPlayerName;\n this._lastSavedPlayerId = this._currentlySavingPlayerId;\n this.lastSavedLeaderboardEntry = leaderboardEntry;\n this.hasScoreBeenSaved = true;\n\n resolveSavingPromise();\n },\n closeSavingWithError: (errorCode) => {\n if (savingPromise !== this.lastSavingPromise) {\n logger.info(\n 'Score saving result received, but another save was launched in the meantime - ignoring the result of this one.'\n );\n\n // Still finish the promise that can be waited upon:\n resolveSavingPromise();\n return;\n }\n\n this._setError(errorCode);\n resolveSavingPromise();\n },\n };\n }\n\n private _setError(errorCode: string): void {\n this.lastSaveError = errorCode;\n this.hasScoreBeenSaved = false;\n this.hasScoreSavingErrored = true;\n }\n }\n\n let _scoreSavingStateByLeaderboard: {\n [leaderboardId: string]: ScoreSavingState;\n } = {};\n\n // Leaderboard display\n let _requestedLeaderboardId: string | null;\n let _leaderboardViewIframe: HTMLIFrameElement | null = null;\n let _leaderboardViewIframeErrored: boolean = false;\n let _leaderboardViewIframeLoading: boolean = false;\n let _leaderboardViewIframeLoaded: boolean = false;\n let _errorTimeoutId: NodeJS.Timeout | null = null;\n let _leaderboardMessageListener:\n | ((event: MessageEvent) => void)\n | null = null;\n\n const _loaderContainer: HTMLDivElement = document.createElement('div');\n _loaderContainer.style.backgroundColor = '#000000';\n _loaderContainer.style.display = 'flex';\n _loaderContainer.style.height = '100%';\n _loaderContainer.style.width = '100%';\n _loaderContainer.style.justifyContent = 'center';\n _loaderContainer.style.alignItems = 'center';\n _loaderContainer.style.position = 'relative';\n _loaderContainer.style.zIndex = '2';\n const _loader = document.createElement('img');\n _loader.setAttribute('width', '50px');\n _loader.setAttribute(\n 'src',\n 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyNCAyNCI+CjxjaXJjbGUgb3BhY2l0eT0nMC4yNScgY3g9IjEyIiBjeT0iMTIiIHI9IjEwIiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iNCI+PC9jaXJjbGU+CjxwYXRoIG9wYWNpdHk9JzAuNzUnIGZpbGw9IiNGRkZGRkYiIGQ9Ik00IDEyYTggOCAwIDAxOC04VjBDNS4zNzMgMCAwIDUuMzczIDAgMTJoNHptMiA1LjI5MUE3Ljk2MiA3Ljk2MiAwIDAxNCAxMkgwYzAgMy4wNDIgMS4xMzUgNS44MjQgMyA3LjkzOGwzLTIuNjQ3eiI+PC9wYXRoPgo8L3N2Zz4='\n );\n try {\n _loader.animate(\n [{ transform: 'rotate(0deg)' }, { transform: 'rotate(359deg)' }],\n {\n duration: 3000,\n iterations: Infinity,\n }\n );\n } catch {\n logger.warn('Animation not supported, loader will be fixed.');\n }\n _loaderContainer.appendChild(_loader);\n\n /** Get the saving state of the leaderboard who had the last update (successful or started). */\n const getLastScoreSavingState = function ({\n hasSucceeded,\n }: {\n hasSucceeded: boolean;\n }): ScoreSavingState | null {\n const getDateField = (scoreSavingState: ScoreSavingState) =>\n hasSucceeded\n ? scoreSavingState.lastScoreSavingSucceededAt\n : scoreSavingState.lastScoreSavingStartedAt;\n const scoreSavingStates = Object.values(\n _scoreSavingStateByLeaderboard\n ).filter((scoreSavingState) => !!getDateField(scoreSavingState));\n if (scoreSavingStates.length === 0) return null;\n\n let lastScoreSavingState = scoreSavingStates[0];\n scoreSavingStates.forEach((scoreSavingState) => {\n const currentItemDate = getDateField(scoreSavingState);\n const lastItemDate = getDateField(lastScoreSavingState);\n if (\n currentItemDate &&\n lastItemDate &&\n currentItemDate > lastItemDate\n ) {\n lastScoreSavingState = scoreSavingState;\n }\n });\n return lastScoreSavingState;\n };\n\n const saveScore = async function ({\n leaderboardId,\n playerName,\n authenticatedPlayerData,\n score,\n runtimeScene,\n }: {\n leaderboardId: string;\n playerName?: string | null;\n authenticatedPlayerData?: { playerId: string; playerToken: string };\n score: number;\n runtimeScene: gdjs.RuntimeScene;\n }): Promise<PublicLeaderboardEntry> {\n const rootApi = runtimeScene\n .getGame()\n .isUsingGDevelopDevelopmentEnvironment()\n ? 'https://api-dev.gdevelop.io'\n : 'https://api.gdevelop.io';\n const baseUrl = `${rootApi}/play`;\n const game = runtimeScene.getGame();\n const payloadObject = {\n score: score,\n sessionId: game.getSessionId(),\n clientPlayerId: game.getPlayerId(),\n location:\n typeof window !== 'undefined' && (window as any).location\n ? (window as any).location.href\n : '',\n };\n const headers = {\n 'Content-Type': 'application/json',\n };\n let leaderboardEntryCreationUrl = `${baseUrl}/game/${gdjs.projectData.properties.projectUuid}/leaderboard/${leaderboardId}/entry`;\n if (authenticatedPlayerData) {\n headers[\n 'Authorization'\n ] = `player-game-token ${authenticatedPlayerData.playerToken}`;\n leaderboardEntryCreationUrl += `?playerId=${authenticatedPlayerData.playerId}`;\n } else {\n // In case playerName is empty, the backend will generate a random name.\n payloadObject['playerName'] = formatPlayerName(playerName);\n }\n const payload = JSON.stringify(payloadObject);\n headers['Digest'] = computeDigest(payload);\n\n try {\n const response = await fetch(leaderboardEntryCreationUrl, {\n body: payload,\n method: 'POST',\n headers: headers,\n });\n\n if (!response.ok) {\n const errorCode = response.status.toString();\n logger.error(\n 'Server responded with an error:',\n errorCode,\n response.statusText\n );\n\n throw errorCode;\n }\n\n try {\n const leaderboardEntry = await response.json();\n return leaderboardEntry;\n } catch (error) {\n logger.warn(\n 'An error occurred when reading response but score has been saved:',\n error\n );\n\n const errorCode = 'SAVED_ENTRY_CANT_BE_READ';\n throw errorCode;\n }\n } catch (error) {\n logger.error('Error while submitting a leaderboard score:', error);\n const errorCode = 'REQUEST_NOT_SENT';\n\n throw errorCode;\n }\n };\n\n export const setPreferSendConnectedPlayerScore = (\n runtimeScene: gdjs.RuntimeScene,\n enable: boolean\n ) => {\n _preferSendConnectedPlayerScore = enable;\n };\n\n export const savePlayerScore = (\n runtimeScene: gdjs.RuntimeScene,\n leaderboardId: string,\n score: float,\n playerName: string\n ) => {\n if (\n _preferSendConnectedPlayerScore &&\n gdjs.playerAuthentication.isAuthenticated()\n ) {\n return saveConnectedPlayerScore(runtimeScene, leaderboardId, score);\n }\n\n return new gdjs.PromiseTask(\n (async () => {\n const scoreSavingState = (_scoreSavingStateByLeaderboard[\n leaderboardId\n ] =\n _scoreSavingStateByLeaderboard[leaderboardId] ||\n new ScoreSavingState());\n\n try {\n const {\n closeSaving,\n closeSavingWithError,\n } = scoreSavingState.startSaving({ playerName, score });\n\n try {\n const leaderboardEntry = await saveScore({\n leaderboardId,\n playerName,\n score,\n runtimeScene,\n });\n closeSaving(leaderboardEntry);\n } catch (errorCode) {\n closeSavingWithError(errorCode);\n }\n } catch {\n // Do nothing: saving was rejected for a reason already logged.\n }\n })()\n );\n };\n\n export const saveConnectedPlayerScore = (\n runtimeScene: gdjs.RuntimeScene,\n leaderboardId: string,\n score: float\n ) =>\n new gdjs.PromiseTask(\n (async () => {\n const playerId = gdjs.playerAuthentication.getUserId();\n const playerToken = gdjs.playerAuthentication.getUserToken();\n if (!playerId || !playerToken) {\n logger.warn(\n 'Cannot save a score for a connected player if the player is not connected.'\n );\n return;\n }\n\n const scoreSavingState = (_scoreSavingStateByLeaderboard[\n leaderboardId\n ] =\n _scoreSavingStateByLeaderboard[leaderboardId] ||\n new ScoreSavingState());\n\n try {\n const {\n closeSaving,\n closeSavingWithError,\n } = scoreSavingState.startSaving({ playerId, score });\n\n try {\n const leaderboardEntryId = await saveScore({\n leaderboardId,\n authenticatedPlayerData: { playerId, playerToken },\n score,\n runtimeScene,\n });\n closeSaving(leaderboardEntryId);\n } catch (errorCode) {\n closeSavingWithError(errorCode);\n }\n } catch {\n // Do nothing: saving was rejected for a reason already logged.\n }\n })()\n );\n\n export const isSaving = function (leaderboardId?: string): boolean {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId].isSaving()\n : false;\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: false,\n });\n return lastScoreSavingState ? lastScoreSavingState.isSaving() : false;\n };\n\n export const hasBeenSaved = function (leaderboardId?: string): boolean {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId].hasScoreBeenSaved\n : false;\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: true,\n });\n return lastScoreSavingState\n ? lastScoreSavingState.hasScoreBeenSaved\n : false;\n };\n\n export const hasSavingErrored = function (\n leaderboardId?: string\n ): boolean {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId]\n .hasScoreSavingErrored\n : false;\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: false,\n });\n return lastScoreSavingState\n ? lastScoreSavingState.hasScoreSavingErrored\n : false;\n };\n\n export const getLastSaveError = function (\n leaderboardId?: string\n ): string | null {\n if (leaderboardId) {\n return _scoreSavingStateByLeaderboard[leaderboardId]\n ? _scoreSavingStateByLeaderboard[leaderboardId].lastSaveError\n : 'NO_DATA_ERROR';\n }\n\n const lastScoreSavingState = getLastScoreSavingState({\n hasSucceeded: false,\n });\n return lastScoreSavingState\n ? lastScoreSavingState.lastSaveError\n : 'NO_DATA_ERROR';\n };\n\n export const formatPlayerName = function (\n rawName?: string | null\n ): string {\n if (\n !rawName ||\n typeof rawName !== 'string' ||\n (typeof rawName === 'string' && rawName.length === 0)\n ) {\n return '';\n }\n return rawName\n .trim()\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/\\s/g, '_')\n .replace(/[^\\w|-]/g, '')\n .slice(0, 30);\n };\n\n const checkLeaderboardAvailability = function (\n url: string\n ): Promise<boolean> {\n return fetch(url, {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' },\n }).then(\n (response) => {\n if (!response.ok) {\n logger.error(\n `Error while fetching leaderboard view, server returned: ${response.status} ${response.statusText}`\n );\n return false;\n }\n return true;\n },\n (err) => {\n logger.error('Error while fetching leaderboard view:', err);\n return false;\n }\n );\n };\n\n const receiveMessageFromLeaderboardView = function (\n runtimeScene: gdjs.RuntimeScene,\n displayLoader: boolean,\n event: MessageEvent\n ) {\n const messageId =\n typeof event.data === 'string' ? event.data : event.data.id;\n switch (messageId) {\n case 'playerAuthenticated':\n gdjs.playerAuthentication.login({\n runtimeScene,\n userId: event.data.userId,\n username: event.data.username,\n userToken: event.data.userToken,\n });\n break;\n case 'openPlayerAuthentication':\n gdjs.playerAuthentication\n .openAuthenticationWindow(runtimeScene, event.data.options)\n .promise.then(({ status }) => {\n if (\n !_leaderboardViewIframe ||\n !_leaderboardViewIframe.contentWindow\n ) {\n logger.warn(\n 'Unable to transmit the new login status to the leaderboard view.'\n );\n return;\n }\n\n if (status === 'errored') {\n _leaderboardViewIframe.contentWindow.postMessage(\n {\n id: 'onPlayerAuthenticationErrored',\n },\n leaderboardHostBaseUrl\n );\n return;\n }\n\n const playerId = gdjs.playerAuthentication.getUserId();\n const playerToken = gdjs.playerAuthentication.getUserToken();\n if (status === 'dismissed' || !playerId || !playerToken) {\n _leaderboardViewIframe.contentWindow.postMessage(\n {\n id: 'onPlayerAuthenticationDismissed',\n },\n leaderboardHostBaseUrl\n );\n return;\n }\n\n _leaderboardViewIframe.contentWindow.postMessage(\n {\n id: 'onPlayerAuthenticated',\n playerId,\n playerUsername: gdjs.playerAuthentication.getUsername(),\n playerToken: playerToken,\n },\n leaderboardHostBaseUrl\n );\n });\n break;\n case 'closeLeaderboardView':\n _hasPlayerJustClosedLeaderboardView = true;\n closeLeaderboardView(runtimeScene);\n break;\n case 'leaderboardViewLoaded':\n if (displayLoader) {\n if (_errorTimeoutId) clearTimeout(_errorTimeoutId);\n displayLoaderInLeaderboardView(false, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: false,\n });\n }\n if (!_leaderboardViewIframe) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n \"The leaderboard view couldn't be found. Doing nothing.\"\n );\n return;\n }\n _leaderboardViewIframe.style.opacity = '1';\n _leaderboardViewIframeLoaded = true;\n _leaderboardViewIframeLoading = false;\n\n break;\n }\n };\n\n const handleErrorDisplayingLeaderboard = function (\n runtimeScene: gdjs.RuntimeScene,\n message: string\n ) {\n logger.error(message);\n _leaderboardViewIframeErrored = true;\n _leaderboardViewIframeLoading = false;\n closeLeaderboardView(runtimeScene);\n };\n\n const resetLeaderboardDisplayErrorTimeout = (\n runtimeScene: gdjs.RuntimeScene\n ) => {\n if (_errorTimeoutId) clearTimeout(_errorTimeoutId);\n _errorTimeoutId = setTimeout(() => {\n if (!_leaderboardViewIframeLoaded) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n 'Leaderboard page did not send message in time. Closing leaderboard view.'\n );\n }\n }, 15000);\n };\n\n const displayLoaderInLeaderboardView = function (\n yesOrNo: boolean,\n runtimeScene: gdjs.RuntimeScene,\n options: { callOnErrorIfDomElementContainerMissing: boolean }\n ): boolean {\n const domElementContainer = runtimeScene\n .getGame()\n .getRenderer()\n .getDomElementContainer();\n if (!domElementContainer) {\n if (options.callOnErrorIfDomElementContainerMissing) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n \"The div element covering the game couldn't be found, the leaderboard cannot be displayed.\"\n );\n }\n return false;\n }\n if (yesOrNo) {\n if (\n domElementContainer.children &&\n domElementContainer.children.length > 0\n ) {\n domElementContainer.insertBefore(\n _loaderContainer,\n domElementContainer.children[0]\n );\n } else {\n domElementContainer.appendChild(_loaderContainer);\n }\n if (_leaderboardViewIframe) {\n _leaderboardViewIframe.style.opacity = '0';\n }\n } else {\n try {\n domElementContainer.removeChild(_loaderContainer);\n if (_leaderboardViewIframe) {\n _leaderboardViewIframe.style.opacity = '1';\n }\n } catch {}\n }\n return true;\n };\n\n const computeLeaderboardDisplayingIframe = function (\n url: string\n ): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n iframe.src = url;\n iframe.id = 'leaderboard-view';\n iframe.style.position = 'absolute';\n // To trigger iframe loading and be able to listen to its events, use `opacity: 0` instead of `visibility: hidden` or `display: none`\n iframe.style.opacity = '0';\n iframe.style.pointerEvents = 'all';\n iframe.style.backgroundColor = '#FFFFFF';\n iframe.style.top = '0px';\n iframe.style.height = '100%';\n iframe.style.left = '0px';\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n\n return iframe;\n };\n\n export const displayLeaderboard = async function (\n runtimeScene: gdjs.RuntimeScene,\n leaderboardId: string,\n displayLoader: boolean\n ) {\n // First ensure we're not trying to display multiple times the same leaderboard (in which case\n // we \"de-duplicate\" the request to display it).\n if (leaderboardId === _requestedLeaderboardId) {\n if (_leaderboardViewIframeLoading) {\n logger.warn(\n `Already loading the view for the requested loader (${leaderboardId}), ignoring.`\n );\n return;\n }\n if (_leaderboardViewIframeLoaded) {\n logger.warn(\n `Already loaded the view for the requested loader (${leaderboardId}), ignoring.`\n );\n return;\n }\n }\n\n // We are now assured we want to display a new (or different) leaderboard: start loading it.\n _requestedLeaderboardId = leaderboardId;\n _leaderboardViewIframeErrored = false;\n _leaderboardViewIframeLoaded = false;\n _leaderboardViewIframeLoading = true;\n\n if (displayLoader) {\n displayLoaderInLeaderboardView(true, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: true,\n });\n }\n\n // If a save is being done for this leaderboard, wait for it to end so that the `lastSavedLeaderboardEntry`\n // can be saved and then used to show the player score.\n const scoreSavingState = _scoreSavingStateByLeaderboard[leaderboardId];\n if (scoreSavingState && scoreSavingState.lastSavingPromise) {\n await scoreSavingState.lastSavingPromise;\n }\n\n const lastSavedLeaderboardEntry = scoreSavingState\n ? scoreSavingState.lastSavedLeaderboardEntry\n : null;\n\n const gameId = gdjs.projectData.properties.projectUuid;\n const isDev = runtimeScene\n .getGame()\n .isUsingGDevelopDevelopmentEnvironment();\n\n const searchParams = new URLSearchParams();\n searchParams.set('inGameEmbedded', 'true');\n if (isDev) searchParams.set('dev', 'true');\n if (lastSavedLeaderboardEntry) {\n searchParams.set(\n 'playerLeaderboardEntryId',\n lastSavedLeaderboardEntry.id\n );\n if (lastSavedLeaderboardEntry.claimSecret) {\n searchParams.set(\n 'playerLeaderboardEntryClaimSecret',\n lastSavedLeaderboardEntry.claimSecret\n );\n }\n }\n const playerId = gdjs.playerAuthentication.getUserId();\n const playerToken = gdjs.playerAuthentication.getUserToken();\n if (playerId && playerToken) {\n searchParams.set('playerId', playerId);\n searchParams.set('playerToken', playerToken);\n searchParams.set(\n 'playerUsername',\n gdjs.playerAuthentication.getUsername()\n );\n }\n\n const targetUrl = `${leaderboardHostBaseUrl}/games/${gameId}/leaderboard/${leaderboardId}?${searchParams}`;\n\n try {\n const isAvailable = await checkLeaderboardAvailability(targetUrl);\n\n if (leaderboardId !== _requestedLeaderboardId) {\n logger.warn(\n `Received a response for leaderboard ${leaderboardId} though the last leaderboard requested is ${_requestedLeaderboardId}, ignoring this response.`\n );\n return;\n }\n if (!isAvailable) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n 'Leaderboard data could not be fetched. Closing leaderboard view if there is one.'\n );\n return;\n }\n\n if (_leaderboardViewIframe) {\n resetLeaderboardDisplayErrorTimeout(runtimeScene);\n if (displayLoader) {\n displayLoaderInLeaderboardView(true, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: false,\n });\n }\n _leaderboardViewIframe.src = targetUrl;\n } else {\n const domElementContainer = runtimeScene\n .getGame()\n .getRenderer()\n .getDomElementContainer();\n if (!domElementContainer) {\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n \"The div element covering the game couldn't be found, the leaderboard cannot be displayed.\"\n );\n return;\n }\n\n resetLeaderboardDisplayErrorTimeout(runtimeScene);\n\n _leaderboardViewIframe = computeLeaderboardDisplayingIframe(\n targetUrl\n );\n if (typeof window !== 'undefined') {\n _leaderboardMessageListener = (event: MessageEvent) => {\n receiveMessageFromLeaderboardView(\n runtimeScene,\n displayLoader,\n event\n );\n };\n (window as any).addEventListener(\n 'message',\n _leaderboardMessageListener,\n true\n );\n }\n domElementContainer.appendChild(_leaderboardViewIframe);\n }\n } catch (err) {\n logger.error(err);\n handleErrorDisplayingLeaderboard(\n runtimeScene,\n 'An error occurred when fetching leaderboard data. Closing leaderboard view if there is one.'\n );\n }\n };\n\n export const isLeaderboardViewErrored = function (): boolean {\n return _leaderboardViewIframeErrored;\n };\n\n export const isLeaderboardViewLoaded = function (): boolean {\n return _leaderboardViewIframeLoaded;\n };\n\n export const isLeaderboardViewLoading = function (): boolean {\n return _leaderboardViewIframeLoading;\n };\n\n export const closeLeaderboardView = function (\n runtimeScene: gdjs.RuntimeScene\n ) {\n try {\n displayLoaderInLeaderboardView(false, runtimeScene, {\n callOnErrorIfDomElementContainerMissing: false,\n });\n\n if (!_leaderboardViewIframe) {\n logger.info(\n \"The iframe displaying the current leaderboard couldn't be found, the leaderboard view must be already closed.\"\n );\n return;\n }\n const domElementContainer = runtimeScene\n .getGame()\n .getRenderer()\n .getDomElementContainer();\n if (!domElementContainer) {\n logger.info(\n \"The div element covering the game couldn't be found, the leaderboard view must be already closed.\"\n );\n return;\n }\n\n if (typeof window !== 'undefined') {\n (window as any).removeEventListener(\n 'message',\n _leaderboardMessageListener,\n true\n );\n _leaderboardMessageListener = null;\n }\n domElementContainer.removeChild(_leaderboardViewIframe);\n _leaderboardViewIframe = null;\n } finally {\n // Don't reset the loading flag (the view of another leaderboard might be loading)\n // or the error flag (we want to persist the error flag even after the view is closed),\n // but reset the flag indicating the view is loaded (if it was).\n _leaderboardViewIframeLoaded = false;\n\n const gameCanvas = runtimeScene.getGame().getRenderer().getCanvas();\n if (gameCanvas) gameCanvas.focus();\n }\n };\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAGA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBACxB,GAAU,GAAV,UAAU,EAAV,CACE,GAAU,GAAV,UAAU,EAAV,CACL,GAAI,GAAsC,GACtC,EAAkC,GAEtC,EAAK,uCAAuC,IAAM,CAEhD,EAAsC,KAM3B,qCAAqC,IAChD,EAEF,KAAM,GAAgB,AAAC,GAA4B,CACjD,KAAM,GAAS,GAAI,OAAM,UAAW,OAAQ,CAAE,SAAU,SACxD,SAAO,OAAO,GACP,EAAO,QAAQ,QAGlB,EAAyB,mBAW/B,OAAuB,CAAvB,aAtCN,CAuCQ,8BAA0C,KAC1C,gCAA4C,KAG5C,uBAA0C,KAGlC,2BAAuC,KACvC,gCAA4C,KAC5C,8BAA0C,KAG1C,qBAAiC,KACjC,0B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8B,MAEhC,EAAoB,YAAY,GAChC,EAAyB,YACzB,CAIA,EAA+B,GAE/B,KAAM,GAAa,EAAa,UAAU,cAAc,YACxD,AAAI,GAAY,EAAW,YAh7BhB,yCADF,iCAFT",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -68,11 +68,8 @@ module.exports = {
|
|
|
68
68
|
|
|
69
69
|
const lightObject = new gd.ObjectJsImplementation();
|
|
70
70
|
|
|
71
|
-
lightObject.updateProperty = function (
|
|
72
|
-
objectContent
|
|
73
|
-
propertyName,
|
|
74
|
-
newValue
|
|
75
|
-
) {
|
|
71
|
+
lightObject.updateProperty = function (propertyName, newValue) {
|
|
72
|
+
const objectContent = this.content;
|
|
76
73
|
if (propertyName === 'radius') {
|
|
77
74
|
objectContent.radius = parseFloat(newValue);
|
|
78
75
|
return true;
|
|
@@ -96,8 +93,9 @@ module.exports = {
|
|
|
96
93
|
return false;
|
|
97
94
|
};
|
|
98
95
|
|
|
99
|
-
lightObject.getProperties = function (
|
|
96
|
+
lightObject.getProperties = function () {
|
|
100
97
|
const objectProperties = new gd.MapStringPropertyDescriptor();
|
|
98
|
+
const objectContent = this.content;
|
|
101
99
|
|
|
102
100
|
objectProperties.set(
|
|
103
101
|
'radius',
|
|
@@ -140,17 +138,14 @@ module.exports = {
|
|
|
140
138
|
|
|
141
139
|
return objectProperties;
|
|
142
140
|
};
|
|
143
|
-
lightObject.
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
})
|
|
150
|
-
);
|
|
141
|
+
lightObject.content = {
|
|
142
|
+
radius: 50,
|
|
143
|
+
color: '255;255;255',
|
|
144
|
+
debugMode: false,
|
|
145
|
+
texture: '',
|
|
146
|
+
};
|
|
151
147
|
|
|
152
148
|
lightObject.updateInitialInstanceProperty = function (
|
|
153
|
-
objectContent,
|
|
154
149
|
instance,
|
|
155
150
|
propertyName,
|
|
156
151
|
newValue
|
|
@@ -158,7 +153,7 @@ module.exports = {
|
|
|
158
153
|
return false;
|
|
159
154
|
};
|
|
160
155
|
|
|
161
|
-
lightObject.getInitialInstanceProperties = function (
|
|
156
|
+
lightObject.getInitialInstanceProperties = function (instance) {
|
|
162
157
|
const instanceProperties = new gd.MapStringPropertyDescriptor();
|
|
163
158
|
|
|
164
159
|
return instanceProperties;
|
|
@@ -238,6 +233,10 @@ module.exports = {
|
|
|
238
233
|
* Renderer for instances of LightObject inside the IDE.
|
|
239
234
|
*/
|
|
240
235
|
class RenderedLightObjectInstance extends RenderedInstance {
|
|
236
|
+
_radius = 0;
|
|
237
|
+
_color = 0;
|
|
238
|
+
_radiusGraphics = null;
|
|
239
|
+
|
|
241
240
|
constructor(
|
|
242
241
|
project,
|
|
243
242
|
instance,
|
|
@@ -252,19 +251,6 @@ module.exports = {
|
|
|
252
251
|
pixiContainer,
|
|
253
252
|
pixiResourcesLoader
|
|
254
253
|
);
|
|
255
|
-
this._radius = parseFloat(
|
|
256
|
-
this._associatedObjectConfiguration
|
|
257
|
-
.getProperties()
|
|
258
|
-
.get('radius')
|
|
259
|
-
.getValue()
|
|
260
|
-
);
|
|
261
|
-
if (this._radius <= 0) this._radius = 1;
|
|
262
|
-
const color = objectsRenderingService.rgbOrHexToHexNumber(
|
|
263
|
-
this._associatedObjectConfiguration
|
|
264
|
-
.getProperties()
|
|
265
|
-
.get('color')
|
|
266
|
-
.getValue()
|
|
267
|
-
);
|
|
268
254
|
|
|
269
255
|
// The icon in the middle.
|
|
270
256
|
const lightIconSprite = new PIXI.Sprite(
|
|
@@ -274,18 +260,11 @@ module.exports = {
|
|
|
274
260
|
lightIconSprite.anchor.y = 0.5;
|
|
275
261
|
|
|
276
262
|
// The circle to show the radius of the light.
|
|
277
|
-
|
|
278
|
-
const radiusGraphics = new PIXI.Graphics();
|
|
279
|
-
radiusGraphics.lineStyle(radiusBorderWidth, color, 0.8);
|
|
280
|
-
radiusGraphics.drawCircle(
|
|
281
|
-
0,
|
|
282
|
-
0,
|
|
283
|
-
Math.max(1, this._radius - radiusBorderWidth)
|
|
284
|
-
);
|
|
263
|
+
this._radiusGraphics = new PIXI.Graphics();
|
|
285
264
|
|
|
286
265
|
this._pixiObject = new PIXI.Container();
|
|
287
266
|
this._pixiObject.addChild(lightIconSprite);
|
|
288
|
-
this._pixiObject.addChild(
|
|
267
|
+
this._pixiObject.addChild(this._radiusGraphics);
|
|
289
268
|
this._pixiContainer.addChild(this._pixiObject);
|
|
290
269
|
this.update();
|
|
291
270
|
}
|
|
@@ -307,8 +286,41 @@ module.exports = {
|
|
|
307
286
|
* This is called to update the PIXI object on the scene editor
|
|
308
287
|
*/
|
|
309
288
|
update() {
|
|
289
|
+
const object = gd.castObject(
|
|
290
|
+
this._associatedObjectConfiguration,
|
|
291
|
+
gd.ObjectJsImplementation
|
|
292
|
+
);
|
|
293
|
+
|
|
310
294
|
this._pixiObject.position.x = this._instance.getX();
|
|
311
295
|
this._pixiObject.position.y = this._instance.getY();
|
|
296
|
+
|
|
297
|
+
let radiusGraphicsDirty = false;
|
|
298
|
+
|
|
299
|
+
let radius = object.content.radius;
|
|
300
|
+
if (radius <= 0) radius = 1;
|
|
301
|
+
if (radius !== this._radius) {
|
|
302
|
+
this._radius = radius;
|
|
303
|
+
radiusGraphicsDirty = true;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const color = objectsRenderingService.rgbOrHexToHexNumber(
|
|
307
|
+
object.content.color
|
|
308
|
+
);
|
|
309
|
+
if (color !== this._color) {
|
|
310
|
+
this._color = color;
|
|
311
|
+
radiusGraphicsDirty = true;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (radiusGraphicsDirty) {
|
|
315
|
+
const radiusBorderWidth = 2;
|
|
316
|
+
this._radiusGraphics.clear();
|
|
317
|
+
this._radiusGraphics.lineStyle(radiusBorderWidth, color, 0.8);
|
|
318
|
+
this._radiusGraphics.drawCircle(
|
|
319
|
+
0,
|
|
320
|
+
0,
|
|
321
|
+
Math.max(1, this._radius - radiusBorderWidth)
|
|
322
|
+
);
|
|
323
|
+
}
|
|
312
324
|
}
|
|
313
325
|
|
|
314
326
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var gdjs;(function(v){const
|
|
1
|
+
var gdjs;(function(v){const C=new v.Logger("Light object"),f=class{constructor(t,e){this._texture=null;this._light=null;this._debugMode=!1;this._debugLight=null;this._debugGraphics=null;this._object=t,this._instanceContainer=e,this._manager=t.getObstaclesManager(),this._radius=t.getRadius();const i=t._color;this._color=[i[0]/255,i[1]/255,i[2]/255],this.updateTexture(),this._center=new Float32Array([t.x,t.y]),this._defaultVertexBuffer=new Float32Array(8),this._vertexBuffer=new Float32Array([t.x-this._radius,t.y+this._radius,t.x+this._radius,t.y+this._radius,t.x+this._radius,t.y-this._radius,t.x-this._radius,t.y-this._radius]),this._indexBuffer=new Uint16Array([0,1,2,0,2,3]),this.updateMesh(),this._isPreview=e.getGame().isPreview(),this._lightBoundingPoly=v.Polygon.createRectangle(0,0),this.updateDebugMode(),this._light&&e.getLayer("").getRenderer().addRendererObject(this.getRendererObject(),t.getZOrder())}static _verticesWithAngleComparator(t,e){return t.angle<e.angle?-1:t.angle>e.angle?1:0}static _computeClosestIntersectionPoint(t,e,i,n){const r=t.getX(),o=t.getY(),h=r+n*Math.cos(e),l=o+n*Math.sin(e);let _=n*n;const u=[null,null];for(const g of i){const d=v.Polygon.raycastTest(g,r,o,h,l);d.collision&&d.closeSqDist<=_&&(_=d.closeSqDist,u[0]=d.closeX,u[1]=d.closeY)}return u[0]&&u[1]?u:null}getRendererObject(){return this._debugLight?this._debugLight:this._light}ensureUpToDate(){this._object.isHidden()||(this._debugGraphics&&this._updateDebugGraphics(),this._updateBuffers())}updateMesh(){if(!PIXI.utils.isWebGLSupported()){C.warn("This device does not support webgl, which is required for Lighting Extension.");return}this.updateTexture();const t=this._texture===null?f.defaultFragmentShader:f.texturedFragmentShader,e={center:this._center,radius:this._radius,color:this._color};this._texture&&(e.uSampler=this._texture);const i=PIXI.Shader.from(f.defaultVertexShader,t,e),n=new PIXI.Geometry;n.addAttribute("aVertexPosition",this._vertexBuffer,2).addIndex(this._indexBuffer),this._light?(this._light.shader=i,this._light.geometry=n):(this._light=new PIXI.Mesh(n,i),this._light.blendMode=PIXI.BLEND_MODES.ADD)}updateRadius(){!this._light||(this._radius=this._object.getRadius(),this._light.shader.uniforms.radius=this._radius)}updateColor(){if(!this._light)return;const t=this._object._color;this._color=[t[0]/255,t[1]/255,t[2]/255],this._light.shader.uniforms.color=this._color}updateTexture(){const t=this._object.getTexture();this._texture=t!==""?this._instanceContainer.getGame().getImageManager().getPIXITexture(t):null}updateDebugMode(){!this._light||(this._debugMode=this._object.getDebugMode(),!this._debugLight&&(this._isPreview||this._debugMode)&&(this._debugLight=new PIXI.Container,this._debugLight.addChild(this._light)),this._debugMode&&!this._debugGraphics&&(this._debugGraphics=new PIXI.Graphics,this._debugLight.addChild(this._debugGraphics)),!this._debugMode&&this._debugGraphics&&(this._debugLight.removeChild(this._debugGraphics),this._debugGraphics.destroy(),this._debugGraphics=null),this.ensureUpToDate())}_updateDebugGraphics(){const t=this._debugGraphics,e=this._computeLightVertices();if(!e.length){t.clear(),t.lineStyle(1,16711680,1).moveTo(this._object.x,this._object.y).lineTo(this._object.x-this._radius,this._object.y+this._radius).lineTo(this._object.x+this._radius,this._object.y+this._radius).moveTo(this._object.x,this._object.y).lineTo(this._object.x+this._radius,this._object.y+this._radius).lineTo(this._object.x+this._radius,this._object.y-this._radius).moveTo(this._object.x,this._object.y).lineTo(this._object.x+this._radius,this._object.y-this._radius).lineTo(this._object.x-this._radius,this._object.y-this._radius).moveTo(this._object.x,this._object.y).lineTo(this._object.x-this._radius,this._object.y-this._radius).lineTo(this._object.x-this._radius,this._object.y+this._radius);return}const i=new Array(2*e.length+2);i[0]=this._object.x,i[1]=this._object.y;for(let r=2;r<2*e.length+2;r+=2)i[r]=e[r/2-1][0],i[r+1]=e[r/2-1][1];t.clear(),t.moveTo(i[2],i[3]);const n=i.length;for(let r=2;r<n;r+=2){const o=r%4==0?16711680:65280,h=r+2>=n?2:r+2,l=r+3>=n?3:r+3;t.lineStyle(1,o,1).lineTo(i[r],i[r+1]).lineTo(i[h],i[l]).moveTo(i[0],i[1]).lineTo(i[r],i[r+1]).moveTo(i[0],i[1]).lineTo(i[h],i[l])}}_updateBuffers(){if(!this._light)return;this._center[0]=this._object.x,this._center[1]=this._object.y;const t=this._computeLightVertices();if(t.length===0){this._defaultVertexBuffer[0]=this._object.x-this._radius,this._defaultVertexBuffer[1]=this._object.y+this._radius,this._defaultVertexBuffer[2]=this._object.x+this._radius,this._defaultVertexBuffer[3]=this._object.y+this._radius,this._defaultVertexBuffer[4]=this._object.x+this._radius,this._defaultVertexBuffer[5]=this._object.y-this._radius,this._defaultVertexBuffer[6]=this._object.x-this._radius,this._defaultVertexBuffer[7]=this._object.y-this._radius,this._light.shader.uniforms.center=this._center,this._light.geometry.getBuffer("aVertexPosition").update(this._defaultVertexBuffer),this._light.geometry.getIndex().update(f._defaultIndexBuffer);return}const e=t.length;let i=!1,n=null,r=null;this._vertexBuffer.length>2*e+2&&(this._vertexBuffer.length<4*e+4?(i=!0,n=this._vertexBuffer.subarray(0,2*e+2),r=this._indexBuffer.subarray(0,3*e)):(this._vertexBuffer=new Float32Array(2*e+2),this._indexBuffer=new Uint16Array(3*e))),this._vertexBuffer.length<2*e+2&&(this._vertexBuffer=new Float32Array(2*e+2),this._indexBuffer=new Uint16Array(3*e)),this._vertexBuffer[0]=this._object.x,this._vertexBuffer[1]=this._object.y;for(let o=2;o<2*e+2;o+=2)this._vertexBuffer[o]=t[o/2-1][0],this._vertexBuffer[o+1]=t[o/2-1][1];for(let o=0;o<3*e;o+=3)this._indexBuffer[o]=0,this._indexBuffer[o+1]=o/3+1,o/3+1!==e?this._indexBuffer[o+2]=o/3+2:this._indexBuffer[o+2]=1;this._light.shader.uniforms.center=this._center,i?(this._light.geometry.getBuffer("aVertexPosition").update(n),this._light.geometry.getIndex().update(r)):(this._light.geometry.getBuffer("aVertexPosition").update(this._vertexBuffer),this._light.geometry.getIndex().update(this._indexBuffer))}_computeLightVertices(){const t=[];this._manager&&this._manager.getAllObstaclesAround(this._object,this._radius,t);const e=this._object.getX()-this._radius,i=this._object.getY()-this._radius,n=this._object.getX()+this._radius,r=this._object.getY()+this._radius;if(t.length===0)return t;const o=this._object.getHitBoxes()[0];for(let s=0;s<4;s++)this._lightBoundingPoly.vertices[s][0]=o.vertices[s][0],this._lightBoundingPoly.vertices[s][1]=o.vertices[s][1];const h=[];h.push(this._lightBoundingPoly);for(let s=0;s<t.length;s++){const c=t[s].owner.getHitBoxesAround(e,i,n,r);for(const y of c)h.push(y)}let l=this._object.x+this._radius,_=this._object.x-this._radius,u=this._object.y+this._radius,g=this._object.y-this._radius;const d=[];for(let s=1;s<h.length;s++){const c=h[s].vertices,y=c.length;for(let a=0;a<y;a++)d.push(c[a]),c[a][0]<_&&(_=c[a][0]),c[a][0]>l&&(l=c[a][0]),c[a][1]<g&&(g=c[a][1]),c[a][1]>u&&(u=c[a][1])}h[0].vertices[0][0]=_,h[0].vertices[0][1]=g,h[0].vertices[1][0]=l,h[0].vertices[1][1]=g,h[0].vertices[2][0]=l,h[0].vertices[2][1]=u,h[0].vertices[3][0]=_,h[0].vertices[3][1]=u;const j=Math.sqrt(Math.max((this._object.x-_)*(this._object.x-_)+(this._object.y-g)*(this._object.y-g),(l-this._object.x)*(l-this._object.x)+(this._object.y-g)*(this._object.y-g),(l-this._object.x)*(l-this._object.x)+(u-this._object.y)*(u-this._object.y),(this._object.x-_)*(this._object.x-_)+(u-this._object.y)*(u-this._object.y)));for(let s=0;s<4;s++)d.push(h[0].vertices[s]);const x=[],A=d.length;for(let s=0;s<A;s++){const c=d[s][0]-this._object.x,y=d[s][1]-this._object.y,a=Math.atan2(y,c),B=f._computeClosestIntersectionPoint(this._object,a,h,j);B&&x.push({vertex:B,angle:a});const P=f._computeClosestIntersectionPoint(this._object,a+1e-4,h,j);P&&x.push({vertex:P,angle:a+1e-4});const I=f._computeClosestIntersectionPoint(this._object,a-1e-4,h,j);I&&x.push({vertex:I,angle:a-1e-4})}x.sort(f._verticesWithAngleComparator);const p=x.length;if(p===0)return[];const m=[x[0].vertex];for(let s=1;s<p;s++)x[s].angle!==x[s-1].angle&&m.push(x[s].vertex);return m}};let b=f;b._defaultIndexBuffer=new Uint16Array([0,1,2,0,2,3]),b.defaultVertexShader=`
|
|
2
2
|
precision highp float;
|
|
3
3
|
attribute vec2 aVertexPosition;
|
|
4
4
|
|