Merge branch 'gamestate-api-read' of github.com:jonnytest1/workadventure into metadataScriptingApi

This commit is contained in:
GRL 2021-05-18 15:18:35 +02:00
commit 201fcf6afa
16 changed files with 9165 additions and 319 deletions

View file

@ -8,12 +8,7 @@ import {SelectCharacterSceneName} from "../Login/SelectCharacterScene";
import {EnableCameraSceneName} from "../Login/EnableCameraScene";
import {localUserStore} from "../../Connexion/LocalUserStore";
export interface HasMovedEvent {
direction: string;
moving: boolean;
x: number;
y: number;
}
/**
* This class should be responsible for any scene starting/stopping

View file

@ -9,7 +9,7 @@ import type {
PositionInterface,
RoomJoinedMessageInterface
} from "../../Connexion/ConnexionModels";
import {CurrentGamerInterface, hasMovedEventName, Player} from "../Player/Player";
import { CurrentGamerInterface, hasMovedEventName, Player } from "../Player/Player";
import {
DEBUG_MODE,
JITSI_PRIVATE_MODE,
@ -25,15 +25,15 @@ import type {
ITiledMapTileLayer,
ITiledTileSet
} from "../Map/ITiledMap";
import type {AddPlayerInterface} from "./AddPlayerInterface";
import {PlayerAnimationDirections} from "../Player/Animation";
import {PlayerMovement} from "./PlayerMovement";
import {PlayersPositionInterpolator} from "./PlayersPositionInterpolator";
import {RemotePlayer} from "../Entity/RemotePlayer";
import {Queue} from 'queue-typescript';
import {SimplePeer, UserSimplePeerInterface} from "../../WebRtc/SimplePeer";
import {ReconnectingSceneName} from "../Reconnecting/ReconnectingScene";
import {lazyLoadPlayerCharacterTextures, loadCustomTexture} from "../Entity/PlayerTexturesLoadingManager";
import type { AddPlayerInterface } from "./AddPlayerInterface";
import { PlayerAnimationDirections } from "../Player/Animation";
import { PlayerMovement } from "./PlayerMovement";
import { PlayersPositionInterpolator } from "./PlayersPositionInterpolator";
import { RemotePlayer } from "../Entity/RemotePlayer";
import { Queue } from 'queue-typescript';
import { SimplePeer, UserSimplePeerInterface } from "../../WebRtc/SimplePeer";
import { ReconnectingSceneName } from "../Reconnecting/ReconnectingScene";
import { lazyLoadPlayerCharacterTextures, loadCustomTexture } from "../Entity/PlayerTexturesLoadingManager";
import {
CenterListener,
JITSI_MESSAGE_PROPERTIES,
@ -46,56 +46,57 @@ import {
AUDIO_VOLUME_PROPERTY,
AUDIO_LOOP_PROPERTY
} from "../../WebRtc/LayoutManager";
import {GameMap} from "./GameMap";
import {coWebsiteManager} from "../../WebRtc/CoWebsiteManager";
import {mediaManager} from "../../WebRtc/MediaManager";
import type {ItemFactoryInterface} from "../Items/ItemFactoryInterface";
import type {ActionableItem} from "../Items/ActionableItem";
import {UserInputManager} from "../UserInput/UserInputManager";
import type {UserMovedMessage} from "../../Messages/generated/messages_pb";
import {ProtobufClientUtils} from "../../Network/ProtobufClientUtils";
import {connectionManager} from "../../Connexion/ConnectionManager";
import type {RoomConnection} from "../../Connexion/RoomConnection";
import {GlobalMessageManager} from "../../Administration/GlobalMessageManager";
import {userMessageManager} from "../../Administration/UserMessageManager";
import {ConsoleGlobalMessageManager} from "../../Administration/ConsoleGlobalMessageManager";
import {ResizableScene} from "../Login/ResizableScene";
import {Room} from "../../Connexion/Room";
import {jitsiFactory} from "../../WebRtc/JitsiFactory";
import {urlManager} from "../../Url/UrlManager";
import {audioManager} from "../../WebRtc/AudioManager";
import {PresentationModeIcon} from "../Components/PresentationModeIcon";
import {ChatModeIcon} from "../Components/ChatModeIcon";
import {OpenChatIcon, openChatIconName} from "../Components/OpenChatIcon";
import {SelectCharacterScene, SelectCharacterSceneName} from "../Login/SelectCharacterScene";
import {TextureError} from "../../Exception/TextureError";
import {addLoader} from "../Components/Loader";
import {ErrorSceneName} from "../Reconnecting/ErrorScene";
import {localUserStore} from "../../Connexion/LocalUserStore";
import {iframeListener} from "../../Api/IframeListener";
import {HtmlUtils} from "../../WebRtc/HtmlUtils";
import { GameMap } from "./GameMap";
import { coWebsiteManager } from "../../WebRtc/CoWebsiteManager";
import { mediaManager } from "../../WebRtc/MediaManager";
import type { ItemFactoryInterface } from "../Items/ItemFactoryInterface";
import type { ActionableItem } from "../Items/ActionableItem";
import { UserInputManager } from "../UserInput/UserInputManager";
import type { UserMovedMessage } from "../../Messages/generated/messages_pb";
import { ProtobufClientUtils } from "../../Network/ProtobufClientUtils";
import { connectionManager } from "../../Connexion/ConnectionManager";
import type { RoomConnection } from "../../Connexion/RoomConnection";
import { GlobalMessageManager } from "../../Administration/GlobalMessageManager";
import { userMessageManager } from "../../Administration/UserMessageManager";
import { ConsoleGlobalMessageManager } from "../../Administration/ConsoleGlobalMessageManager";
import { ResizableScene } from "../Login/ResizableScene";
import { Room } from "../../Connexion/Room";
import { jitsiFactory } from "../../WebRtc/JitsiFactory";
import { urlManager } from "../../Url/UrlManager";
import { audioManager } from "../../WebRtc/AudioManager";
import { PresentationModeIcon } from "../Components/PresentationModeIcon";
import { ChatModeIcon } from "../Components/ChatModeIcon";
import { OpenChatIcon, openChatIconName } from "../Components/OpenChatIcon";
import { SelectCharacterScene, SelectCharacterSceneName } from "../Login/SelectCharacterScene";
import { TextureError } from "../../Exception/TextureError";
import { addLoader } from "../Components/Loader";
import { ErrorSceneName } from "../Reconnecting/ErrorScene";
import { localUserStore } from "../../Connexion/LocalUserStore";
import { iframeListener } from "../../Api/IframeListener";
import { HtmlUtils } from "../../WebRtc/HtmlUtils";
import Texture = Phaser.Textures.Texture;
import Sprite = Phaser.GameObjects.Sprite;
import CanvasTexture = Phaser.Textures.CanvasTexture;
import GameObject = Phaser.GameObjects.GameObject;
import FILE_LOAD_ERROR = Phaser.Loader.Events.FILE_LOAD_ERROR;
import DOMElement = Phaser.GameObjects.DOMElement;
import type {Subscription} from "rxjs";
import {worldFullMessageStream} from "../../Connexion/WorldFullMessageStream";
import type { Subscription } from "rxjs";
import { worldFullMessageStream } from "../../Connexion/WorldFullMessageStream";
import { lazyLoadCompanionResource } from "../Companion/CompanionTexturesLoadingManager";
import RenderTexture = Phaser.GameObjects.RenderTexture;
import Tilemap = Phaser.Tilemaps.Tilemap;
import {DirtyScene} from "./DirtyScene";
import {TextUtils} from "../Components/TextUtils";
import {touchScreenManager} from "../../Touch/TouchScreenManager";
import {PinchManager} from "../UserInput/PinchManager";
import {joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey} from "../Components/MobileJoystick";
import {waScaleManager} from "../Services/WaScaleManager";
import { DirtyScene } from "./DirtyScene";
import { TextUtils } from "../Components/TextUtils";
import { touchScreenManager } from "../../Touch/TouchScreenManager";
import { PinchManager } from "../UserInput/PinchManager";
import { joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey } from "../Components/MobileJoystick";
import { waScaleManager } from "../Services/WaScaleManager";
import { HasPlayerMovedEvent } from '../../Api/Events/HasPlayerMovedEvent';
import {LayerEvent} from "../../Api/Events/LayerEvent";
import {SetPropertyEvent} from "../../Api/Events/setPropertyEvent";
import {SetPropertyEvent} from "../../Api/Events/setPropertyEve
export interface GameSceneInitInterface {
initPosition: PointInterface|null,
initPosition: PointInterface | null,
reconnecting: boolean
}
@ -132,10 +133,10 @@ interface DeleteGroupEventInterface {
const defaultStartLayerName = 'start';
export class GameScene extends DirtyScene implements CenterListener {
Terrains : Array<Phaser.Tilemaps.Tileset>;
Terrains: Array<Phaser.Tilemaps.Tileset>;
CurrentPlayer!: CurrentGamerInterface;
MapPlayers!: Phaser.Physics.Arcade.Group;
MapPlayersByKey : Map<number, RemotePlayer> = new Map<number, RemotePlayer>();
MapPlayersByKey: Map<number, RemotePlayer> = new Map<number, RemotePlayer>();
Map!: Phaser.Tilemaps.Tilemap;
Objects!: Array<Phaser.Physics.Arcade.Sprite>;
mapFile!: ITiledMap;
@ -144,10 +145,10 @@ export class GameScene extends DirtyScene implements CenterListener {
startY!: number;
circleTexture!: CanvasTexture;
circleRedTexture!: CanvasTexture;
pendingEvents: Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface> = new Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface>();
private initPosition: PositionInterface|null = null;
pendingEvents: Queue<InitUserPositionEventInterface | AddPlayerEventInterface | RemovePlayerEventInterface | UserMovedEventInterface | GroupCreatedUpdatedEventInterface | DeleteGroupEventInterface> = new Queue<InitUserPositionEventInterface | AddPlayerEventInterface | RemovePlayerEventInterface | UserMovedEventInterface | GroupCreatedUpdatedEventInterface | DeleteGroupEventInterface>();
private initPosition: PositionInterface | null = null;
private playersPositionInterpolator = new PlayersPositionInterpolator();
public connection: RoomConnection|undefined;
public connection: RoomConnection | undefined;
private simplePeer!: SimplePeer;
private GlobalMessageManager!: GlobalMessageManager;
public ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager;
@ -156,14 +157,14 @@ export class GameScene extends DirtyScene implements CenterListener {
// A promise that will resolve when the "create" method is called (signaling loading is ended)
private createPromise: Promise<void>;
private createPromiseResolve!: (value?: void | PromiseLike<void>) => void;
private iframeSubscriptionList! : Array<Subscription>;
private iframeSubscriptionList!: Array<Subscription>;
MapUrlFile: string;
RoomId: string;
instance: string;
currentTick!: number;
lastSentTick!: number; // The last tick at which a position was sent.
lastMoveEventSent: HasMovedEvent = {
lastMoveEventSent: HasPlayerMovedEvent = {
direction: '',
moving: false,
x: -1000,
@ -175,23 +176,23 @@ export class GameScene extends DirtyScene implements CenterListener {
private gameMap!: GameMap;
private actionableItems: Map<number, ActionableItem> = new Map<number, ActionableItem>();
// The item that can be selected by pressing the space key.
private outlinedItem: ActionableItem|null = null;
private outlinedItem: ActionableItem | null = null;
public userInputManager!: UserInputManager;
private isReconnecting: boolean|undefined = undefined;
private isReconnecting: boolean | undefined = undefined;
private startLayerName!: string | null;
private openChatIcon!: OpenChatIcon;
private playerName!: string;
private characterLayers!: string[];
private companion!: string|null;
private messageSubscription: Subscription|null = null;
private companion!: string | null;
private messageSubscription: Subscription | null = null;
private popUpElements : Map<number, DOMElement> = new Map<number, Phaser.GameObjects.DOMElement>();
private originalMapUrl: string|undefined;
private pinchManager: PinchManager|undefined;
private originalMapUrl: string | undefined;
private pinchManager: PinchManager | undefined;
private physicsEnabled: boolean = true;
private mapTransitioning: boolean = false; //used to prevent transitions happenning at the same time.
private onVisibilityChangeCallback: () => void;
constructor(private room: Room, MapUrlFile: string, customKey?: string|undefined) {
constructor(private room: Room, MapUrlFile: string, customKey?: string | undefined) {
super({
key: customKey ?? room.id
});
@ -227,13 +228,13 @@ export class GameScene extends DirtyScene implements CenterListener {
this.load.image(joystickBaseKey, joystickBaseImg);
this.load.image(joystickThumbKey, joystickThumbImg);
}
this.load.on(FILE_LOAD_ERROR, (file: {src: string}) => {
this.load.on(FILE_LOAD_ERROR, (file: { src: string }) => {
// If we happen to be in HTTP and we are trying to load a URL in HTTPS only... (this happens only in dev environments)
if (window.location.protocol === 'http:' && file.src === this.MapUrlFile && file.src.startsWith('http:') && this.originalMapUrl === undefined) {
this.originalMapUrl = this.MapUrlFile;
this.MapUrlFile = this.MapUrlFile.replace('http://', 'https://');
this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile);
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data);
});
return;
@ -247,7 +248,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.originalMapUrl = this.MapUrlFile;
this.MapUrlFile = this.MapUrlFile.replace('https://', 'http://');
this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile);
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data);
});
return;
@ -259,7 +260,7 @@ export class GameScene extends DirtyScene implements CenterListener {
message: this.originalMapUrl ?? file.src
});
});
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data);
});
//TODO strategy to add access token
@ -271,7 +272,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.onMapLoad(data);
}
this.load.spritesheet('layout_modes', 'resources/objects/layout_modes.png', {frameWidth: 32, frameHeight: 32});
this.load.spritesheet('layout_modes', 'resources/objects/layout_modes.png', { frameWidth: 32, frameHeight: 32 });
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
//this function must stay at the end of preload function
@ -300,7 +301,7 @@ export class GameScene extends DirtyScene implements CenterListener {
for (const layer of this.mapFile.layers) {
if (layer.type === 'objectgroup') {
for (const object of layer.objects) {
let objectsOfType: ITiledMapObject[]|undefined;
let objectsOfType: ITiledMapObject[] | undefined;
if (!objects.has(object.type)) {
objectsOfType = new Array<ITiledMapObject>();
} else {
@ -328,7 +329,7 @@ export class GameScene extends DirtyScene implements CenterListener {
}
default:
continue;
//throw new Error('Unsupported object type: "'+ itemType +'"');
//throw new Error('Unsupported object type: "'+ itemType +'"');
}
itemFactory.preload(this.load);
@ -363,7 +364,7 @@ export class GameScene extends DirtyScene implements CenterListener {
}
//hook initialisation
init(initData : GameSceneInitInterface) {
init(initData: GameSceneInitInterface) {
if (initData.initPosition !== undefined) {
this.initPosition = initData.initPosition; //todo: still used?
}
@ -433,7 +434,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.Objects = new Array<Phaser.Physics.Arcade.Sprite>();
//initialise list of other player
this.MapPlayers = this.physics.add.group({immovable: true});
this.MapPlayers = this.physics.add.group({ immovable: true });
//create input to move
@ -524,7 +525,7 @@ export class GameScene extends DirtyScene implements CenterListener {
bottom: camera.scrollY + camera.height,
},
this.companion
).then((onConnect: OnConnectInterface) => {
).then((onConnect: OnConnectInterface) => {
this.connection = onConnect.connection;
this.connection.onUserJoins((message: MessageUserJoined) => {
@ -630,7 +631,7 @@ export class GameScene extends DirtyScene implements CenterListener {
//listen event to share position of user
this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this))
this.CurrentPlayer.on(hasMovedEventName, this.outlineItem.bind(this))
this.CurrentPlayer.on(hasMovedEventName, (event: HasMovedEvent) => {
this.CurrentPlayer.on(hasMovedEventName, (event: HasPlayerMovedEvent) => {
this.gameMap.setPosition(event.x, event.y);
})
@ -676,23 +677,23 @@ export class GameScene extends DirtyScene implements CenterListener {
const contextRed = this.circleRedTexture.context;
contextRed.beginPath();
contextRed.arc(48, 48, 48, 0, 2 * Math.PI, false);
//context.lineWidth = 5;
//context.lineWidth = 5;
contextRed.strokeStyle = '#ff0000';
contextRed.stroke();
this.circleRedTexture.refresh();
}
private safeParseJSONstring(jsonString: string|undefined, propertyName: string) {
private safeParseJSONstring(jsonString: string | undefined, propertyName: string) {
try {
return jsonString ? JSON.parse(jsonString) : {};
} catch(e) {
} catch (e) {
console.warn('Invalid JSON found in property "' + propertyName + '" of the map:' + jsonString, e);
return {}
}
}
private triggerOnMapLayerPropertyChange(){
private triggerOnMapLayerPropertyChange() {
this.gameMap.onPropertyChange('exitSceneUrl', (newValue, oldValue) => {
if (newValue) this.onMapExit(newValue as string);
});
@ -703,22 +704,22 @@ export class GameScene extends DirtyScene implements CenterListener {
if (newValue === undefined) {
layoutManager.removeActionButton('openWebsite', this.userInputManager);
coWebsiteManager.closeCoWebsite();
}else{
} else {
const openWebsiteFunction = () => {
coWebsiteManager.loadCoWebsite(newValue as string, this.MapUrlFile, allProps.get('openWebsiteAllowApi') as boolean | undefined, allProps.get('openWebsitePolicy') as string | undefined);
layoutManager.removeActionButton('openWebsite', this.userInputManager);
};
const openWebsiteTriggerValue = allProps.get(TRIGGER_WEBSITE_PROPERTIES);
if(openWebsiteTriggerValue && openWebsiteTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
if (openWebsiteTriggerValue && openWebsiteTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
let message = allProps.get(WEBSITE_MESSAGE_PROPERTIES);
if(message === undefined){
if (message === undefined) {
message = 'Press SPACE or touch here to open web site';
}
layoutManager.addActionButton('openWebsite', message.toString(), () => {
openWebsiteFunction();
}, this.userInputManager);
}else{
} else {
openWebsiteFunction();
}
}
@ -727,12 +728,12 @@ export class GameScene extends DirtyScene implements CenterListener {
if (newValue === undefined) {
layoutManager.removeActionButton('jitsiRoom', this.userInputManager);
this.stopJitsi();
}else{
} else {
const openJitsiRoomFunction = () => {
const roomName = jitsiFactory.getRoomName(newValue.toString(), this.instance);
const jitsiUrl = allProps.get("jitsiUrl") as string|undefined;
const jitsiUrl = allProps.get("jitsiUrl") as string | undefined;
if (JITSI_PRIVATE_MODE && !jitsiUrl) {
const adminTag = allProps.get("jitsiRoomAdminTag") as string|undefined;
const adminTag = allProps.get("jitsiRoomAdminTag") as string | undefined;
this.connection?.emitQueryJitsiJwtMessage(roomName, adminTag);
} else {
@ -742,7 +743,7 @@ export class GameScene extends DirtyScene implements CenterListener {
}
const jitsiTriggerValue = allProps.get(TRIGGER_JITSI_PROPERTIES);
if(jitsiTriggerValue && jitsiTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
if (jitsiTriggerValue && jitsiTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
let message = allProps.get(JITSI_MESSAGE_PROPERTIES);
if (message === undefined) {
message = 'Press SPACE or touch here to enter Jitsi Meet room';
@ -750,7 +751,7 @@ export class GameScene extends DirtyScene implements CenterListener {
layoutManager.addActionButton('jitsiRoom', message.toString(), () => {
openJitsiRoomFunction();
}, this.userInputManager);
}else{
} else {
openJitsiRoomFunction();
}
}
@ -763,8 +764,8 @@ export class GameScene extends DirtyScene implements CenterListener {
}
});
this.gameMap.onPropertyChange('playAudio', (newValue, oldValue, allProps) => {
const volume = allProps.get(AUDIO_VOLUME_PROPERTY) as number|undefined;
const loop = allProps.get(AUDIO_LOOP_PROPERTY) as boolean|undefined;
const volume = allProps.get(AUDIO_VOLUME_PROPERTY) as number | undefined;
const loop = allProps.get(AUDIO_LOOP_PROPERTY) as boolean | undefined;
newValue === undefined ? audioManager.unloadAudio() : audioManager.playAudio(newValue, this.getMapDirUrl(), volume, loop);
});
// TODO: This legacy property should be removed at some point
@ -783,13 +784,13 @@ export class GameScene extends DirtyScene implements CenterListener {
}
private listenToIframeEvents(): void {
this.iframeSubscriptionList = [];
this.iframeSubscriptionList.push(iframeListener.openPopupStream.subscribe((openPopupEvent) => {
this.iframeSubscriptionList = [];
this.iframeSubscriptionList.push(iframeListener.openPopupStream.subscribe((openPopupEvent) => {
let objectLayerSquare : ITiledMapObject;
let objectLayerSquare: ITiledMapObject;
const targetObjectData = this.getObjectLayerData(openPopupEvent.targetObject);
if (targetObjectData !== undefined){
objectLayerSquare = targetObjectData;
if (targetObjectData !== undefined) {
objectLayerSquare = targetObjectData;
} else {
console.error("Error while opening a popup. Cannot find an object on the map with name '" + openPopupEvent.targetObject + "'. The first parameter of WA.openPopup() must be the name of a rectangle object in your map.");
return;
@ -802,14 +803,14 @@ ${escapedMessage}
html += buttonContainer;
let id = 0;
for (const button of openPopupEvent.buttons) {
html += `<button type="button" class="nes-btn is-${HtmlUtils.escapeHtml(button.className ?? '')}" id="popup-${openPopupEvent.popupId}-${id}">${HtmlUtils.escapeHtml(button.label)}</button>`;
html += `<button type="button" class="nes-btn is-${HtmlUtils.escapeHtml(button.className ?? '')}" id="popup-${openPopupEvent.popupId}-${id}">${HtmlUtils.escapeHtml(button.label)}</button>`;
id++;
}
html += '</div>';
const domElement = this.add.dom(objectLayerSquare.x ,
const domElement = this.add.dom(objectLayerSquare.x,
objectLayerSquare.y).createFromHTML(html);
const container : HTMLDivElement = domElement.getChildByID("container") as HTMLDivElement;
const container: HTMLDivElement = domElement.getChildByID("container") as HTMLDivElement;
container.style.width = objectLayerSquare.width + "px";
domElement.scale = 0;
domElement.setClassName('popUpElement');
@ -829,10 +830,10 @@ ${escapedMessage}
id++;
}
this.tweens.add({
targets : domElement ,
scale : 1,
ease : "EaseOut",
duration : 400,
targets: domElement,
scale: 1,
ease: "EaseOut",
duration: 400,
});
this.popUpElements.set(openPopupEvent.popupId, domElement);
@ -841,36 +842,45 @@ ${escapedMessage}
this.iframeSubscriptionList.push(iframeListener.closePopupStream.subscribe((closePopupEvent) => {
const popUpElement = this.popUpElements.get(closePopupEvent.popupId);
if (popUpElement === undefined) {
console.error('Could not close popup with ID ', closePopupEvent.popupId,'. Maybe it has already been closed?');
console.error('Could not close popup with ID ', closePopupEvent.popupId, '. Maybe it has already been closed?');
}
this.tweens.add({
targets : popUpElement ,
scale : 0,
ease : "EaseOut",
duration : 400,
onComplete : () => {
targets: popUpElement,
scale: 0,
ease: "EaseOut",
duration: 400,
onComplete: () => {
popUpElement?.destroy();
this.popUpElements.delete(closePopupEvent.popupId);
},
});
}));
this.iframeSubscriptionList.push(iframeListener.disablePlayerControlStream.subscribe(()=>{
this.iframeSubscriptionList.push(iframeListener.disablePlayerControlStream.subscribe(() => {
this.userInputManager.disableControls();
}));
this.iframeSubscriptionList.push(iframeListener.enablePlayerControlStream.subscribe(()=>{
this.iframeSubscriptionList.push(iframeListener.enablePlayerControlStream.subscribe(() => {
this.userInputManager.restoreControls();
}));
let scriptedBubbleSprite : Sprite;
this.iframeSubscriptionList.push(iframeListener.displayBubbleStream.subscribe(()=>{
scriptedBubbleSprite = new Sprite(this,this.CurrentPlayer.x + 25,this.CurrentPlayer.y,'circleSprite-white');
this.iframeSubscriptionList.push(iframeListener.gameStateStream.subscribe(() => {
iframeListener.sendFrozenGameStateEvent({
mapUrl: this.MapUrlFile,
startLayerName: this.startLayerName,
uuid: localUserStore.getLocalUser()?.uuid,
roomId: this.RoomId,
})
}));
let scriptedBubbleSprite: Sprite;
this.iframeSubscriptionList.push(iframeListener.displayBubbleStream.subscribe(() => {
scriptedBubbleSprite = new Sprite(this, this.CurrentPlayer.x + 25, this.CurrentPlayer.y, 'circleSprite-white');
scriptedBubbleSprite.setDisplayOrigin(48, 48);
this.add.existing(scriptedBubbleSprite);
}));
this.iframeSubscriptionList.push(iframeListener.removeBubbleStream.subscribe(()=>{
this.iframeSubscriptionList.push(iframeListener.removeBubbleStream.subscribe(() => {
scriptedBubbleSprite.destroy();
}));
@ -965,7 +975,7 @@ ${escapedMessage}
this.userInputManager.destroy();
this.pinchManager?.destroy();
for(const iframeEvents of this.iframeSubscriptionList){
for (const iframeEvents of this.iframeSubscriptionList) {
iframeEvents.unsubscribe();
}
@ -987,7 +997,7 @@ ${escapedMessage}
private switchLayoutMode(): void {
//if discussion is activated, this layout cannot be activated
if(mediaManager.activatedDiscussion){
if (mediaManager.activatedDiscussion) {
return;
}
const mode = layoutManager.getLayoutMode();
@ -1028,24 +1038,24 @@ ${escapedMessage}
private initPositionFromLayerName(layerName: string) {
for (const layer of this.gameMap.flatLayers) {
if ((layerName === layer.name || layer.name.endsWith('/'+layerName)) && layer.type === 'tilelayer' && (layerName === defaultStartLayerName || this.isStartLayer(layer))) {
if ((layerName === layer.name || layer.name.endsWith('/' + layerName)) && layer.type === 'tilelayer' && (layerName === defaultStartLayerName || this.isStartLayer(layer))) {
const startPosition = this.startUser(layer);
this.startX = startPosition.x + this.mapFile.tilewidth/2;
this.startY = startPosition.y + this.mapFile.tileheight/2;
this.startX = startPosition.x + this.mapFile.tilewidth / 2;
this.startY = startPosition.y + this.mapFile.tileheight / 2;
}
}
}
private getExitUrl(layer: ITiledMapLayer): string|undefined {
return this.getProperty(layer, "exitUrl") as string|undefined;
private getExitUrl(layer: ITiledMapLayer): string | undefined {
return this.getProperty(layer, "exitUrl") as string | undefined;
}
/**
* @deprecated the map property exitSceneUrl is deprecated
*/
private getExitSceneUrl(layer: ITiledMapLayer): string|undefined {
return this.getProperty(layer, "exitSceneUrl") as string|undefined;
private getExitSceneUrl(layer: ITiledMapLayer): string | undefined {
return this.getProperty(layer, "exitSceneUrl") as string | undefined;
}
private isStartLayer(layer: ITiledMapLayer): boolean {
@ -1056,8 +1066,8 @@ ${escapedMessage}
return (this.getProperties(map, "script") as string[]).map((script) => (new URL(script, this.MapUrlFile)).toString());
}
private getProperty(layer: ITiledMapLayer|ITiledMap, name: string): string|boolean|number|undefined {
const properties: ITiledMapLayerProperty[]|undefined = layer.properties;
private getProperty(layer: ITiledMapLayer | ITiledMap, name: string): string | boolean | number | undefined {
const properties: ITiledMapLayerProperty[] | undefined = layer.properties;
if (!properties) {
return undefined;
}
@ -1068,8 +1078,8 @@ ${escapedMessage}
return obj.value;
}
private getProperties(layer: ITiledMapLayer|ITiledMap, name: string): (string|number|boolean|undefined)[] {
const properties: ITiledMapLayerProperty[]|undefined = layer.properties;
private getProperties(layer: ITiledMapLayer | ITiledMap, name: string): (string | number | boolean | undefined)[] {
const properties: ITiledMapLayerProperty[] | undefined = layer.properties;
if (!properties) {
return [];
}
@ -1077,30 +1087,30 @@ ${escapedMessage}
}
//todo: push that into the gameManager
private async loadNextGame(exitSceneIdentifier: string){
const {roomId, hash} = Room.getIdFromIdentifier(exitSceneIdentifier, this.MapUrlFile, this.instance);
private async loadNextGame(exitSceneIdentifier: string) {
const { roomId, hash } = Room.getIdFromIdentifier(exitSceneIdentifier, this.MapUrlFile, this.instance);
const room = new Room(roomId);
await gameManager.loadMap(room, this.scene);
}
private startUser(layer: ITiledMapTileLayer): PositionInterface {
const tiles = layer.data;
if (typeof(tiles) === 'string') {
if (typeof (tiles) === 'string') {
throw new Error('The content of a JSON map must be filled as a JSON array, not as a string');
}
const possibleStartPositions : PositionInterface[] = [];
tiles.forEach((objectKey : number, key: number) => {
if(objectKey === 0){
const possibleStartPositions: PositionInterface[] = [];
tiles.forEach((objectKey: number, key: number) => {
if (objectKey === 0) {
return;
}
const y = Math.floor(key / layer.width);
const x = key % layer.width;
possibleStartPositions.push({x: x * this.mapFile.tilewidth, y: y * this.mapFile.tilewidth});
possibleStartPositions.push({ x: x * this.mapFile.tilewidth, y: y * this.mapFile.tilewidth });
});
// Get a value at random amongst allowed values
if (possibleStartPositions.length === 0) {
console.warn('The start layer "'+layer.name+'" for this map is empty.');
console.warn('The start layer "' + layer.name + '" for this map is empty.');
return {
x: 0,
y: 0
@ -1112,7 +1122,7 @@ ${escapedMessage}
//todo: in a dedicated class/function?
initCamera() {
this.cameras.main.setBounds(0,0, this.Map.widthInPixels, this.Map.heightInPixels);
this.cameras.main.setBounds(0, 0, this.Map.widthInPixels, this.Map.heightInPixels);
this.cameras.main.startFollow(this.CurrentPlayer, true);
this.updateCameraOffset();
}
@ -1143,7 +1153,7 @@ ${escapedMessage}
}
}
createCurrentPlayer(){
createCurrentPlayer() {
//TODO create animation moving between exit and start
const texturesPromise = lazyLoadPlayerCharacterTextures(this.load, this.characterLayers);
try {
@ -1159,8 +1169,8 @@ ${escapedMessage}
this.companion,
this.companion !== null ? lazyLoadCompanionResource(this.load, this.companion) : undefined
);
}catch (err){
if(err instanceof TextureError) {
} catch (err) {
if (err instanceof TextureError) {
gameManager.leaveGame(this, SelectCharacterSceneName, new SelectCharacterScene());
}
throw err;
@ -1170,7 +1180,7 @@ ${escapedMessage}
this.createCollisionWithPlayer();
}
pushPlayerPosition(event: HasMovedEvent) {
pushPlayerPosition(event: HasPlayerMovedEvent) {
if (this.lastMoveEventSent === event) {
return;
}
@ -1200,7 +1210,7 @@ ${escapedMessage}
* Finds the correct item to outline and outline it (if there is an item to be outlined)
* @param event
*/
private outlineItem(event: HasMovedEvent): void {
private outlineItem(event: HasPlayerMovedEvent): void {
let x = event.x;
let y = event.y;
switch (event.direction) {
@ -1221,7 +1231,7 @@ ${escapedMessage}
}
let shortestDistance: number = Infinity;
let selectedItem: ActionableItem|null = null;
let selectedItem: ActionableItem | null = null;
for (const item of this.actionableItems.values()) {
const distance = item.actionableDistance(x, y);
if (distance !== null && distance < shortestDistance) {
@ -1239,7 +1249,7 @@ ${escapedMessage}
this.outlinedItem?.selectable();
}
private doPushPlayerPosition(event: HasMovedEvent): void {
private doPushPlayerPosition(event: HasPlayerMovedEvent): void {
this.lastMoveEventSent = event;
this.lastSentTick = this.currentTick;
const camera = this.cameras.main;
@ -1249,13 +1259,14 @@ ${escapedMessage}
right: camera.scrollX + camera.width,
bottom: camera.scrollY + camera.height,
});
iframeListener.hasPlayerMoved(event);
}
/**
* @param time
* @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/
update(time: number, delta: number) : void {
update(time: number, delta: number): void {
mediaManager.updateScene();
this.currentTick = time;
if (this.CurrentPlayer.isMoving()) {
@ -1300,7 +1311,7 @@ ${escapedMessage}
}
// Let's move all users
const updatedPlayersPositions = this.playersPositionInterpolator.getUpdatedPositions(time);
updatedPlayersPositions.forEach((moveEvent: HasMovedEvent, userId: number) => {
updatedPlayersPositions.forEach((moveEvent: HasPlayerMovedEvent, userId: number) => {
this.dirty = true;
const player: RemotePlayer | undefined = this.MapPlayersByKey.get(userId);
if (player === undefined) {
@ -1327,8 +1338,8 @@ ${escapedMessage}
const currentPlayerId = this.connection?.getUserId();
this.removeAllRemotePlayers();
// load map
usersPosition.forEach((userPosition : MessageUserPositionInterface) => {
if(userPosition.userId === currentPlayerId){
usersPosition.forEach((userPosition: MessageUserPositionInterface) => {
if (userPosition.userId === currentPlayerId) {
return;
}
this.addPlayer(userPosition);
@ -1338,16 +1349,16 @@ ${escapedMessage}
/**
* Called by the connexion when a new player arrives on a map
*/
public addPlayer(addPlayerData : AddPlayerInterface) : void {
public addPlayer(addPlayerData: AddPlayerInterface): void {
this.pendingEvents.enqueue({
type: "AddPlayerEvent",
event: addPlayerData
});
}
private doAddPlayer(addPlayerData : AddPlayerInterface): void {
private doAddPlayer(addPlayerData: AddPlayerInterface): void {
//check if exist player, if exist, move position
if(this.MapPlayersByKey.has(addPlayerData.userId)){
if (this.MapPlayersByKey.has(addPlayerData.userId)) {
this.updatePlayerPosition({
userId: addPlayerData.userId,
position: addPlayerData.position
@ -1408,10 +1419,10 @@ ${escapedMessage}
}
private doUpdatePlayerPosition(message: MessageUserMovedInterface): void {
const player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId);
const player: RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId);
if (player === undefined) {
//throw new Error('Cannot find player with ID "' + message.userId +'"');
console.error('Cannot update position of player with ID "' + message.userId +'": player not found');
console.error('Cannot update position of player with ID "' + message.userId + '": player not found');
return;
}
@ -1455,7 +1466,7 @@ ${escapedMessage}
doDeleteGroup(groupId: number): void {
const group = this.groups.get(groupId);
if(!group){
if (!group) {
return;
}
group.destroy();
@ -1484,7 +1495,7 @@ ${escapedMessage}
bottom: camera.scrollY + camera.height,
});
}
private getObjectLayerData(objectName : string) : ITiledMapObject| undefined{
private getObjectLayerData(objectName: string): ITiledMapObject | undefined {
for (const layer of this.mapFile.layers) {
if (layer.type === 'objectgroup' && layer.name === 'floorLayer') {
for (const object of layer.objects) {
@ -1518,7 +1529,7 @@ ${escapedMessage}
const game = HtmlUtils.querySelectorOrFail<HTMLCanvasElement>('#game canvas');
// Let's put this in Game coordinates by applying the zoom level:
this.cameras.main.setFollowOffset((xCenter - game.offsetWidth/2) * window.devicePixelRatio / this.scale.zoom , (yCenter - game.offsetHeight/2) * window.devicePixelRatio / this.scale.zoom);
this.cameras.main.setFollowOffset((xCenter - game.offsetWidth / 2) * window.devicePixelRatio / this.scale.zoom, (yCenter - game.offsetHeight / 2) * window.devicePixelRatio / this.scale.zoom);
}
public onCenterChange(): void {
@ -1527,16 +1538,16 @@ ${escapedMessage}
public startJitsi(roomName: string, jwt?: string): void {
const allProps = this.gameMap.getCurrentProperties();
const jitsiConfig = this.safeParseJSONstring(allProps.get("jitsiConfig") as string|undefined, 'jitsiConfig');
const jitsiInterfaceConfig = this.safeParseJSONstring(allProps.get("jitsiInterfaceConfig") as string|undefined, 'jitsiInterfaceConfig');
const jitsiUrl = allProps.get("jitsiUrl") as string|undefined;
const jitsiConfig = this.safeParseJSONstring(allProps.get("jitsiConfig") as string | undefined, 'jitsiConfig');
const jitsiInterfaceConfig = this.safeParseJSONstring(allProps.get("jitsiInterfaceConfig") as string | undefined, 'jitsiInterfaceConfig');
const jitsiUrl = allProps.get("jitsiUrl") as string | undefined;
jitsiFactory.start(roomName, this.playerName, jwt, jitsiConfig, jitsiInterfaceConfig, jitsiUrl);
this.connection?.setSilent(true);
mediaManager.hideGameOverlay();
//permit to stop jitsi when user close iframe
mediaManager.addTriggerCloseJitsiFrameButton('close-jisi',() => {
mediaManager.addTriggerCloseJitsiFrameButton('close-jisi', () => {
this.stopJitsi();
});
@ -1553,7 +1564,7 @@ ${escapedMessage}
}
//todo: put this into an 'orchestrator' scene (EntryScene?)
private bannedUser(){
private bannedUser() {
this.cleanupClosingScene();
this.userInputManager.disableControls();
this.scene.start(ErrorSceneName, {
@ -1564,22 +1575,22 @@ ${escapedMessage}
}
//todo: put this into an 'orchestrator' scene (EntryScene?)
private showWorldFullError(message: string|null): void {
private showWorldFullError(message: string | null): void {
this.cleanupClosingScene();
this.scene.stop(ReconnectingSceneName);
this.scene.remove(ReconnectingSceneName);
this.userInputManager.disableControls();
//FIX ME to use status code
if(message == undefined){
if (message == undefined) {
this.scene.start(ErrorSceneName, {
title: 'Connection rejected',
subTitle: 'The world you are trying to join is full. Try again later.',
message: 'If you want more information, you may contact us at: workadventure@thecodingmachine.com'
});
}else{
} else {
this.scene.start(ErrorSceneName, {
title: 'Connection rejected',
subTitle: 'You cannot join the World. Try again later. \n\r \n\r Error: '+message+'.',
subTitle: 'You cannot join the World. Try again later. \n\r \n\r Error: ' + message + '.',
message: 'If you want more information, you may contact administrator or contact us at: workadventure@thecodingmachine.com'
});
}

View file

@ -1,9 +1,10 @@
import type {HasMovedEvent} from "./GameManager";
import {MAX_EXTRAPOLATION_TIME} from "../../Enum/EnvironmentVariable";
import type {PositionInterface} from "../../Connexion/ConnexionModels";
import { MAX_EXTRAPOLATION_TIME } from "../../Enum/EnvironmentVariable";
import type { PositionInterface } from "../../Connexion/ConnexionModels";
import type { HasPlayerMovedEvent } from '../../Api/Events/HasPlayerMovedEvent';
export class PlayerMovement {
public constructor(private startPosition: PositionInterface, private startTick: number, private endPosition: HasMovedEvent, private endTick: number) {
public constructor(private startPosition: PositionInterface, private startTick: number, private endPosition: HasPlayerMovedEvent, private endTick: number) {
}
public isOutdated(tick: number): boolean {
@ -17,7 +18,7 @@ export class PlayerMovement {
return tick > this.endTick + MAX_EXTRAPOLATION_TIME;
}
public getPosition(tick: number): HasMovedEvent {
public getPosition(tick: number): HasPlayerMovedEvent {
// Special case: end position reached and end position is not moving
if (tick >= this.endTick && this.endPosition.moving === false) {
//console.log('Movement finished ', this.endPosition)

View file

@ -2,13 +2,13 @@
* This class is in charge of computing the position of all players.
* Player movement is delayed by 200ms so position depends on ticks.
*/
import type {PlayerMovement} from "./PlayerMovement";
import type {HasMovedEvent} from "./GameManager";
import type { HasPlayerMovedEvent } from '../../Api/Events/HasPlayerMovedEvent';
import type { PlayerMovement } from "./PlayerMovement";
export class PlayersPositionInterpolator {
playerMovements: Map<number, PlayerMovement> = new Map<number, PlayerMovement>();
updatePlayerPosition(userId: number, playerMovement: PlayerMovement) : void {
updatePlayerPosition(userId: number, playerMovement: PlayerMovement): void {
this.playerMovements.set(userId, playerMovement);
}
@ -16,8 +16,8 @@ export class PlayersPositionInterpolator {
this.playerMovements.delete(userId);
}
getUpdatedPositions(tick: number) : Map<number, HasMovedEvent> {
const positions = new Map<number, HasMovedEvent>();
getUpdatedPositions(tick: number): Map<number, HasPlayerMovedEvent> {
const positions = new Map<number, HasPlayerMovedEvent>();
this.playerMovements.forEach((playerMovement: PlayerMovement, userId: number) => {
if (playerMovement.isOutdated(tick)) {
//console.log("outdated")