avocado-old/packages/topdown/layer-view.js
2019-09-29 13:19:57 -05:00

93 lines
2.7 KiB
JavaScript

import {EntityListView} from '@avocado/entity';
import {Container, Sprite} from '@avocado/graphics';
import {Vector} from '@avocado/math';
import {BodyView} from '@avocado/physics';
import {Layer} from './layer';
import {TilesRenderer} from './tiles-renderer';
export class LayerView extends Container {
constructor(layer, renderer) {
super();
this.entityListView = new EntityListView(layer.entityList);
this.layer = layer;
this.layerContainer = new Container();
this.renderer = renderer;
this.tileGeometryContainer = new Container();
this.tileGeometryViews = [];
// Handle entity add/remove.
layer.on('tileDataChanged', this.onLayerTileDataChanged, this);
this.onLayerTileDataChanged();
layer.on('tileGeometryChanged', this.onLayerTileGeometryChanged, this);
this.onLayerTileGeometryChanged();
layer.on('tilesetChanged', this.onLayerTilesetChanged, this);
this.onLayerTilesetChanged(layer.tileset, undefined);
this.addChild(this.layerContainer);
this.addChild(this.tileGeometryContainer);
this.addChild(this.entityListView);
}
destroy() {
super.destroy();
layer.off('entityAdded', this.onLayerEntityAdded);
layer.off('entityRemoved', this.onLayerEntityRemoved);
layer.off('tileDataChanged', this.onLayerTileDataChanged);
layer.off('tilesetChanged', this.onLayerTilesetChanged);
this.destroyTileGeometryBodies();
}
destroyTileGeometryBodies() {
for (const view of this.tileGeometryViews) {
view.destroy();
}
this.tileGeometryViews = [];
}
onLayerTileDataChanged() {
this.render();
}
onLayerTileGeometryChanged() {
this.destroyTileGeometryBodies();
for (const body of this.layer.tileGeometry) {
const bodyView = new BodyView(body);
this.tileGeometryViews.push(bodyView);
this.tileGeometryContainer.addChild(bodyView);
}
}
onLayerTilesetChanged(oldTileset, newTileset) {
if (oldTileset) {
oldTileset.off('imageChanged', this.onLayerTilesetImageChanged, this);
}
if (newTileset) {
newTileset.on('imageChanged', this.onLayerTilesetImageChanged, this);
}
this.onLayerTilesetImageChanged();
}
onLayerTilesetImageChanged() {
this.render();
}
render() {
this.layerContainer.removeAllChildren();
if (!this.renderer) {
return;
}
if (!this.layer.tileset) {
return;
}
if (Vector.isZero(this.layer.tiles.size)) {
return;
}
const tilesRenderer = new TilesRenderer(this.layer.tiles, this.layer.tileset);
const chunk = tilesRenderer.renderChunk(this.renderer);
const tilesSprite = new Sprite(chunk);
tilesSprite.anchor = [0, 0];
this.layerContainer.addChild(tilesSprite);
}
}