Cache and recycle diagram for performance

This commit is contained in:
Wuzzy 2023-10-20 13:27:31 +02:00
parent 7cab828e5a
commit 5a566efea6

View File

@ -160,8 +160,11 @@ function putAxes(context) {
context.stroke();
}
// Cache diagram object for performance boost
let cachedVoronoiDiagram = null;
function getVoronoiDiagram() {
function getVoronoiDiagram(recalculate) {
if ((cachedVoronoiDiagram === null) || recalculate) {
let pad = 10;
let vbbox = {xl: LIMIT_MIN-pad, xr: LIMIT_MAX+pad, yt: LIMIT_MIN-pad, yb: LIMIT_MAX+pad};
let sites = []
@ -169,8 +172,18 @@ function getVoronoiDiagram() {
sites.push(biomePointToVoronoiPoint(p));
}
let voronoi = new Voronoi();
let diagram = voronoi.compute(sites, vbbox);
let diagram = null;
if (cachedVoronoiDiagram && recalculate) {
diagram = cachedVoronoiDiagram;
// This should improve performance
voronoi.recycle(diagram);
}
diagram = voronoi.compute(sites, vbbox);
cachedVoronoiDiagram = diagram;
return diagram;
} else {
return cachedVoronoiDiagram;
}
}
function getDrawContext() {
@ -183,11 +196,11 @@ function drawInit() {
context.scale(voronoiCanvas.width/(LIMIT_MAX-LIMIT_MIN), voronoiCanvas.height/(LIMIT_MAX-LIMIT_MIN));
context.translate(-LIMIT_MIN, -LIMIT_MIN);
}
function draw() {
function draw(recalculate) {
let context = getDrawContext();
context.fillStyle = "#FFFFFF";
context.fillRect(DRAW_MIN, DRAW_MIN, DRAW_MAX-DRAW_MIN, DRAW_MAX-DRAW_MIN);
let diagram = getVoronoiDiagram();
let diagram = getVoronoiDiagram(recalculate);
//let colors = shuffleArray(cellColors);
let colors = cellColors;
for (let c=0; c<diagram.cells.length; c++) {
@ -228,13 +241,10 @@ function draw() {
context.stroke();
}
console.log("---");
for (let p=0; p<biomePoints.length; p++) {
if (p === biomeSelector.selectedIndex) {
console.log("SEL"+p)
context.fillStyle = pointColorSelected;
} else {
console.log("NONSEL"+p)
context.fillStyle = pointColor;
}
putPoint(context, biomePoints[p]);
@ -258,7 +268,7 @@ function rewriteBiomeSelector() {
}
biomeSelector.onchange = function() {
draw();
draw(false);
}
addBiomeButton.onclick = function() {
@ -274,7 +284,7 @@ addBiomeButton.onclick = function() {
biomeSelector.append(newElem);
newElem.selected = "selected";
draw();
draw(true);
}
removeBiomeButton.onclick = function() {
if (biomeSelector.selectedOptions.length === 0) {
@ -298,7 +308,7 @@ removeBiomeButton.onclick = function() {
biomeSelector.options[newIndex].selected = "selected";
}
draw();
draw(true);
}
</script>