phaserLayers managed by Gamemap

Implementation of LayersFlattener
Implementation of Setting properties of a layer form script
Update show/hide layer form script
Update unit test of LayersIteratorTest
This commit is contained in:
GRL 2021-05-12 14:30:12 +02:00
parent ab7b06f71e
commit 43aad4ab14
11 changed files with 258 additions and 196 deletions

View File

@ -10,6 +10,7 @@ import { OpenPopupEvent } from './OpenPopupEvent';
import { OpenTabEvent } from './OpenTabEvent'; import { OpenTabEvent } from './OpenTabEvent';
import { UserInputChatEvent } from './UserInputChatEvent'; import { UserInputChatEvent } from './UserInputChatEvent';
import { LayerEvent } from './LayerEvent'; import { LayerEvent } from './LayerEvent';
import { SetPropertyEvent } from "./setPropertyEvent";
export interface TypedMessageEvent<T> extends MessageEvent { export interface TypedMessageEvent<T> extends MessageEvent {
@ -32,6 +33,7 @@ export type IframeEventMap = {
removeBubble: null removeBubble: null
showLayer: LayerEvent showLayer: LayerEvent
hideLayer: LayerEvent hideLayer: LayerEvent
setProperty: SetPropertyEvent
} }
export interface IframeEvent<T extends keyof IframeEventMap> { export interface IframeEvent<T extends keyof IframeEventMap> {
type: T; type: T;

View File

@ -0,0 +1,12 @@
import * as tg from "generic-type-guard";
export const isSetPropertyEvent =
new tg.IsInterface().withProperties({
layerName: tg.isString,
propertyName: tg.isString,
propertyValue: tg.isUnion(tg.isString, tg.isUnion(tg.isNumber, tg.isUnion(tg.isBoolean, tg.isUndefined)))
}).get();
/**
* A message sent from the iFrame to the game to change the value of the property of the layer
*/
export type SetPropertyEvent = tg.GuardedType<typeof isSetPropertyEvent>;

View File

@ -13,6 +13,7 @@ import { isOpenCoWebsite, OpenCoWebSiteEvent } from "./Events/OpenCoWebSiteEvent
import { IframeEventMap, IframeEvent, IframeResponseEvent, IframeResponseEventMap, isIframeEventWrapper, TypedMessageEvent } from "./Events/IframeEvent"; import { IframeEventMap, IframeEvent, IframeResponseEvent, IframeResponseEventMap, isIframeEventWrapper, TypedMessageEvent } from "./Events/IframeEvent";
import { UserInputChatEvent } from "./Events/UserInputChatEvent"; import { UserInputChatEvent } from "./Events/UserInputChatEvent";
import { isLayerEvent, LayerEvent } from "./Events/LayerEvent"; import { isLayerEvent, LayerEvent } from "./Events/LayerEvent";
import { isSetPropertyEvent, SetPropertyEvent} from "./Events/setPropertyEvent";
/** /**
@ -59,6 +60,9 @@ class IframeListener {
private readonly _hideLayerStream: Subject<LayerEvent> = new Subject(); private readonly _hideLayerStream: Subject<LayerEvent> = new Subject();
public readonly hideLayerStream = this._hideLayerStream.asObservable(); public readonly hideLayerStream = this._hideLayerStream.asObservable();
private readonly _setPropertyStream: Subject<SetPropertyEvent> = new Subject();
public readonly setPropertyStream = this._setPropertyStream.asObservable();
private readonly iframes = new Set<HTMLIFrameElement>(); private readonly iframes = new Set<HTMLIFrameElement>();
private readonly scripts = new Map<string, HTMLIFrameElement>(); private readonly scripts = new Map<string, HTMLIFrameElement>();
@ -84,6 +88,8 @@ class IframeListener {
this._showLayerStream.next(payload.data); this._showLayerStream.next(payload.data);
} else if (payload.type === 'hideLayer' && isLayerEvent(payload.data)) { } else if (payload.type === 'hideLayer' && isLayerEvent(payload.data)) {
this._hideLayerStream.next(payload.data); this._hideLayerStream.next(payload.data);
} else if (payload.type === 'setProperty' && isSetPropertyEvent(payload.data)) {
this._setPropertyStream.next(payload.data);
} else if (payload.type === 'chat' && isChatEvent(payload.data)) { } else if (payload.type === 'chat' && isChatEvent(payload.data)) {
this._chatStream.next(payload.data); this._chatStream.next(payload.data);
} else if (payload.type === 'openPopup' && isOpenPopupEvent(payload.data)) { } else if (payload.type === 'openPopup' && isOpenPopupEvent(payload.data)) {

View File

@ -1,5 +1,5 @@
import {ITiledMap, ITiledMapLayer} from "../Map/ITiledMap"; import {ITiledMap, ITiledMapLayer, ITiledMapTileLayer} from "../Map/ITiledMap";
import {LayersIterator} from "../Map/LayersIterator"; import { flattenGroupLayersMap } from "../Map/LayersFlattener";
export type PropertyChangeCallback = (newValue: string | number | boolean | undefined, oldValue: string | number | boolean | undefined, allProps: Map<string, string | boolean | number>) => void; export type PropertyChangeCallback = (newValue: string | number | boolean | undefined, oldValue: string | number | boolean | undefined, allProps: Map<string, string | boolean | number>) => void;
@ -11,10 +11,19 @@ export class GameMap {
private key: number|undefined; private key: number|undefined;
private lastProperties = new Map<string, string|boolean|number>(); private lastProperties = new Map<string, string|boolean|number>();
private callbacks = new Map<string, Array<PropertyChangeCallback>>(); private callbacks = new Map<string, Array<PropertyChangeCallback>>();
public readonly layersIterator: LayersIterator; public readonly flatLayers: ITiledMapLayer[];
public constructor(private map: ITiledMap) { public constructor(private map: ITiledMap, phaserMap: Phaser.Tilemaps.Tilemap, terrains: Array<Phaser.Tilemaps.Tileset>) {
this.layersIterator = new LayersIterator(map); this.flatLayers = flattenGroupLayersMap(map);
let depth = -2;
for (const layer of this.flatLayers) {
if(layer.type === 'tilelayer'){
layer.phaserLayer = phaserMap.createLayer(layer.name, terrains, 0, 0).setDepth(depth);
}
if (layer.type === 'objectgroup' && layer.name === 'floorLayer') {
depth = 10000;
}
}
} }
/** /**
@ -58,7 +67,7 @@ export class GameMap {
private getProperties(key: number): Map<string, string|boolean|number> { private getProperties(key: number): Map<string, string|boolean|number> {
const properties = new Map<string, string|boolean|number>(); const properties = new Map<string, string|boolean|number>();
for (const layer of this.layersIterator) { for (const layer of this.flatLayers) {
if (layer.type !== 'tilelayer') { if (layer.type !== 'tilelayer') {
continue; continue;
} }
@ -100,4 +109,22 @@ export class GameMap {
} }
callbacksArray.push(callback); callbacksArray.push(callback);
} }
public findLayer(layerName: string): ITiledMapLayer | undefined {
let i = 0;
let found = false;
while (!found && i<this.flatLayers.length) {
if (this.flatLayers[i].name === layerName) {
found = true;
}
else {
i++;
}
}
if (found) {
return this.flatLayers[i];
}
return undefined;
}
} }

View File

@ -92,6 +92,7 @@ import {PinchManager} from "../UserInput/PinchManager";
import {joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey} from "../Components/MobileJoystick"; import {joystickBaseImg, joystickBaseKey, joystickThumbImg, joystickThumbKey} from "../Components/MobileJoystick";
import {waScaleManager} from "../Services/WaScaleManager"; import {waScaleManager} from "../Services/WaScaleManager";
import {LayerEvent} from "../../Api/Events/LayerEvent"; import {LayerEvent} from "../../Api/Events/LayerEvent";
import {SetPropertyEvent} from "../../Api/Events/setPropertyEvent";
export interface GameSceneInitInterface { export interface GameSceneInitInterface {
initPosition: PointInterface|null, initPosition: PointInterface|null,
@ -136,7 +137,6 @@ export class GameScene extends DirtyScene implements CenterListener {
MapPlayers!: Phaser.Physics.Arcade.Group; 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; Map!: Phaser.Tilemaps.Tilemap;
Layers!: Array<Phaser.Tilemaps.TilemapLayer>;
Objects!: Array<Phaser.Physics.Arcade.Sprite>; Objects!: Array<Phaser.Physics.Arcade.Sprite>;
mapFile!: ITiledMap; mapFile!: ITiledMap;
groups: Map<number, Sprite>; groups: Map<number, Sprite>;
@ -392,7 +392,6 @@ export class GameScene extends DirtyScene implements CenterListener {
//initalise map //initalise map
this.Map = this.add.tilemap(this.MapUrlFile); this.Map = this.add.tilemap(this.MapUrlFile);
this.gameMap = new GameMap(this.mapFile);
const mapDirUrl = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/')); const mapDirUrl = this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/'));
this.mapFile.tilesets.forEach((tileset: ITiledTileSet) => { this.mapFile.tilesets.forEach((tileset: ITiledTileSet) => {
this.Terrains.push(this.Map.addTilesetImage(tileset.name, `${mapDirUrl}/${tileset.image}`, tileset.tilewidth, tileset.tileheight, tileset.margin, tileset.spacing/*, tileset.firstgid*/)); this.Terrains.push(this.Map.addTilesetImage(tileset.name, `${mapDirUrl}/${tileset.image}`, tileset.tilewidth, tileset.tileheight, tileset.margin, tileset.spacing/*, tileset.firstgid*/));
@ -402,11 +401,9 @@ export class GameScene extends DirtyScene implements CenterListener {
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 //add layer on map
this.Layers = new Array<Phaser.Tilemaps.TilemapLayer>(); this.gameMap = new GameMap(this.mapFile, this.Map, this.Terrains);
let depth = -2; for (const layer of this.gameMap.flatLayers) {
for (const layer of this.gameMap.layersIterator) {
if (layer.type === 'tilelayer') { if (layer.type === 'tilelayer') {
this.addLayer(this.Map.createLayer(layer.name, this.Terrains, 0, 0).setDepth(depth));
const exitSceneUrl = this.getExitSceneUrl(layer); const exitSceneUrl = this.getExitSceneUrl(layer);
if (exitSceneUrl !== undefined) { if (exitSceneUrl !== undefined) {
@ -417,9 +414,6 @@ export class GameScene extends DirtyScene implements CenterListener {
this.loadNextGame(exitUrl); this.loadNextGame(exitUrl);
} }
} }
if (layer.type === 'objectgroup' && layer.name === 'floorLayer') {
depth = 10000;
}
if (layer.type === 'objectgroup') { if (layer.type === 'objectgroup') {
for (const object of layer.objects) { for (const object of layer.objects) {
if (object.text) { if (object.text) {
@ -428,9 +422,6 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
} }
} }
if (depth === -2) {
throw new Error('Your map MUST contain a layer of type "objectgroup" whose name is "floorLayer" that represents the layer characters are drawn at. This layer cannot be contained in a group.');
}
this.initStartXAndStartY(); this.initStartXAndStartY();
@ -884,15 +875,38 @@ ${escapedMessage}
this.setLayerVisibility(layerEvent.name, false); this.setLayerVisibility(layerEvent.name, false);
})); }));
this.iframeSubscriptionList.push(iframeListener.setPropertyStream.subscribe((setProperty) => {
this.setPropertyLayer(setProperty.layerName, setProperty.propertyName, setProperty.propertyValue);
}));
}
private setPropertyLayer(layerName: string, propertyName: string, propertyValue: string | number | boolean | undefined): void {
const layer = this.gameMap.findLayer(layerName);
if (layer === undefined) {
console.warn('Could not find layer "' + layerName + '" when calling setProperty');
return;
}
const property = (layer.properties as ITiledMapLayerProperty[])?.find((property) => property.name === propertyName);
if (property === undefined) {
layer.properties = [];
layer.properties.push({name : propertyName, type : typeof propertyValue, value : propertyValue});
return;
}
property.value = propertyValue;
} }
private setLayerVisibility(layerName: string, visible: boolean): void { private setLayerVisibility(layerName: string, visible: boolean): void {
const layer = this.Layers.find((layer) => layer.layer.name === layerName); const layer = this.gameMap.findLayer(layerName);
if (layer === undefined) { if (layer === undefined) {
console.warn('Could not find layer "' + layerName + '" when calling WA.hideLayer / WA.showLayer'); console.warn('Could not find layer "' + layerName + '" when calling WA.hideLayer / WA.showLayer');
return; return;
} }
layer.setVisible(visible); if(layer.type != "tilelayer"){
console.warn('The layer "' + layerName + '" is not a tilelayer. It can not be show/hide');
return;
}
layer.phaserLayer?.setVisible(visible);
this.dirty = true; this.dirty = true;
} }
@ -1001,7 +1015,7 @@ ${escapedMessage}
} }
private initPositionFromLayerName(layerName: string) { private initPositionFromLayerName(layerName: string) {
for (const layer of this.gameMap.layersIterator) { 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); const startPosition = this.startUser(layer);
this.startX = startPosition.x + this.mapFile.tilewidth/2; this.startX = startPosition.x + this.mapFile.tilewidth/2;
@ -1091,27 +1105,29 @@ ${escapedMessage}
this.updateCameraOffset(); this.updateCameraOffset();
} }
addLayer(Layer : Phaser.Tilemaps.TilemapLayer){
this.Layers.push(Layer);
}
createCollisionWithPlayer() { createCollisionWithPlayer() {
this.physics.disableUpdate(); this.physics.disableUpdate();
//add collision layer //add collision layer
this.Layers.forEach((Layer: Phaser.Tilemaps.TilemapLayer) => { for (const Layer of this.gameMap.flatLayers) {
this.physics.add.collider(this.CurrentPlayer, Layer, (object1: GameObject, object2: GameObject) => { if (Layer.type == "tilelayer") {
if (Layer.phaserLayer === undefined) {
throw new Error('phaserLayer of layer "' + Layer.name + '" is undefined');
}
this.physics.add.collider(this.CurrentPlayer, Layer.phaserLayer, (object1: GameObject, object2: GameObject) => {
//this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name) //this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name)
}); });
Layer.setCollisionByProperty({collides: true}); Layer.phaserLayer.setCollisionByProperty({collides: true});
if (DEBUG_MODE) { if (DEBUG_MODE) {
//debug code to see the collision hitbox of the object in the top layer //debug code to see the collision hitbox of the object in the top layer
Layer.renderDebug(this.add.graphics(), { Layer.phaserLayer.renderDebug(this.add.graphics(), {
tileColor: null, //non-colliding tiles tileColor: null, //non-colliding tiles
collidingTileColor: new Phaser.Display.Color(243, 134, 48, 200), // Colliding tiles, collidingTileColor: new Phaser.Display.Color(243, 134, 48, 200), // Colliding tiles,
faceColor: new Phaser.Display.Color(40, 39, 37, 255) // Colliding face edges faceColor: new Phaser.Display.Color(40, 39, 37, 255) // Colliding face edges
}); });
} }
}); //});
}
}
} }
createCurrentPlayer(){ createCurrentPlayer(){

View File

@ -4,6 +4,8 @@
* Represents the interface for the Tiled exported data structure (JSON). Used * Represents the interface for the Tiled exported data structure (JSON). Used
* when loading resources via Resource loader. * when loading resources via Resource loader.
*/ */
import TilemapLayer = Phaser.Tilemaps.TilemapLayer;
export interface ITiledMap { export interface ITiledMap {
width: number; width: number;
height: number; height: number;
@ -81,6 +83,7 @@ export interface ITiledMapTileLayer {
* Draw order (topdown (default), index) * Draw order (topdown (default), index)
*/ */
draworder?: string; draworder?: string;
phaserLayer?: TilemapLayer;
} }
export interface ITiledMapObjectLayer { export interface ITiledMapObjectLayer {

View File

@ -0,0 +1,22 @@
import {ITiledMap, ITiledMapLayer} from "./ITiledMap";
/**
* Flatten the grouped layers
*/
export function flattenGroupLayersMap(map: ITiledMap) {
let flatLayers: ITiledMapLayer[] = [];
flattenGroupLayers(map.layers, '', flatLayers);
return flatLayers;
}
function flattenGroupLayers(layers : ITiledMapLayer[], prefix : string, flatLayers: ITiledMapLayer[]) {
for (const layer of layers) {
if (layer.type === 'group') {
flattenGroupLayers(layer.layers, prefix + layer.name + '/', flatLayers);
} else {
const layerWithNewName = { ...layer };
layerWithNewName.name = prefix+layerWithNewName.name;
flatLayers.push(layerWithNewName);
}
}
}

View File

@ -1,44 +0,0 @@
import {ITiledMap, ITiledMapLayer} from "./ITiledMap";
/**
* Iterates over the layers of a map, flattening the grouped layers
*/
export class LayersIterator implements IterableIterator<ITiledMapLayer> {
private layers: ITiledMapLayer[] = [];
private pointer: number = 0;
constructor(private map: ITiledMap) {
this.initLayersList(map.layers, '');
}
private initLayersList(layers : ITiledMapLayer[], prefix : string) {
for (const layer of layers) {
if (layer.type === 'group') {
this.initLayersList(layer.layers, prefix + layer.name + '/');
} else {
const layerWithNewName = { ...layer };
layerWithNewName.name = prefix+layerWithNewName.name;
this.layers.push(layerWithNewName);
}
}
}
public next(): IteratorResult<ITiledMapLayer> {
if (this.pointer < this.layers.length) {
return {
done: false,
value: this.layers[this.pointer++]
}
} else {
return {
done: true,
value: null
}
}
}
[Symbol.iterator](): IterableIterator<ITiledMapLayer> {
return new LayersIterator(this.map);
}
}

View File

@ -10,6 +10,7 @@ import { OpenTabEvent } from "./Api/Events/OpenTabEvent";
import { GoToPageEvent } from "./Api/Events/GoToPageEvent"; import { GoToPageEvent } from "./Api/Events/GoToPageEvent";
import { OpenCoWebSiteEvent } from "./Api/Events/OpenCoWebSiteEvent"; import { OpenCoWebSiteEvent } from "./Api/Events/OpenCoWebSiteEvent";
import { LayerEvent } from "./Api/Events/LayerEvent"; import { LayerEvent } from "./Api/Events/LayerEvent";
import { SetPropertyEvent } from "./Api/Events/setPropertyEvent";
interface WorkAdventureApi { interface WorkAdventureApi {
sendChatMessage(message: string, author: string): void; sendChatMessage(message: string, author: string): void;
@ -27,6 +28,7 @@ interface WorkAdventureApi {
removeBubble() : void; removeBubble() : void;
showLayer(layer: string) : void; showLayer(layer: string) : void;
hideLayer(layer: string) : void; hideLayer(layer: string) : void;
setProperty(layerName: string, propertyName: string, propertyValue: string | number | boolean | undefined): void;
} }
declare global { declare global {
@ -107,6 +109,16 @@ window.WA = {
} as LayerEvent } as LayerEvent
}, '*'); }, '*');
}, },
setProperty(layerName: string, propertyName: string, propertyValue: string | number | boolean | undefined): void {
window.parent.postMessage({
'type' : 'setProperty',
'data' : {
'layerName' : layerName,
'propertyName' : propertyName,
'propertyValue' : propertyValue
} as SetPropertyEvent
}, '*');
},
disablePlayerControls(): void { disablePlayerControls(): void {
window.parent.postMessage({ 'type': 'disablePlayerControls' }, '*'); window.parent.postMessage({ 'type': 'disablePlayerControls' }, '*');
}, },

View File

@ -1,10 +1,12 @@
import "jasmine"; import "jasmine";
import {Room} from "../../../src/Connexion/Room"; import {Room} from "../../../src/Connexion/Room";
import {LayersIterator} from "../../../src/Phaser/Map/LayersIterator"; import {flattenGroupLayersMap} from "../../../src/Phaser/Map/LayersFlattener";
import {ITiledMapLayer} from "../../../src/Phaser/Map/ITiledMap";
describe("Layers iterator", () => { describe("Layers flattener", () => {
it("should iterate maps with no group", () => { it("should iterate maps with no group", () => {
const layersIterator = new LayersIterator({ let flatLayers:ITiledMapLayer[] = [];
flatLayers = flattenGroupLayersMap({
"compressionlevel": -1, "compressionlevel": -1,
"height": 2, "height": 2,
"infinite": false, "infinite": false,
@ -47,14 +49,15 @@ describe("Layers iterator", () => {
}) })
const layers = []; const layers = [];
for (const layer of layersIterator) { for (const layer of flatLayers) {
layers.push(layer.name); layers.push(layer.name);
} }
expect(layers).toEqual(['Tile Layer 1', 'Tile Layer 2']); expect(layers).toEqual(['Tile Layer 1', 'Tile Layer 2']);
}); });
it("should iterate maps with recursive groups", () => { it("should iterate maps with recursive groups", () => {
const layersIterator = new LayersIterator({ let flatLayers:ITiledMapLayer[] = [];
flatLayers = flattenGroupLayersMap({
"compressionlevel": -1, "compressionlevel": -1,
"height": 2, "height": 2,
"infinite": false, "infinite": false,
@ -139,7 +142,7 @@ describe("Layers iterator", () => {
}) })
const layers = []; const layers = [];
for (const layer of layersIterator) { for (const layer of flatLayers) {
layers.push(layer.name); layers.push(layer.name);
} }
expect(layers).toEqual(['Group 1/Group 3/Tile3', 'Group 1/Group 3/Tile2', 'Group 1/Group 2/Tile1']); expect(layers).toEqual(['Group 1/Group 3/Tile3', 'Group 1/Group 3/Tile2', 'Group 1/Group 2/Tile1']);

View File

@ -19,17 +19,20 @@
})); }));
</script> </script>
<div> <div>
<label for="show/hideLayer">Layer Name : </label><input type="checkbox" id="show/hideLayer" name="visible" value="show" checked> <label for="show/hideLayer">Metadata Layer : </label><input type="checkbox" id="show/hideLayer" name="visible" value="show" checked>
</div> </div>
<script> <script>
document.getElementById('show/hideLayer').onclick = () => { document.getElementById('show/hideLayer').onclick = () => {
if (document.getElementById('show/hideLayer').checked) { if (document.getElementById('show/hideLayer').checked) {
WA.showLayer('LayerName'); WA.showLayer('Metadata');
} }
else { else {
WA.hideLayer('LayerName'); WA.hideLayer('Metadata');
} }
} }
</script> </script>
<script>
WA.setProperty('start', 'openWebsite', 'https://www.wikipedia.org/');
</script>
</body> </body>
</html> </html>