Files
wlgol/grid.c
T
arek 81a1b26842 perf(render): redraw on demand and only changed cells
Rendering used to clear the whole canvas and redraw every cell on
every frame callback (~60 fps) even though the simulation ticks at
20 tps and starts paused, keeping CPU usage at ~85% while idle.

Split simulation timing out of redraw() into the event loop and
render only when displayed content can have changed (tick, painting,
pattern placement, preview movement, grid-line toggle, resize);
idle frames commit only a new frame callback. Repaint incrementally
by diffing the grid against a rendered-state snapshot per row and
redrawing just the changed cells, with damage limited to the
repainted bounding box.

Idle CPU drops to ~1% of one core; running frames render at tick
rate (~20 fps) at microsecond cost. Adds grid_copy() snapshot
helper with tests and archives the optimize-render-on-demand change
with the new on-demand-rendering spec.
2026-11-08 20:11:55 +01:00

68 lines
1.9 KiB
C

#include "grid.h"
#include <stdlib.h>
#include <string.h>
void grid_init(grid_t *g, int cols, int rows) {
if (!g) return;
if (cols < 1) cols = 1;
if (rows < 1) rows = 1;
g->cols = cols;
g->rows = rows;
g->cells = calloc((size_t)cols * (size_t)rows, 1);
g->show_lines = 1;
}
void grid_free(grid_t *g) {
if (!g) return;
free(g->cells);
g->cells = NULL;
g->cols = 0;
g->rows = 0;
}
void grid_resize(grid_t *g, int new_cols, int new_rows) {
if (!g) return;
if (new_cols < 1) new_cols = 1;
if (new_rows < 1) new_rows = 1;
unsigned char *ncells = calloc((size_t)new_cols * (size_t)new_rows, 1);
if (!ncells) return;
int copy_cols = g->cols < new_cols ? g->cols : new_cols;
int copy_rows = g->rows < new_rows ? g->rows : new_rows;
for (int r = 0; r < copy_rows; r++) {
memcpy(ncells + (size_t)r * new_cols,
g->cells + (size_t)r * g->cols,
(size_t)copy_cols);
}
free(g->cells);
g->cells = ncells;
g->cols = new_cols;
g->rows = new_rows;
}
void grid_clear(grid_t *g) {
if (!g || !g->cells) return;
memset(g->cells, 0, (size_t)g->cols * (size_t)g->rows);
}
void grid_copy(grid_t *dst, const grid_t *src) {
if (!dst || !src || !src->cells) return;
if (dst->cols != src->cols || dst->rows != src->rows) {
grid_resize(dst, src->cols, src->rows);
}
if (dst->cols == src->cols && dst->rows == src->rows && dst->cells) {
memcpy(dst->cells, src->cells, (size_t)src->cols * (size_t)src->rows);
}
}
int grid_get(const grid_t *g, int c, int r) {
if (!g || !g->cells) return 0;
if (c < 0 || r < 0 || c >= g->cols || r >= g->rows) return 0;
return g->cells[(size_t)r * g->cols + c];
}
void grid_set(grid_t *g, int c, int r, int val) {
if (!g || !g->cells) return;
if (c < 0 || r < 0 || c >= g->cols || r >= g->rows) return;
g->cells[(size_t)r * g->cols + c] = val ? 1 : 0;
}