Merge branch 'develop' into player-report

# Conflicts:
#	back/src/Controller/IoSocketController.ts
#	front/src/Phaser/Game/GameScene.ts
#	front/src/index.ts
#	messages/messages.proto
This commit is contained in:
Gregoire Parant 2020-10-13 20:39:29 +02:00
commit 05a1ea8469
28 changed files with 1189 additions and 975 deletions

View file

@ -6,12 +6,6 @@
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Include stylesheet -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-10196481-11"></script>
<script>

View file

@ -6,6 +6,7 @@
"devDependencies": {
"@types/google-protobuf": "^3.7.3",
"@types/jasmine": "^3.5.10",
"@types/quill": "^1.3.7",
"@typescript-eslint/eslint-plugin": "^2.26.0",
"@typescript-eslint/parser": "^2.26.0",
"eslint": "^6.8.0",
@ -20,14 +21,14 @@
"webpack-merge": "^4.2.2"
},
"dependencies": {
"@types/axios": "^0.14.0",
"@types/simple-peer": "^9.6.0",
"@types/socket.io-client": "^1.4.32",
"axios": "^0.20.0",
"generic-type-guard": "^3.2.0",
"google-protobuf": "^3.13.0",
"phaser": "^3.22.0",
"queue-typescript": "^1.0.1",
"quill": "1.3.7",
"quill": "^1.3.7",
"simple-peer": "^9.6.2",
"socket.io-client": "^2.3.0",
"webpack-require-http": "^0.4.3"

View file

@ -1,7 +1,3 @@
import {GameScene} from "../Phaser/Game/GameScene";
const Quill = require("quill");
import {HtmlUtils} from "../WebRtc/HtmlUtils";
import {UserInputManager} from "../Phaser/UserInput/UserInputManager";
import {RoomConnection} from "../Connexion/RoomConnection";
@ -10,7 +6,6 @@ import {PlayGlobalMessageInterface} from "../Connexion/ConnexionModels";
export const CLASS_CONSOLE_MESSAGE = 'main-console';
export const INPUT_CONSOLE_MESSAGE = 'input-send-text';
export const UPLOAD_CONSOLE_MESSAGE = 'input-upload-music';
export const BUTTON_CONSOLE_SEND = 'button-send';
export const INPUT_TYPE_CONSOLE = 'input-type';
export const AUDIO_TYPE = 'audio';
@ -26,6 +21,7 @@ export class ConsoleGlobalMessageManager {
private buttonMainConsole: HTMLDivElement;
private activeConsole: boolean = false;
private userInputManager!: UserInputManager;
private static cssLoaded: boolean = false;
constructor(private Connection: RoomConnection, userInputManager : UserInputManager) {
this.buttonMainConsole = document.createElement('div');
@ -123,24 +119,30 @@ export class ConsoleGlobalMessageManager {
section.appendChild(buttonDiv);
this.divMainConsole.appendChild(section);
//TODO refactor
setTimeout(() => {
(async () => {
// Start loading CSS
const cssPromise = ConsoleGlobalMessageManager.loadCss();
// Import quill
const Quill:any = await import("quill"); // eslint-disable-line @typescript-eslint/no-explicit-any
// Wait for CSS to be loaded
await cssPromise;
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{'header': 1}, {'header': 2}], // custom button values
[{'list': 'ordered'}, {'list': 'bullet'}],
[{'script': 'sub'}, {'script': 'super'}], // superscript/subscript
[{'indent': '-1'}, {'indent': '+1'}], // outdent/indent
[{'direction': 'rtl'}], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{'size': ['small', false, 'large', 'huge']}], // custom dropdown
[{'header': [1, 2, 3, 4, 5, 6, false]}],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
[{'color': []}, {'background': []}], // dropdown with defaults from theme
[{'font': []}],
[{'align': []}],
['clean'],
@ -154,8 +156,28 @@ export class ConsoleGlobalMessageManager {
toolbar: toolbarOptions
},
});
})();
}
}, 1000);
private static loadCss(): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (ConsoleGlobalMessageManager.cssLoaded) {
resolve();
return;
}
const fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", "https://cdn.quilljs.com/1.3.7/quill.snow.css");
document.getElementsByTagName("head")[0].appendChild(fileref);
ConsoleGlobalMessageManager.cssLoaded = true;
fileref.onload = () => {
resolve();
}
fileref.onerror = () => {
reject();
}
});
}
createUploadAudioPart(){

View file

@ -1,43 +1,78 @@
import Axios from "axios";
import {API_URL} from "../Enum/EnvironmentVariable";
import {RoomConnection} from "./RoomConnection";
import {PositionInterface, ViewportInterface} from "./ConnexionModels";
import {GameConnexionTypes, urlManager} from "../Url/UrlManager";
import {localUserStore} from "./LocalUserStore";
import {LocalUser} from "./LocalUser";
import {Room} from "./Room";
interface LoginApiData {
authToken: string
userUuid: string
mapUrlStart: string
newUrl: string
}
const URL_ROOM_STARTED = '/Floor0/floor0.json';
class ConnectionManager {
private initPromise!: Promise<LoginApiData>;
private mapUrlStart: string|null = null;
private localUser!:LocalUser;
private authToken:string|null = null;
private userUuid: string|null = null;
/**
* Tries to login to the node server and return the starting map url to be loaded
*/
public async initGameConnexion(): Promise<Room> {
public async init(): Promise<void> {
const match = /\/register\/(.+)/.exec(window.location.toString());
const organizationMemberToken = match ? match[1] : null;
this.initPromise = Axios.post(`${API_URL}/login`, {organizationMemberToken}).then(res => res.data);
const data = await this.initPromise
this.authToken = data.authToken;
this.userUuid = data.userUuid;
this.mapUrlStart = data.mapUrlStart;
const newUrl = data.newUrl;
const connexionType = urlManager.getGameConnexionType();
if(connexionType === GameConnexionTypes.register) {
const organizationMemberToken = urlManager.getOrganizationToken();
const data = await Axios.post(`${API_URL}/register`, {organizationMemberToken}).then(res => res.data);
this.localUser = new LocalUser(data.userUuid, data.authToken);
localUserStore.saveUser(this.localUser);
if (newUrl) {
history.pushState({}, '', newUrl);
const organizationSlug = data.organizationSlug;
const worldSlug = data.worldSlug;
const roomSlug = data.roomSlug;
urlManager.editUrlForRoom(roomSlug, organizationSlug, worldSlug);
const room = new Room(window.location.pathname);
return Promise.resolve(room);
} else if (connexionType === GameConnexionTypes.anonymous || connexionType === GameConnexionTypes.empty) {
const localUser = localUserStore.getLocalUser();
if (localUser && localUser.jwtToken && localUser.uuid) {
this.localUser = localUser
} else {
const data = await Axios.post(`${API_URL}/anonymLogin`).then(res => res.data);
this.localUser = new LocalUser(data.userUuid, data.authToken);
localUserStore.saveUser(this.localUser);
}
let roomId: string
if (connexionType === GameConnexionTypes.empty) {
const defaultMapUrl = window.location.host.replace('play.', 'maps.') + URL_ROOM_STARTED;
roomId = urlManager.editUrlForRoom(defaultMapUrl, null, null);
} else {
roomId = window.location.pathname;
}
const room = new Room(roomId);
return Promise.resolve(room);
} else if (connexionType == GameConnexionTypes.organization) {
const localUser = localUserStore.getLocalUser();
if (localUser) {
this.localUser = localUser
const room = new Room(window.location.pathname);
return Promise.resolve(room);
} else {
//todo: find some kind of fallback?
return Promise.reject('Could not find a user in localstorage');
}
}
return Promise.reject('Invalid URL');
}
public initBenchmark(): void {
this.authToken = 'test';
this.localUser = new LocalUser('', 'test');
}
public connectToRoomSocket(): Promise<RoomConnection> {
public connectToRoomSocket(roomId: string, name: string, characterLayers: string[], position: PositionInterface, viewport: ViewportInterface): Promise<RoomConnection> {
return new Promise<RoomConnection>((resolve, reject) => {
const connection = new RoomConnection(this.authToken as string);
const connection = new RoomConnection(this.localUser.jwtToken, roomId, name, characterLayers, position, viewport);
connection.onConnectError((error: object) => {
console.log('An error occurred while connecting to socket server. Retrying');
reject(error);
@ -50,20 +85,11 @@ class ConnectionManager {
return new Promise<RoomConnection>((resolve, reject) => {
setTimeout(() => {
//todo: allow a way to break recurrsion?
this.connectToRoomSocket().then((connection) => resolve(connection));
this.connectToRoomSocket(roomId, name, characterLayers, position, viewport).then((connection) => resolve(connection));
}, 4000 + Math.floor(Math.random() * 2000) );
});
});
}
public getMapUrlStart(): Promise<string> {
return this.initPromise.then(() => {
if (!this.mapUrlStart) {
throw new Error('No map url set!');
}
return this.mapUrlStart;
})
}
}
export const connectionManager = new ConnectionManager();

View file

@ -6,6 +6,7 @@ export enum EventMessage{
WEBRTC_SIGNAL = "webrtc-signal",
WEBRTC_SCREEN_SHARING_SIGNAL = "webrtc-screen-sharing-signal",
WEBRTC_START = "webrtc-start",
START_ROOM = "start-room", // From server to client: list of all room users/groups/items
JOIN_ROOM = "join-room", // bi-directional
USER_POSITION = "user-position", // From client to server
USER_MOVED = "user-moved", // From server to client

View file

@ -0,0 +1,9 @@
export class LocalUser {
public uuid: string;
public jwtToken: string;
constructor(uuid:string, jwtToken: string) {
this.uuid = uuid;
this.jwtToken = jwtToken;
}
}

View file

@ -0,0 +1,16 @@
import {LocalUser} from "./LocalUser";
class LocalUserStore {
saveUser(localUser: LocalUser) {
localStorage.setItem('localUser', JSON.stringify(localUser));
}
getLocalUser(): LocalUser|null {
const data = localStorage.getItem('localUser');
return data ? JSON.parse(data) : null;
}
}
export const localUserStore = new LocalUserStore();

View file

@ -0,0 +1,91 @@
import Axios from "axios";
import {API_URL} from "../Enum/EnvironmentVariable";
export class Room {
public readonly id: string;
public readonly isPublic: boolean;
private mapUrl: string|undefined;
private instance: string|undefined;
constructor(id: string) {
if (id.startsWith('/')) {
id = id.substr(1);
}
this.id = id;
if (id.startsWith('_/')) {
this.isPublic = true;
} else if (id.startsWith('@/')) {
this.isPublic = false;
} else {
throw new Error('Invalid room ID');
}
}
public async getMapUrl(): Promise<string> {
return new Promise<string>((resolve, reject) => {
if (this.mapUrl !== undefined) {
resolve(this.mapUrl);
return;
}
if (this.isPublic) {
const match = /_\/[^/]+\/(.+)/.exec(this.id);
if (!match) throw new Error('Could not extract url from "'+this.id+'"');
this.mapUrl = window.location.protocol+'//'+match[1];
resolve(this.mapUrl);
return;
} else {
// We have a private ID, we need to query the map URL from the server.
const urlParts = this.parsePrivateUrl(this.id);
Axios.get(`${API_URL}/map`, {
params: urlParts
}).then(({data}) => {
console.log('Map ', this.id, ' resolves to URL ', data.mapUrl);
resolve(data.mapUrl);
return;
});
}
});
}
/**
* Instance name is:
* - In a public URL: the second part of the URL ( _/[instance]/map.json)
* - In a private URL: [organizationId/worldId]
*/
public getInstance(): string {
if (this.instance !== undefined) {
return this.instance;
}
if (this.isPublic) {
const match = /_\/([^/]+)\/.+/.exec(this.id);
if (!match) throw new Error('Could not extract instance from "'+this.id+'"');
this.instance = match[1];
return this.instance;
} else {
const match = /_\/([^/]+)\/([^/]+)\/.+/.exec(this.id);
if (!match) throw new Error('Could not extract instance from "'+this.id+'"');
this.instance = match[1]+'/'+match[2];
return this.instance;
}
}
private parsePrivateUrl(url: string): { organizationSlug: string, worldSlug: string, roomSlug?: string } {
const regex = /@\/([^/]+)\/([^/]+)(?:\/([^/]*))?/gm;
const match = regex.exec(url);
if (!match) {
throw new Error('Invalid URL '+url);
}
const results: { organizationSlug: string, worldSlug: string, roomSlug?: string } = {
organizationSlug: match[1],
worldSlug: match[2],
}
if (match[3] !== undefined) {
results.roomSlug = match[3];
}
return results;
}
}

View file

@ -6,12 +6,11 @@ import {
GroupDeleteMessage,
GroupUpdateMessage,
ItemEventMessage,
JoinRoomMessage, PlayGlobalMessage,
PlayGlobalMessage,
PositionMessage,
RoomJoinedMessage,
ServerToClientMessage,
SetPlayerDetailsMessage,
SetUserIdMessage,
SilentMessage, StopGlobalMessage,
UserJoinedMessage,
UserLeftMessage,
@ -32,7 +31,7 @@ import {ProtobufClientUtils} from "../Network/ProtobufClientUtils";
import {
EventMessage,
GroupCreatedUpdatedMessageInterface, ItemEventMessageInterface,
MessageUserJoined, PlayGlobalMessageInterface,
MessageUserJoined, PlayGlobalMessageInterface, PositionInterface,
RoomJoinedMessageInterface,
ViewportInterface, WebRtcDisconnectMessageInterface,
WebRtcSignalReceivedMessageInterface,
@ -51,9 +50,26 @@ export class RoomConnection implements RoomConnection {
RoomConnection.websocketFactory = websocketFactory;
}
public constructor(token: string) {
/**
*
* @param token A JWT token containing the UUID of the user
* @param roomId The ID of the room in the form "_/[instance]/[map_url]" or "@/[org]/[event]/[map]"
*/
public constructor(token: string|null, roomId: string, name: string, characterLayers: string[], position: PositionInterface, viewport: ViewportInterface) {
let url = API_URL.replace('http://', 'ws://').replace('https://', 'wss://');
url += '?token='+token;
url += '/room';
url += '?roomId='+(roomId ?encodeURIComponent(roomId):'');
url += '&token='+(token ?encodeURIComponent(token):'');
url += '&name='+encodeURIComponent(name);
for (const layer of characterLayers) {
url += '&characterLayers='+encodeURIComponent(layer);
}
url += '&x='+Math.floor(position.x);
url += '&y='+Math.floor(position.y);
url += '&top='+Math.floor(viewport.top);
url += '&bottom='+Math.floor(viewport.bottom);
url += '&left='+Math.floor(viewport.left);
url += '&right='+Math.floor(viewport.right);
if (RoomConnection.websocketFactory) {
this.socket = RoomConnection.websocketFactory(url);
@ -109,13 +125,13 @@ export class RoomConnection implements RoomConnection {
items[item.getItemid()] = JSON.parse(item.getStatejson());
}
this.resolveJoinRoom({
this.userId = roomJoinedMessage.getCurrentuserid();
this.dispatch(EventMessage.START_ROOM, {
users,
groups,
items
})
} else if (message.hasSetuseridmessage()) {
this.userId = (message.getSetuseridmessage() as SetUserIdMessage).getUserid();
});
} else if (message.hasErrormessage()) {
console.error(EventMessage.MESSAGE_ERROR, message.getErrormessage()?.getMessage());
} else if (message.hasWebrtcsignaltoclientmessage()) {
@ -165,29 +181,6 @@ export class RoomConnection implements RoomConnection {
this.closed = true;
}
private resolveJoinRoom!: (value?: (RoomJoinedMessageInterface | PromiseLike<RoomJoinedMessageInterface> | undefined)) => void;
public joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean, viewport: ViewportInterface): Promise<RoomJoinedMessageInterface> {
const promise = new Promise<RoomJoinedMessageInterface>((resolve, reject) => {
this.resolveJoinRoom = resolve;
const positionMessage = this.toPositionMessage(startX, startY, direction, moving);
const viewportMessage = this.toViewportMessage(viewport);
const joinRoomMessage = new JoinRoomMessage();
joinRoomMessage.setRoomid(roomId);
joinRoomMessage.setPosition(positionMessage);
joinRoomMessage.setViewport(viewportMessage);
//console.log('Sending position ', positionMessage.getX(), positionMessage.getY());
const clientToServerMessage = new ClientToServerMessage();
clientToServerMessage.setJoinroommessage(joinRoomMessage);
this.socket.send(clientToServerMessage.serializeBinary().buffer);
})
return promise;
}
private toPositionMessage(x : number, y : number, direction : string, moving: boolean): PositionMessage {
const positionMessage = new PositionMessage();
positionMessage.setX(Math.floor(x));
@ -343,6 +336,13 @@ export class RoomConnection implements RoomConnection {
this.socket.addEventListener('open', callback)
}
/**
* Triggered when we receive all the details of a room (users, groups, ...)
*/
public onStartRoom(callback: (event: RoomJoinedMessageInterface) => void): void {
this.onMessage(EventMessage.START_ROOM, callback);
}
public sendWebrtcSignal(signal: unknown, receiverId: number) {
const webRtcSignal = new WebRtcSignalToServerMessage();
webRtcSignal.setReceiverid(receiverId);

View file

@ -1,10 +1,7 @@
import {GameScene} from "./GameScene";
import {
StartMapInterface
} from "../../Connexion/ConnexionModels";
import Axios from "axios";
import {API_URL} from "../../Enum/EnvironmentVariable";
import {connectionManager} from "../../Connexion/ConnectionManager";
import {Room} from "../../Connexion/Room";
import {FourOFourSceneName} from "../Reconnecting/FourOFourScene";
export interface HasMovedEvent {
direction: string;
@ -16,6 +13,12 @@ export interface HasMovedEvent {
export class GameManager {
private playerName!: string;
private characterLayers!: string[];
private startRoom!:Room;
public async init(scenePlugin: Phaser.Scenes.ScenePlugin) {
this.startRoom = await connectionManager.initGameConnexion();
await this.loadMap(this.startRoom, scenePlugin);
}
public setPlayerName(name: string): void {
this.playerName = name;
@ -29,15 +32,6 @@ export class GameManager {
this.characterLayers = layers;
}
loadStartMap() : Promise<StartMapInterface> {
return connectionManager.getMapUrlStart().then(mapUrlStart => {
return {
mapUrlStart: mapUrlStart,
startInstance: "global", //todo: is this property still usefull?
}
});
}
getPlayerName(): string {
return this.playerName;
}
@ -46,15 +40,31 @@ export class GameManager {
return this.characterLayers;
}
loadMap(mapUrl: string, scene: Phaser.Scenes.ScenePlugin, instance: string): string {
const sceneKey = GameScene.getMapKeyByUrl(mapUrl);
const gameIndex = scene.getIndex(sceneKey);
public async loadMap(room: Room, scenePlugin: Phaser.Scenes.ScenePlugin): Promise<void> {
const roomID = room.id;
const mapUrl = await room.getMapUrl();
console.log('Loading map '+roomID+' at url '+mapUrl);
const gameIndex = scenePlugin.getIndex(mapUrl);
if(gameIndex === -1){
const game : Phaser.Scene = GameScene.createFromUrl(mapUrl, instance);
scene.add(sceneKey, game, false);
const game : Phaser.Scene = GameScene.createFromUrl(room, mapUrl);
console.log('Adding scene '+mapUrl);
scenePlugin.add(mapUrl, game, false);
}
return sceneKey;
}
public getMapKeyByUrl(mapUrlStart: string) : string {
// FIXME: the key should be computed from the full URL of the map.
const startPos = mapUrlStart.indexOf('://')+3;
const endPos = mapUrlStart.indexOf(".json");
return mapUrlStart.substring(startPos, endPos);
}
public async goToStartingMap(scenePlugin: Phaser.Scenes.ScenePlugin) {
const url = await this.startRoom.getMapUrl();
console.log('Starting scene '+url);
scenePlugin.start(url, {startLayerName: 'global'});
}
}

View file

@ -45,6 +45,7 @@ import {RoomConnection} from "../../Connexion/RoomConnection";
import {GlobalMessageManager} from "../../Administration/GlobalMessageManager";
import {ConsoleGlobalMessageManager} from "../../Administration/ConsoleGlobalMessageManager";
import {ResizableScene} from "../Login/ResizableScene";
import {Room} from "../../Connexion/Room";
export enum Textures {
@ -107,7 +108,6 @@ export class GameScene extends ResizableScene implements CenterListener {
private simplePeer!: SimplePeer;
private GlobalMessageManager!: GlobalMessageManager;
private ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager;
private connectionPromise!: Promise<RoomConnection>
private connectionAnswerPromise: Promise<RoomJoinedMessageInterface>;
private connectionAnswerPromiseResolve!: (value?: RoomJoinedMessageInterface | PromiseLike<RoomJoinedMessageInterface>) => void;
// A promise that will resolve when the "create" method is called (signaling loading is ended)
@ -138,27 +138,27 @@ export class GameScene extends ResizableScene implements CenterListener {
private outlinedItem: ActionableItem|null = null;
private userInputManager!: UserInputManager;
static createFromUrl(mapUrlFile: string, instance: string, key: string|null = null): GameScene {
const mapKey = GameScene.getMapKeyByUrl(mapUrlFile);
if (key === null) {
key = mapKey;
static createFromUrl(room: Room, mapUrlFile: string, gameSceneKey: string|null = null): GameScene {
// We use the map URL as a key
if (gameSceneKey === null) {
gameSceneKey = mapUrlFile;
}
return new GameScene(mapKey, mapUrlFile, instance, key);
return new GameScene(room, mapUrlFile, gameSceneKey);
}
constructor(MapKey : string, MapUrlFile: string, instance: string, key: string) {
constructor(private room: Room, MapUrlFile: string, gameSceneKey: string) {
super({
key: key
key: gameSceneKey
});
this.GameManager = gameManager;
this.Terrains = [];
this.groups = new Map<number, Sprite>();
this.instance = instance;
this.instance = room.getInstance();
this.MapKey = MapKey;
this.MapKey = MapUrlFile;
this.MapUrlFile = MapUrlFile;
this.RoomId = this.instance + '__' + MapKey;
this.RoomId = room.id;
this.createPromise = new Promise<void>((resolve, reject): void => {
this.createPromiseResolve = resolve;
@ -193,110 +193,6 @@ export class GameScene extends ResizableScene implements CenterListener {
loadObject(this.load);
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
this.connectionPromise = connectionManager.connectToRoomSocket().then((connection : RoomConnection) => {
this.connection = connection;
this.connection.emitPlayerDetailsMessage(gameManager.getPlayerName(), gameManager.getCharacterSelected())
connection.onUserJoins((message: MessageUserJoined) => {
const userMessage: AddPlayerInterface = {
userId: message.userId,
characterLayers: message.characterLayers,
name: message.name,
position: message.position
}
this.addPlayer(userMessage);
});
connection.onUserMoved((message: UserMovedMessage) => {
const position = message.getPosition();
if (position === undefined) {
throw new Error('Position missing from UserMovedMessage');
}
//console.log('Received position ', position.getX(), position.getY(), "from user", message.getUserid());
const messageUserMoved: MessageUserMovedInterface = {
userId: message.getUserid(),
position: ProtobufClientUtils.toPointInterface(position)
}
this.updatePlayerPosition(messageUserMoved);
});
connection.onUserLeft((userId: number) => {
this.removePlayer(userId);
});
connection.onGroupUpdatedOrCreated((groupPositionMessage: GroupCreatedUpdatedMessageInterface) => {
this.shareGroupPosition(groupPositionMessage);
})
connection.onGroupDeleted((groupId: number) => {
try {
this.deleteGroup(groupId);
} catch (e) {
console.error(e);
}
})
connection.onServerDisconnected(() => {
console.log('Player disconnected from server. Reloading scene.');
this.simplePeer.closeAllConnections();
this.simplePeer.unregister();
const key = 'somekey'+Math.round(Math.random()*10000);
const game : Phaser.Scene = GameScene.createFromUrl(this.MapUrlFile, this.instance, key);
this.scene.add(key, game, true,
{
initPosition: {
x: this.CurrentPlayer.x,
y: this.CurrentPlayer.y
}
});
this.scene.stop(this.scene.key);
this.scene.remove(this.scene.key);
})
connection.onActionableEvent((message => {
const item = this.actionableItems.get(message.itemId);
if (item === undefined) {
console.warn('Received an event about object "'+message.itemId+'" but cannot find this item on the map.');
return;
}
item.fire(message.event, message.state, message.parameters);
}));
connection.receiveTeleportMessage((map: string) => {
//TODO
console.log('receiveTeleportMessage', map);
})
// When connection is performed, let's connect SimplePeer
this.simplePeer = new SimplePeer(this.connection);
this.GlobalMessageManager = new GlobalMessageManager(this.connection);
const self = this;
this.simplePeer.registerPeerConnectionListener({
onConnect(user: UserSimplePeerInterface) {
self.presentationModeSprite.setVisible(true);
self.chatModeSprite.setVisible(true);
},
onDisconnect(userId: number) {
if (self.simplePeer.getNbConnections() === 0) {
self.presentationModeSprite.setVisible(false);
self.chatModeSprite.setVisible(false);
}
}
})
this.scene.wake();
this.scene.sleep(ReconnectingSceneName);
return connection;
});
}
// FIXME: we need to put a "unknown" instead of a "any" and validate the structure of the JSON we are receiving.
@ -422,7 +318,7 @@ export class GameScene extends ResizableScene implements CenterListener {
});
//permit to set bound collision
this.physics.world.setBounds(0,0, this.Map.widthInPixels, this.Map.heightInPixels);
this.physics.world.setBounds(0, 0, this.Map.widthInPixels, this.Map.heightInPixels);
//add layer on map
this.Layers = new Array<Phaser.Tilemaps.StaticTilemapLayer>();
@ -483,7 +379,7 @@ export class GameScene extends ResizableScene implements CenterListener {
this.EventToClickOnTile();
//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
this.userInputManager = new UserInputManager(this);
@ -499,7 +395,7 @@ export class GameScene extends ResizableScene implements CenterListener {
// Let's generate the circle for the group delimiter
const circleElement = Object.values(this.textures.list).find((object: Texture) => object.key === 'circleSprite');
if(circleElement) {
if (circleElement) {
this.textures.remove('circleSprite');
}
this.circleTexture = this.textures.createCanvas('circleSprite', 96, 96);
@ -511,14 +407,6 @@ export class GameScene extends ResizableScene implements CenterListener {
context.stroke();
this.circleTexture.refresh();
// Let's alter browser history
const url = new URL(this.MapUrlFile);
let path = '/_/'+this.instance+'/'+url.host+url.pathname;
if (this.startLayerName) {
path += '#'+this.startLayerName;
}
window.history.pushState({}, 'WorkAdventure', path);
// Let's pause the scene if the connection is not established yet
if (this.connection === undefined) {
// Let's wait 0.5 seconds before printing the "connecting" screen to avoid blinking
@ -532,7 +420,7 @@ export class GameScene extends ResizableScene implements CenterListener {
this.createPromiseResolve();
this.userInputManager.spaceEvent( () => {
this.userInputManager.spaceEvent(() => {
this.outlinedItem?.activate();
});
@ -607,8 +495,131 @@ export class GameScene extends ResizableScene implements CenterListener {
}
});
//lisen event to report user
this.onReportUser();
const camera = this.cameras.main;
connectionManager.connectToRoomSocket(
this.RoomId,
gameManager.getPlayerName(),
gameManager.getCharacterSelected(),
{
x: this.startX,
y: this.startY
},
{
left: camera.scrollX,
top: camera.scrollY,
right: camera.scrollX + camera.width,
bottom: camera.scrollY + camera.height,
}).then((connection: RoomConnection) => {
this.connection = connection;
//this.connection.emitPlayerDetailsMessage(gameManager.getPlayerName(), gameManager.getCharacterSelected())
connection.onStartRoom((roomJoinedMessage: RoomJoinedMessageInterface) => {
this.initUsersPosition(roomJoinedMessage.users);
this.connectionAnswerPromiseResolve(roomJoinedMessage);
});
connection.onUserJoins((message: MessageUserJoined) => {
const userMessage: AddPlayerInterface = {
userId: message.userId,
characterLayers: message.characterLayers,
name: message.name,
position: message.position
}
this.addPlayer(userMessage);
});
connection.onUserMoved((message: UserMovedMessage) => {
const position = message.getPosition();
if (position === undefined) {
throw new Error('Position missing from UserMovedMessage');
}
//console.log('Received position ', position.getX(), position.getY(), "from user", message.getUserid());
const messageUserMoved: MessageUserMovedInterface = {
userId: message.getUserid(),
position: ProtobufClientUtils.toPointInterface(position)
}
this.updatePlayerPosition(messageUserMoved);
});
connection.onUserLeft((userId: number) => {
this.removePlayer(userId);
});
connection.onGroupUpdatedOrCreated((groupPositionMessage: GroupCreatedUpdatedMessageInterface) => {
this.shareGroupPosition(groupPositionMessage);
})
connection.onGroupDeleted((groupId: number) => {
try {
this.deleteGroup(groupId);
} catch (e) {
console.error(e);
}
})
connection.onServerDisconnected(() => {
console.log('Player disconnected from server. Reloading scene.');
this.simplePeer.closeAllConnections();
this.simplePeer.unregister();
const gameSceneKey = 'somekey' + Math.round(Math.random() * 10000);
const game: Phaser.Scene = GameScene.createFromUrl(this.room, this.MapUrlFile, gameSceneKey);
this.scene.add(gameSceneKey, game, true,
{
initPosition: {
x: this.CurrentPlayer.x,
y: this.CurrentPlayer.y
}
});
this.scene.stop(this.scene.key);
this.scene.remove(this.scene.key);
})
connection.onActionableEvent((message => {
const item = this.actionableItems.get(message.itemId);
if (item === undefined) {
console.warn('Received an event about object "' + message.itemId + '" but cannot find this item on the map.');
return;
}
item.fire(message.event, message.state, message.parameters);
}));
// When connection is performed, let's connect SimplePeer
this.simplePeer = new SimplePeer(this.connection);
this.GlobalMessageManager = new GlobalMessageManager(this.connection);
const self = this;
this.simplePeer.registerPeerConnectionListener({
onConnect(user: UserSimplePeerInterface) {
self.presentationModeSprite.setVisible(true);
self.chatModeSprite.setVisible(true);
},
onDisconnect(userId: number) {
if (self.simplePeer.getNbConnections() === 0) {
self.presentationModeSprite.setVisible(false);
self.chatModeSprite.setVisible(false);
}
}
})
//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.gameMap.setPosition(event.x, event.y);
})
this.scene.wake();
this.scene.sleep(ReconnectingSceneName);
return connection;
});
}
private switchLayoutMode(): void {
@ -655,6 +666,7 @@ export class GameScene extends ResizableScene implements CenterListener {
* @param tileWidth
* @param tileHeight
*/
//todo: push that into the gameManager
private loadNextGame(layer: ITiledMapLayer, mapWidth: number, tileWidth: number, tileHeight: number){
const exitSceneUrl = this.getExitSceneUrl(layer);
if (exitSceneUrl === undefined) {
@ -665,9 +677,20 @@ export class GameScene extends ResizableScene implements CenterListener {
instance = this.instance;
}
console.log('existSceneUrl', exitSceneUrl);
console.log('existSceneInstance', instance);
// TODO: eventually compute a relative URL
// TODO: handle /@/ URL CASES!
const absoluteExitSceneUrl = new URL(exitSceneUrl, this.MapUrlFile).href;
const exitSceneKey = gameManager.loadMap(absoluteExitSceneUrl, this.scene, instance);
const absoluteExitSceneUrlWithoutProtocol = absoluteExitSceneUrl.toString().substr(absoluteExitSceneUrl.toString().indexOf('://')+3);
const roomId = '_/'+instance+'/'+absoluteExitSceneUrlWithoutProtocol;
console.log("Foo", instance, absoluteExitSceneUrlWithoutProtocol);
const room = new Room(roomId);
gameManager.loadMap(room, this.scene);
const exitSceneKey = roomId;
const tiles : number[] = layer.data as number[];
for (let key=0; key < tiles.length; key++) {
@ -688,10 +711,12 @@ export class GameScene extends ResizableScene implements CenterListener {
if (this.PositionNextScene[y] === undefined) {
this.PositionNextScene[y] = new Array<{key: string, hash: string}>();
}
this.PositionNextScene[y][x] = {
key: exitSceneKey,
hash
}
room.getMapUrl().then((url: string) => {
this.PositionNextScene[y][x] = {
key: url,
hash
}
})
}
}
@ -754,14 +779,6 @@ export class GameScene extends ResizableScene implements CenterListener {
});
}
createCollisionObject(){
/*this.Objects.forEach((Object : Phaser.Physics.Arcade.Sprite) => {
this.physics.add.collider(this.CurrentPlayer, Object, (object1, object2) => {
this.CurrentPlayer.say("Collision with object : " + (object2 as Phaser.Physics.Arcade.Sprite).texture.key)
});
})*/
}
createCurrentPlayer(){
//initialise player
//TODO create animation moving between exit and start
@ -778,33 +795,6 @@ export class GameScene extends ResizableScene implements CenterListener {
//create collision
this.createCollisionWithPlayer();
this.createCollisionObject();
//join room
this.connectionPromise.then((connection: RoomConnection) => {
const camera = this.cameras.main;
connection.joinARoom(this.RoomId,
this.startX,
this.startY,
PlayerAnimationNames.WalkDown,
false, {
left: camera.scrollX,
top: camera.scrollY,
right: camera.scrollX + camera.width,
bottom: camera.scrollY + camera.height,
}).then((roomJoinedMessage: RoomJoinedMessageInterface) => {
this.initUsersPosition(roomJoinedMessage.users);
this.connectionAnswerPromiseResolve(roomJoinedMessage);
});
// FIXME: weirdly enough we don't use the result of joinARoom !!!!!!
//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.gameMap.setPosition(event.x, event.y);
})
});
}
pushPlayerPosition(event: HasMovedEvent) {
@ -974,7 +964,6 @@ export class GameScene extends ResizableScene implements CenterListener {
type: "InitUserPositionEvent",
event: usersPosition
});
}
/**
@ -1128,12 +1117,7 @@ export class GameScene extends ResizableScene implements CenterListener {
this.groups.delete(groupId);
}
public static getMapKeyByUrl(mapUrlStart: string) : string {
// FIXME: the key should be computed from the full URL of the map.
const startPos = mapUrlStart.indexOf('://')+3;
const endPos = mapUrlStart.indexOf(".json");
return mapUrlStart.substring(startPos, endPos);
}
/**
* Sends to the server an event emitted by one of the ActionableItems.
@ -1189,10 +1173,4 @@ export class GameScene extends ResizableScene implements CenterListener {
public onCenterChange(): void {
this.updateCameraOffset();
}
public onReportUser(){
this.events.on('reportUser', (message: {reportedUserId: number, reportComment: string}) => {
this.connection.emitReportPlayerMessage(message.reportedUserId, message.reportComment);
});
}
}

View file

@ -94,7 +94,7 @@ export class EnableCameraScene extends Phaser.Scene {
this.add.existing(this.logo);
this.input.keyboard.on('keyup-ENTER', () => {
return this.login();
this.login();
});
this.getElementByIdOrFail<HTMLDivElement>('webRtcSetup').classList.add('active');
@ -258,7 +258,7 @@ export class EnableCameraScene extends Phaser.Scene {
this.soundMeterSprite.setVolume(this.soundMeter.getVolume());
}
private async login(): Promise<StartMapInterface> {
private login(): void {
this.getElementByIdOrFail<HTMLDivElement>('webRtcSetup').style.display = 'none';
this.soundMeter.stop();
window.removeEventListener('resize', this.repositionCallback);
@ -266,46 +266,7 @@ export class EnableCameraScene extends Phaser.Scene {
mediaManager.stopCamera();
mediaManager.stopMicrophone();
// Do we have a start URL in the address bar? If so, let's redirect to this address
const instanceAndMapUrl = this.findMapUrl();
if (instanceAndMapUrl !== null) {
const [mapUrl, instance] = instanceAndMapUrl;
const key = gameManager.loadMap(mapUrl, this.scene, instance);
this.scene.start(key, {
startLayerName: window.location.hash ? window.location.hash.substr(1) : undefined
} as GameSceneInitInterface);
return {
mapUrlStart: mapUrl,
startInstance: instance
};
} else {
// If we do not have a map address in the URL, let's ask the server for a start map.
return gameManager.loadStartMap().then((startMap: StartMapInterface) => {
const key = gameManager.loadMap(window.location.protocol + "//" + startMap.mapUrlStart, this.scene, startMap.startInstance);
this.scene.start(key);
return startMap;
}).catch((err) => {
console.error(err);
throw err;
});
}
}
/**
* Returns the map URL and the instance from the current URL
*/
private findMapUrl(): [string, string]|null {
const path = window.location.pathname;
if (!path.startsWith('/_/')) {
return null;
}
const instanceAndMap = path.substr(3);
const firstSlash = instanceAndMap.indexOf('/');
if (firstSlash === -1) {
return null;
}
const instance = instanceAndMap.substr(0, firstSlash);
return [window.location.protocol+'//'+instanceAndMap.substr(firstSlash+1), instance];
gameManager.goToStartingMap(this.scene);
}
private async getDevices() {

View file

@ -0,0 +1,40 @@
import {gameManager} from "../Game/GameManager";
import {TextField} from "../Components/TextField";
import {TextInput} from "../Components/TextInput";
import {ClickButton} from "../Components/ClickButton";
import Image = Phaser.GameObjects.Image;
import Rectangle = Phaser.GameObjects.Rectangle;
import {PLAYER_RESOURCES, PlayerResourceDescriptionInterface} from "../Entity/Character";
import {cypressAsserter} from "../../Cypress/CypressAsserter";
import {SelectCharacterSceneName} from "./SelectCharacterScene";
import {ResizableScene} from "./ResizableScene";
import {Scene} from "phaser";
import {LoginSceneName} from "./LoginScene";
import {FourOFourSceneName} from "../Reconnecting/FourOFourScene";
export const EntrySceneName = "EntryScene";
/**
* The EntryScene is not a real scene. It is the first scene loaded and is only used to initialize the gameManager
* and to route to the next correct scene.
*/
export class EntryScene extends Scene {
constructor() {
super({
key: EntrySceneName
});
}
preload() {
}
create() {
gameManager.init(this.scene).then(() => {
this.scene.start(LoginSceneName);
}).catch(() => {
this.scene.start(FourOFourSceneName, {
url: window.location.pathname.toString()
});
});
}
}

View file

@ -15,7 +15,8 @@ export class FourOFourScene extends Phaser.Scene {
private fileNameField!: Text;
private logo!: Image;
private cat!: Sprite;
private file!: string;
private file: string|undefined;
private url: string|undefined;
constructor() {
super({
@ -23,8 +24,9 @@ export class FourOFourScene extends Phaser.Scene {
});
}
init({ file }: { file: string }) {
init({ file, url }: { file?: string, url?: string }) {
this.file = file;
this.url = url;
}
preload() {
@ -45,11 +47,22 @@ export class FourOFourScene extends Phaser.Scene {
this.mapNotFoundField = new TextField(this, this.game.renderer.width / 2, this.game.renderer.height / 2, "404 - File not found");
this.mapNotFoundField.setOrigin(0.5, 0.5).setCenterAlign();
this.couldNotFindField = new TextField(this, this.game.renderer.width / 2, this.game.renderer.height / 2 + 24, "Could not load file");
let text: string = '';
if (this.file !== undefined) {
text = "Could not load map"
}
if (this.url !== undefined) {
text = "Invalid URL"
}
this.couldNotFindField = new TextField(this, this.game.renderer.width / 2, this.game.renderer.height / 2 + 24, text);
this.couldNotFindField.setOrigin(0.5, 0.5).setCenterAlign();
this.fileNameField = this.add.text(this.game.renderer.width / 2, this.game.renderer.height / 2 + 38, this.file, { fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif', fontSize: '10px' });
this.fileNameField.setOrigin(0.5, 0.5);
const url = this.file ? this.file : this.url;
if (url !== undefined) {
this.fileNameField = this.add.text(this.game.renderer.width / 2, this.game.renderer.height / 2 + 38, url, { fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif', fontSize: '10px' });
this.fileNameField.setOrigin(0.5, 0.5);
}
this.cat = this.physics.add.sprite(this.game.renderer.width / 2, this.game.renderer.height / 2 - 32, 'cat', 6);
this.cat.flipY=true;

View file

@ -0,0 +1,50 @@
export enum GameConnexionTypes {
anonymous=1,
organization,
register,
empty,
unknown,
}
//this class is responsible with analysing and editing the game's url
class UrlManager {
//todo: use that to detect if we can find a token in localstorage
public getGameConnexionType(): GameConnexionTypes {
const url = window.location.pathname.toString();
if (url.includes('_/')) {
return GameConnexionTypes.anonymous;
} else if (url.includes('@/')) {
return GameConnexionTypes.organization;
} else if(url.includes('register/')) {
return GameConnexionTypes.register;
} else if(url === '/') {
return GameConnexionTypes.empty;
} else {
return GameConnexionTypes.unknown;
}
}
public getOrganizationToken(): string|null {
const match = /\/register\/(.+)/.exec(window.location.pathname.toString());
return match ? match [1] : null;
}
//todo: simply use the roomId
//todo: test this with cypress
public editUrlForRoom(roomSlug: string, organizationSlug: string|null, worldSlug: string |null): string {
let newUrl:string;
if (organizationSlug) {
newUrl = '/@/'+organizationSlug+'/'+worldSlug+'/'+roomSlug;
} else {
newUrl = '/_/global/'+roomSlug;
}
history.pushState({}, 'WorkAdventure', newUrl);
return newUrl;
}
}
export const urlManager = new UrlManager();

View file

@ -11,11 +11,11 @@ import WebGLRenderer = Phaser.Renderer.WebGL.WebGLRenderer;
import {OutlinePipeline} from "./Phaser/Shaders/OutlinePipeline";
import {CustomizeScene} from "./Phaser/Login/CustomizeScene";
import {CoWebsiteManager} from "./WebRtc/CoWebsiteManager";
import {connectionManager} from "./Connexion/ConnectionManager";
import {gameManager} from "./Phaser/Game/GameManager";
import {ResizableScene} from "./Phaser/Login/ResizableScene";
import {EntryScene} from "./Phaser/Login/EntryScene";
//CoWebsiteManager.loadCoWebsite('https://thecodingmachine.com');
connectionManager.init();
// Load Jitsi if the environment variable is set.
if (JITSI_URL) {
@ -31,14 +31,7 @@ const config: GameConfig = {
width: width / RESOLUTION,
height: height / RESOLUTION,
parent: "game",
scene: [
LoginScene,
SelectCharacterScene,
EnableCameraScene,
ReconnectingScene,
FourOFourScene,
CustomizeScene
],
scene: [EntryScene, LoginScene, SelectCharacterScene, EnableCameraScene, ReconnectingScene, FourOFourScene, CustomizeScene],
zoom: RESOLUTION,
physics: {
default: "arcade",

File diff suppressed because it is too large Load diff