Migrating userId to "int32" to save some space and adding userMoves message in protobuf

This commit is contained in:
David Négrier 2020-09-18 13:57:38 +02:00
parent 4b55b54a07
commit e9ca8721a6
31 changed files with 295 additions and 445 deletions

View file

@ -1,13 +1,19 @@
import Axios from "axios";
import {API_URL} from "./Enum/EnvironmentVariable";
import {MessageUI} from "./Logger/MessageUI";
import {SetPlayerDetailsMessage} from "../../messages/generated/src/proto/messages_pb"
import {
PositionMessage,
SetPlayerDetailsMessage,
UserMovesMessage,
ViewportMessage
} from "../../messages/generated/messages_pb"
const SocketIo = require('socket.io-client');
import Socket = SocketIOClient.Socket;
import {PlayerAnimationNames} from "./Phaser/Player/Animation";
import {UserSimplePeerInterface} from "./WebRtc/SimplePeer";
import {SignalData} from "simple-peer";
import Direction = PositionMessage.Direction;
enum EventMessage{
WEBRTC_SIGNAL = "webrtc-signal",
@ -46,19 +52,19 @@ export class Point implements PointInterface{
}
export interface MessageUserPositionInterface {
userId: string;
userId: number;
name: string;
characterLayers: string[];
position: PointInterface;
}
export interface MessageUserMovedInterface {
userId: string;
userId: number;
position: PointInterface;
}
export interface MessageUserJoined {
userId: string;
userId: number;
name: string;
characterLayers: string[];
position: PointInterface
@ -80,16 +86,16 @@ export interface WebRtcStartMessageInterface {
}
export interface WebRtcDisconnectMessageInterface {
userId: string
userId: number
}
export interface WebRtcSignalSentMessageInterface {
receiverId: string,
receiverId: number,
signal: SignalData
}
export interface WebRtcSignalReceivedMessageInterface {
userId: string,
userId: number,
signal: SignalData
}
@ -105,11 +111,6 @@ export interface ViewportInterface {
bottom: number,
}
export interface UserMovesInterface {
position: PositionInterface,
viewport: ViewportInterface,
}
export interface BatchedMessageInterface {
event: string,
payload: unknown
@ -130,7 +131,7 @@ export interface RoomJoinedMessageInterface {
export class Connection implements Connection {
private readonly socket: Socket;
private userId: string|null = null;
private userId: number|null = null;
private constructor(token: string) {
@ -173,7 +174,7 @@ export class Connection implements Connection {
const message = new SetPlayerDetailsMessage();
message.setName(name);
message.setCharacterlayersList(characterLayersSelected);
connection.socket.emit(EventMessage.SET_PLAYER_DETAILS, message.serializeBinary().buffer, (id: string) => {
connection.socket.emit(EventMessage.SET_PLAYER_DETAILS, message.serializeBinary().buffer, (id: number) => {
connection.userId = id;
});
@ -214,7 +215,40 @@ export class Connection implements Connection {
return;
}
const point = new Point(x, y, direction, moving);
this.socket.emit(EventMessage.USER_POSITION, { position: point, viewport } as UserMovesInterface);
const positionMessage = new PositionMessage();
positionMessage.setX(Math.floor(x));
positionMessage.setY(Math.floor(y));
let directionEnum: PositionMessage.DirectionMap[keyof PositionMessage.DirectionMap];
switch (direction) {
case 'up':
directionEnum = Direction.UP;
break;
case 'down':
directionEnum = Direction.DOWN;
break;
case 'left':
directionEnum = Direction.LEFT;
break;
case 'right':
directionEnum = Direction.RIGHT;
break;
default:
throw new Error("Unexpected direction");
}
positionMessage.setDirection(directionEnum);
positionMessage.setMoving(moving);
const viewportMessage = new ViewportMessage();
viewportMessage.setLeft(Math.floor(viewport.left));
viewportMessage.setRight(Math.floor(viewport.right));
viewportMessage.setTop(Math.floor(viewport.top));
viewportMessage.setBottom(Math.floor(viewport.bottom));
const userMovesMessage = new UserMovesMessage();
userMovesMessage.setPosition(positionMessage);
userMovesMessage.setViewport(viewportMessage);
this.socket.emit(EventMessage.USER_POSITION, userMovesMessage.serializeBinary().buffer);
}
public setSilent(silent: boolean): void {
@ -233,7 +267,7 @@ export class Connection implements Connection {
this.socket.on(EventMessage.USER_MOVED, callback);
}
public onUserLeft(callback: (userId: string) => void): void {
public onUserLeft(callback: (userId: number) => void): void {
this.socket.on(EventMessage.USER_LEFT, callback);
}
@ -249,14 +283,14 @@ export class Connection implements Connection {
this.socket.on(EventMessage.CONNECT_ERROR, callback)
}
public sendWebrtcSignal(signal: unknown, receiverId : string) {
public sendWebrtcSignal(signal: unknown, receiverId: number) {
return this.socket.emit(EventMessage.WEBRTC_SIGNAL, {
receiverId: receiverId,
signal: signal
} as WebRtcSignalSentMessageInterface);
}
public sendWebrtcScreenSharingSignal(signal: unknown, receiverId : string) {
public sendWebrtcScreenSharingSignal(signal: unknown, receiverId: number) {
return this.socket.emit(EventMessage.WEBRTC_SCREEN_SHARING_SIGNAL, {
receiverId: receiverId,
signal: signal
@ -286,7 +320,7 @@ export class Connection implements Connection {
}
public getUserId(): string|null {
public getUserId(): number|null {
return this.userId;
}

View file

@ -6,10 +6,10 @@ import {Character} from "../Entity/Character";
* Class representing the sprite of a remote player (a player that plays on another computer)
*/
export class RemotePlayer extends Character {
userId: string;
userId: number;
constructor(
userId: string,
userId: number,
Scene: GameScene,
x: number,
y: number,

View file

@ -1,7 +1,7 @@
import {PointInterface} from "../../Connection";
export interface AddPlayerInterface {
userId: string;
userId: number;
name: string;
characterLayers: string[];
position: PointInterface;

View file

@ -63,7 +63,7 @@ interface AddPlayerEventInterface {
interface RemovePlayerEventInterface {
type: 'RemovePlayerEvent'
userId: string
userId: number
}
interface UserMovedEventInterface {
@ -86,7 +86,7 @@ export class GameScene extends Phaser.Scene implements CenterListener {
Terrains : Array<Phaser.Tilemaps.Tileset>;
CurrentPlayer!: CurrentGamerInterface;
MapPlayers!: Phaser.Physics.Arcade.Group;
MapPlayersByKey : Map<string, RemotePlayer> = new Map<string, RemotePlayer>();
MapPlayersByKey : Map<number, RemotePlayer> = new Map<number, RemotePlayer>();
Map!: Phaser.Tilemaps.Tilemap;
Layers!: Array<Phaser.Tilemaps.StaticTilemapLayer>;
Objects!: Array<Phaser.Physics.Arcade.Sprite>;
@ -217,7 +217,7 @@ export class GameScene extends Phaser.Scene implements CenterListener {
this.updatePlayerPosition(message);
});
connection.onUserLeft((userId: string) => {
connection.onUserLeft((userId: number) => {
this.removePlayer(userId);
});
@ -271,7 +271,7 @@ export class GameScene extends Phaser.Scene implements CenterListener {
self.presentationModeSprite.setVisible(true);
self.chatModeSprite.setVisible(true);
},
onDisconnect(userId: string) {
onDisconnect(userId: number) {
if (self.simplePeer.getNbConnections() === 0) {
self.presentationModeSprite.setVisible(false);
self.chatModeSprite.setVisible(false);
@ -918,7 +918,7 @@ export class GameScene extends Phaser.Scene implements CenterListener {
// Let's move all users
const updatedPlayersPositions = this.playersPositionInterpolator.getUpdatedPositions(time);
updatedPlayersPositions.forEach((moveEvent: HasMovedEvent, userId: string) => {
updatedPlayersPositions.forEach((moveEvent: HasMovedEvent, userId: number) => {
const player : RemotePlayer | undefined = this.MapPlayersByKey.get(userId);
if (player === undefined) {
throw new Error('Cannot find player with ID "' + userId +'"');
@ -973,7 +973,7 @@ export class GameScene extends Phaser.Scene implements CenterListener {
player.destroy();
this.MapPlayers.remove(player);
});
this.MapPlayersByKey = new Map<string, RemotePlayer>();
this.MapPlayersByKey = new Map<number, RemotePlayer>();
// load map
usersPosition.forEach((userPosition : MessageUserPositionInterface) => {
@ -1030,14 +1030,14 @@ export class GameScene extends Phaser.Scene implements CenterListener {
/**
* Called by the connexion when a player is removed from the map
*/
public removePlayer(userId: string) {
public removePlayer(userId: number) {
this.pendingEvents.enqueue({
type: "RemovePlayerEvent",
userId
});
}
private doRemovePlayer(userId: string) {
private doRemovePlayer(userId: number) {
const player = this.MapPlayersByKey.get(userId);
if (player === undefined) {
console.error('Cannot find user with id ', userId);

View file

@ -6,19 +6,19 @@ import {PlayerMovement} from "./PlayerMovement";
import {HasMovedEvent} from "./GameManager";
export class PlayersPositionInterpolator {
playerMovements: Map<string, PlayerMovement> = new Map<string, PlayerMovement>();
playerMovements: Map<number, PlayerMovement> = new Map<number, PlayerMovement>();
updatePlayerPosition(userId: string, playerMovement: PlayerMovement) : void {
updatePlayerPosition(userId: number, playerMovement: PlayerMovement) : void {
this.playerMovements.set(userId, playerMovement);
}
removePlayer(userId: string): void {
removePlayer(userId: number): void {
this.playerMovements.delete(userId);
}
getUpdatedPositions(tick: number) : Map<string, HasMovedEvent> {
const positions = new Map<string, HasMovedEvent>();
this.playerMovements.forEach((playerMovement: PlayerMovement, userId: string) => {
getUpdatedPositions(tick: number) : Map<number, HasMovedEvent> {
const positions = new Map<number, HasMovedEvent>();
this.playerMovements.forEach((playerMovement: PlayerMovement, userId: number) => {
if (playerMovement.isOutdated(tick)) {
//console.log("outdated")
this.playerMovements.delete(userId);

View file

@ -343,7 +343,7 @@ export class MediaManager {
*
* @param userId
*/
addActiveVideo(userId : string, userName: string = ""){
addActiveVideo(userId: string, userName: string = ""){
this.webrtcInAudio.play();
userName = userName.toUpperCase();
@ -368,7 +368,7 @@ export class MediaManager {
*
* @param userId
*/
addScreenSharingActiveVideo(userId : string, divImportance: DivImportance = DivImportance.Important){
addScreenSharingActiveVideo(userId: string, divImportance: DivImportance = DivImportance.Important){
//this.webrtcInAudio.play();
userId = `screen-sharing-${userId}`;
@ -387,7 +387,7 @@ export class MediaManager {
*
* @param userId
*/
disabledMicrophoneByUserId(userId: string){
disabledMicrophoneByUserId(userId: number){
const element = document.getElementById(`microphone-${userId}`);
if(!element){
return;
@ -399,7 +399,7 @@ export class MediaManager {
*
* @param userId
*/
enabledMicrophoneByUserId(userId: string){
enabledMicrophoneByUserId(userId: number){
const element = document.getElementById(`microphone-${userId}`);
if(!element){
return;
@ -411,7 +411,7 @@ export class MediaManager {
*
* @param userId
*/
disabledVideoByUserId(userId: string) {
disabledVideoByUserId(userId: number) {
let element = document.getElementById(`${userId}`);
if (element) {
element.style.opacity = "0";
@ -426,7 +426,7 @@ export class MediaManager {
*
* @param userId
*/
enabledVideoByUserId(userId: string){
enabledVideoByUserId(userId: number){
let element = document.getElementById(`${userId}`);
if(element){
element.style.opacity = "1";
@ -442,7 +442,7 @@ export class MediaManager {
* @param userId
* @param stream
*/
addStreamRemoteVideo(userId : string, stream : MediaStream){
addStreamRemoteVideo(userId: string, stream : MediaStream){
const remoteVideo = this.remoteVideo.get(userId);
if (remoteVideo === undefined) {
console.error('Unable to find video for ', userId);
@ -450,7 +450,7 @@ export class MediaManager {
}
remoteVideo.srcObject = stream;
}
addStreamRemoteScreenSharing(userId : string, stream : MediaStream){
addStreamRemoteScreenSharing(userId: string, stream : MediaStream){
// In the case of screen sharing (going both ways), we may need to create the HTML element if it does not exist yet
const remoteVideo = this.remoteVideo.get(`screen-sharing-${userId}`);
if (remoteVideo === undefined) {
@ -464,15 +464,15 @@ export class MediaManager {
*
* @param userId
*/
removeActiveVideo(userId : string){
removeActiveVideo(userId: string){
layoutManager.remove(userId);
this.remoteVideo.delete(userId);
}
removeActiveScreenSharingVideo(userId : string) {
removeActiveScreenSharingVideo(userId: string) {
this.removeActiveVideo(`screen-sharing-${userId}`)
}
isConnecting(userId : string): void {
isConnecting(userId: string): void {
const connectingSpinnerDiv = this.getSpinner(userId);
if (connectingSpinnerDiv === null) {
return;
@ -480,7 +480,7 @@ export class MediaManager {
connectingSpinnerDiv.style.display = 'block';
}
isConnected(userId : string): void {
isConnected(userId: string): void {
const connectingSpinnerDiv = this.getSpinner(userId);
if (connectingSpinnerDiv === null) {
return;
@ -488,7 +488,7 @@ export class MediaManager {
connectingSpinnerDiv.style.display = 'none';
}
isError(userId : string): void {
isError(userId: string): void {
console.log("isError", `div-${userId}`);
const element = document.getElementById(`div-${userId}`);
if(!element){
@ -500,12 +500,12 @@ export class MediaManager {
}
errorDiv.style.display = 'block';
}
isErrorScreenSharing(userId : string): void {
isErrorScreenSharing(userId: string): void {
this.isError(`screen-sharing-${userId}`);
}
private getSpinner(userId : string): HTMLDivElement|null {
private getSpinner(userId: string): HTMLDivElement|null {
const element = document.getElementById(`div-${userId}`);
if(!element){
return null;

View file

@ -14,7 +14,7 @@ export class ScreenSharingPeer extends Peer {
*/
private isReceivingStream:boolean = false;
constructor(private userId: string, initiator: boolean, private connection: Connection) {
constructor(private userId: number, initiator: boolean, private connection: Connection) {
super({
initiator: initiator ? initiator : false,
reconnectTimer: 10000,
@ -52,7 +52,7 @@ export class ScreenSharingPeer extends Peer {
if (message.streamEnded !== true) {
console.error('Unexpected message on screen sharing peer connection');
}
mediaManager.removeActiveScreenSharingVideo(this.userId);
mediaManager.removeActiveScreenSharingVideo("" + this.userId);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -63,7 +63,7 @@ export class ScreenSharingPeer extends Peer {
this.on('connect', () => {
// FIXME: we need to put the loader on the screen sharing connection
mediaManager.isConnected(this.userId);
mediaManager.isConnected("" + this.userId);
console.info(`connect => ${this.userId}`);
});
@ -86,10 +86,10 @@ export class ScreenSharingPeer extends Peer {
//console.log(`ScreenSharingPeer::stream => ${this.userId}`, stream);
//console.log(`stream => ${this.userId} => `, stream);
if(!stream){
mediaManager.removeActiveScreenSharingVideo(this.userId);
mediaManager.removeActiveScreenSharingVideo("" + this.userId);
this.isReceivingStream = false;
} else {
mediaManager.addStreamRemoteScreenSharing(this.userId, stream);
mediaManager.addStreamRemoteScreenSharing("" + this.userId, stream);
this.isReceivingStream = true;
}
}
@ -100,7 +100,7 @@ export class ScreenSharingPeer extends Peer {
public destroy(error?: Error): void {
try {
mediaManager.removeActiveScreenSharingVideo(this.userId);
mediaManager.removeActiveScreenSharingVideo("" + this.userId);
// FIXME: I don't understand why "Closing connection with" message is displayed TWICE before "Nb users in peerConnectionArray"
// I do understand the method closeConnection is called twice, but I don't understand how they manage to run in parallel.
//console.log('Closing connection with '+userId);

View file

@ -16,7 +16,7 @@ import {VideoPeer} from "./VideoPeer";
const Peer: SimplePeerNamespace.SimplePeer = require('simple-peer');
export interface UserSimplePeerInterface{
userId: string;
userId: number;
name?: string;
initiator?: boolean;
}
@ -24,7 +24,7 @@ export interface UserSimplePeerInterface{
export interface PeerConnectionListener {
onConnect(user: UserSimplePeerInterface): void;
onDisconnect(userId: string): void;
onDisconnect(userId: number): void;
}
/**
@ -35,8 +35,8 @@ export class SimplePeer {
private WebRtcRoomId: string;
private Users: Array<UserSimplePeerInterface> = new Array<UserSimplePeerInterface>();
private PeerScreenSharingConnectionArray: Map<string, ScreenSharingPeer> = new Map<string, ScreenSharingPeer>();
private PeerConnectionArray: Map<string, VideoPeer> = new Map<string, VideoPeer>();
private PeerScreenSharingConnectionArray: Map<number, ScreenSharingPeer> = new Map<number, ScreenSharingPeer>();
private PeerConnectionArray: Map<number, VideoPeer> = new Map<number, VideoPeer>();
private readonly sendLocalVideoStreamCallback: UpdatedLocalStreamCallback;
private readonly sendLocalScreenSharingStreamCallback: StartScreenSharingCallback;
private readonly stopLocalScreenSharingStreamCallback: StopScreenSharingCallback;
@ -140,8 +140,8 @@ export class SimplePeer {
}
}
mediaManager.removeActiveVideo(user.userId);
mediaManager.addActiveVideo(user.userId, name);
mediaManager.removeActiveVideo("" + user.userId);
mediaManager.addActiveVideo("" + user.userId, name);
const peer = new VideoPeer(user.userId, user.initiator ? user.initiator : false, this.Connection);
// When a connection is established to a video stream, and if a screen sharing is taking place,
@ -171,8 +171,8 @@ export class SimplePeer {
// We should display the screen sharing ONLY if we are not initiator
if (!user.initiator) {
mediaManager.removeActiveScreenSharingVideo(user.userId);
mediaManager.addScreenSharingActiveVideo(user.userId);
mediaManager.removeActiveScreenSharingVideo("" + user.userId);
mediaManager.addScreenSharingActiveVideo("" + user.userId);
}
const peer = new ScreenSharingPeer(user.userId, user.initiator ? user.initiator : false, this.Connection);
@ -189,7 +189,7 @@ export class SimplePeer {
*
* @param userId
*/
private closeConnection(userId : string) {
private closeConnection(userId : number) {
try {
//mediaManager.removeActiveVideo(userId);
const peer = this.PeerConnectionArray.get(userId);
@ -217,9 +217,9 @@ export class SimplePeer {
*
* @param userId
*/
private closeScreenSharingConnection(userId : string) {
private closeScreenSharingConnection(userId : number) {
try {
mediaManager.removeActiveScreenSharingVideo(userId);
mediaManager.removeActiveScreenSharingVideo("" + userId);
const peer = this.PeerScreenSharingConnectionArray.get(userId);
if (peer === undefined) {
console.warn("Tried to close connection for user "+userId+" but could not find user")
@ -293,7 +293,7 @@ export class SimplePeer {
*
* @param userId
*/
private pushVideoToRemoteUser(userId : string) {
private pushVideoToRemoteUser(userId : number) {
try {
const PeerConnection = this.PeerConnectionArray.get(userId);
if (!PeerConnection) {
@ -314,7 +314,7 @@ export class SimplePeer {
}
}
private pushScreenSharingToRemoteUser(userId : string) {
private pushScreenSharingToRemoteUser(userId : number) {
const PeerConnection = this.PeerScreenSharingConnectionArray.get(userId);
if (!PeerConnection) {
throw new Error('While pushing screen sharing, cannot find user with ID ' + userId);
@ -359,7 +359,7 @@ export class SimplePeer {
}
}
private sendLocalScreenSharingStreamToUser(userId: string): void {
private sendLocalScreenSharingStreamToUser(userId: number): void {
// If a connection already exists with user (because it is already sharing a screen with us... let's use this connection)
if (this.PeerScreenSharingConnectionArray.has(userId)) {
this.pushScreenSharingToRemoteUser(userId);
@ -376,7 +376,7 @@ export class SimplePeer {
}
}
private stopLocalScreenSharingStreamToUser(userId: string, stream: MediaStream): void {
private stopLocalScreenSharingStreamToUser(userId: number, stream: MediaStream): void {
const PeerConnectionScreenSharing = this.PeerScreenSharingConnectionArray.get(userId);
if (!PeerConnectionScreenSharing) {
throw new Error('Weird, screen sharing connection to user ' + userId + 'not found')

View file

@ -9,7 +9,7 @@ const Peer: SimplePeerNamespace.SimplePeer = require('simple-peer');
* A peer connection used to transmit video / audio signals between 2 peers.
*/
export class VideoPeer extends Peer {
constructor(private userId: string, initiator: boolean, private connection: Connection) {
constructor(private userId: number, initiator: boolean, private connection: Connection) {
super({
initiator: initiator ? initiator : false,
reconnectTimer: 10000,
@ -63,11 +63,11 @@ export class VideoPeer extends Peer {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.on('error', (err: any) => {
console.error(`error => ${this.userId} => ${err.code}`, err);
mediaManager.isError(userId);
mediaManager.isError("" + userId);
});
this.on('connect', () => {
mediaManager.isConnected(this.userId);
mediaManager.isConnected("" + this.userId);
console.info(`connect => ${this.userId}`);
});
@ -108,7 +108,7 @@ export class VideoPeer extends Peer {
mediaManager.disabledVideoByUserId(this.userId);
mediaManager.disabledMicrophoneByUserId(this.userId);
} else {
mediaManager.addStreamRemoteVideo(this.userId, stream);
mediaManager.addStreamRemoteVideo("" + this.userId, stream);
}
}
@ -117,7 +117,7 @@ export class VideoPeer extends Peer {
*/
public destroy(error?: Error): void {
try {
mediaManager.removeActiveVideo(this.userId);
mediaManager.removeActiveVideo("" + this.userId);
// FIXME: I don't understand why "Closing connection with" message is displayed TWICE before "Nb users in peerConnectionArray"
// I do understand the method closeConnection is called twice, but I don't understand how they manage to run in parallel.
//console.log('Closing connection with '+userId);