avocado-old/packages/topdown/tiles.js

73 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-03-25 19:03:34 -05:00
import {compose} from '@avocado/core';
import {Rectangle, Vector} from '@avocado/math';
const decorate = compose(
Vector.Mixin('size', 'width', 'height', {
default: [0, 0],
}),
);
class TilesBase {
fromJSON(json) {
if (json.size) {
this.size = json.size;
}
if (json.data) {
this.data = json.data;
}
return this;
}
get rectangle() {
return Rectangle.compose([0, 0], this.size);
}
2019-03-25 20:49:16 -05:00
setTileAt(x, y, tile) {
const index = y * this.width + x;
if (index < 0 || index >= this.data.length) {
return;
}
this.data[index] = tile;
}
2019-03-25 19:03:34 -05:00
slice(rectangle) {
const tilesRectangle = this.rectangle;
2019-03-25 20:49:42 -05:00
// Get intersection.
2019-03-25 19:03:34 -05:00
if (!Rectangle.intersects(rectangle, tilesRectangle)) {
return [];
}
2019-03-25 20:49:42 -05:00
let [x, y, sliceWidth, sliceHeight] = Rectangle.intersection(
rectangle,
tilesRectangle,
);
// No muls in the loop.
let sliceRow = y * sliceWidth;
const dataWidth = this.width;
let dataRow = y * dataWidth;
// Copy slice.
const slice = new Array(sliceWidth * sliceHeight);
for (let j = 0; j < sliceHeight; ++j) {
for (let i = 0; i < sliceWidth; ++i) {
slice[sliceRow + x] = this.data[dataRow + x];
2019-03-25 19:03:34 -05:00
x++;
}
2019-03-25 20:49:42 -05:00
sliceRow += sliceWidth;
dataRow += dataWidth;
x -= sliceWidth;
2019-03-25 19:03:34 -05:00
}
return slice;
}
tileAt(x, y) {
2019-03-25 20:49:57 -05:00
return this.data[y * this.width + x];
2019-03-25 19:03:34 -05:00
}
toJSON() {
}
}
export class Tiles extends decorate(TilesBase) {}