feat: masks with noise :3

This commit is contained in:
cha0s 2021-03-19 12:49:17 -05:00
parent f88d70b3e5
commit f7e2856d8a

View File

@ -1,11 +1,15 @@
import {
Canvas,
Color,
Container,
Primitives,
Image,
Sprite,
} from '@avocado/graphics';
import {Rectangle, Vector} from '@avocado/math';
import {
noise,
Rectangle,
Vector,
Vertice,
} from '@avocado/math';
export default class TilesRenderer {
@ -21,7 +25,7 @@ export default class TilesRenderer {
if (!slice) {
return undefined;
}
const mask = this.renderMask(rectangle, renderer);
const mask = this.renderMask(rectangle);
const size = Rectangle.size(rectangle);
const {tileSize} = this.tileset;
if (mask) {
@ -71,39 +75,76 @@ export default class TilesRenderer {
return image;
}
renderMask(rectangle, renderer) {
renderMask(rectangle) {
const hulls = this.tiles.indexHulls(0);
if (!hulls.length > 0) {
return undefined;
}
const black = new Color(0, 0, 0);
const white = new Color(255, 255, 255);
const size = Rectangle.size(rectangle);
const {tileSize} = this.tileset;
const canvasSize = Vector.mul(size, tileSize);
const m = new Primitives();
m.drawRectangle(
Rectangle.compose([0, 0], canvasSize),
Primitives.lineStyle(white, 1),
Primitives.fillStyle(white),
);
const canvas = window.document.createElement('canvas');
[canvas.width, canvas.height] = canvasSize;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
for (let i = 0; i < hulls.length; ++i) {
const scaled = [];
for (let j = 0; j < hulls[i].length; j++) {
scaled.push(Vector.scale(hulls[i][j], 16));
}
m.drawPolygon(
scaled,
Primitives.lineStyle(black, 1),
Primitives.fillStyle(black),
);
scaled.push(Vector.scale(hulls[i][0], 16));
ctx.beginPath();
ctx.moveTo(scaled[0][0], scaled[0][1]);
for (let j = 0; j < scaled.length - 1; j++) {
const p0 = scaled[j + 0];
const p1 = scaled[j + 1];
let points = Vertice.bresenham(p0, p1);
if (
(p0[0] > p1[0] && points[0][0] < points[points.length - 1][0])
|| (p0[1] > p1[1] && points[0][1] < points[points.length - 1][1])
) {
points = points.reverse();
}
const u = Vector.scale(
Vector.fromRadians((Math.PI * 0.5) + Vector.toRadians(Vector.sub(p1, p0))),
2,
);
for (let k = 0; k < points.length; k++) {
const [x, y] = points[k];
const shift = Vector.add(
u,
Vector.scale(
Vector.mul(
[
noise(Vector.scale([x, y], 1)),
noise(Vector.scale([y, x], 1)),
],
(1 + noise(Vector.scale([x, y], 2))) / 2 < 0.2
? [
noise(Vector.scale([x, y], 30)),
noise(Vector.scale([y, x], 30)),
]
: [
noise(Vector.scale([x, y], 3)),
noise(Vector.scale([y, x], 3)),
],
),
6,
),
);
const [vx, vy] = Vector.add(
points[k],
shift,
);
ctx.lineTo(vx, vy);
}
}
ctx.closePath();
ctx.fill();
}
const canvas = new Canvas(canvasSize);
canvas.render(m, renderer);
const sprite = new Sprite(canvas.toImage());
canvas.destroy();
m.destroy();
return sprite;
return new Sprite(Image.from(canvas));
}
}