silphius/app/util/noise.js

57 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-07-10 16:48:36 -05:00
// import {Texture} from '@pixi/core';
// import {Sprite} from '@pixi/sprite';
import {bresenham, createNoise2D, TAU} from '@/util/math.js';
const simplex2D = createNoise2D();
// TODO - 3d noise around a circumference of length polygon perimeter
export function createLayerMask(layer) {
const {area, hulls, tileSize} = layer;
const canvas = window.document.createElement('canvas');
if (0 === hulls.length) {
return Texture.from(canvas);
}
[canvas.width, canvas.height] = [area.x * tileSize.x, area.y * tileSize.y];
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
for (let i = 0; i < hulls.length; ++i) {
const hull = [...hulls[i]];
hull.push(hull[0]);
ctx.beginPath();
ctx.moveTo(hull[0].x, hull[0].y);
for (let j = 0; j < hull.length - 1; j++) {
const p0 = hull[j + 0];
const p1 = hull[j + 1];
const points = bresenham(p0, p1);
const isReversed = (
(p0.x > p1.x && points[0].x < points[points.length - 1].x)
|| (p0.y > p1.y && points[0].y < points[points.length - 1].y)
);
for (
let k = (isReversed ? points.length - 1 : 0);
(isReversed ? k >= 0 : k < points.length);
k += (isReversed ? -1 : 1)
) {
const {x, y} = points[k];
const ANGLE_SCALE = 1000;
const WALK_SCALE = 10;
const MAGNITUDE = ((tileSize.x + tileSize.y) / 2) * simplex2D(x * 100, y * 100);
const w = simplex2D(x * WALK_SCALE, y * WALK_SCALE);
const r = TAU * simplex2D(x * ANGLE_SCALE, y * ANGLE_SCALE)
ctx.lineTo(
x + Math.cos(r) * w * MAGNITUDE,
y + -Math.sin(r) * w * MAGNITUDE,
);
}
}
ctx.closePath();
ctx.fill();
}
return Texture.from(canvas);
}