lnvis

nanovg lightning network visualizer
git clone git://jb55.com/lnvis
Log | Files | Refs | README | LICENSE

grid.c (1623B)


      1 
      2 #include "grid.h"
      3 #include <string.h>
      4 #include <assert.h>
      5 #include <stdio.h>
      6 
      7 
      8 static void remove_node_from_cell(struct cell *cell, struct node *node) {
      9 	struct node **n = NULL;
     10 
     11 	for (int i = 0; i < cell->node_count; i++) {
     12 		n = &cell->nodes[i];
     13 		if (node != *n)
     14 			continue;
     15 
     16 		// shortcut: reduce node count if it's the last node
     17 		if (i == cell->node_count-1) {
     18 			cell->node_count--;
     19 			assert(cell->node_count < CELL_MAX_ELEMS);
     20 			return;
     21 		}
     22 		else {
     23 			assert(i + 1 <= CELL_MAX_ELEMS);
     24 			int msize = sizeof(struct node *) * (cell->node_count - i - 1);
     25 			memmove(n, n + 1, msize);
     26 			cell->node_count--;
     27 			assert(cell->node_count < CELL_MAX_ELEMS);
     28 			return;
     29 		}
     30 	}
     31 
     32 	/* assert(!"expect to remove a node"); */
     33 }
     34 
     35 void update_grid_move_nodes(struct ln *ln) {
     36 	struct node *n = NULL;
     37 	struct cell *new_cell;
     38 
     39 	for (u32 i = 0; i < ln->node_count; i++) {
     40 		n = &ln->nodes[i];
     41 
     42 		int gx = ((double)(n->x / (double)ln->window_width)) * ln->grid_div;
     43 		int gy = ((double)(n->y / (double)ln->window_height)) * ln->grid_div;
     44 
     45 		// TODO: handle outside of grid?
     46 		if (gx > ln->grid_div || gy > ln->grid_div)
     47 			continue;
     48 
     49 		new_cell = &ln->grid[gy * ln->grid_div + gx];
     50 
     51 		// we've moved to a new cell
     52 		if (n->cell != new_cell) {
     53 			// can't move to new cell :[
     54 			if (new_cell->node_count == CELL_MAX_ELEMS)
     55 				continue;
     56 
     57 			// remove from old cell
     58 			if (n->cell)
     59 				remove_node_from_cell(n->cell, n);
     60 
     61 			// add to new cell
     62 			n->cell = new_cell;
     63 
     64 			/* printf("adding to cell (%d, %d) elems %d\n", */
     65 			/*        gx, gy, new_cell->node_count+1); */
     66 			new_cell->nodes[new_cell->node_count++] = n;
     67 		}
     68 	}
     69 }
     70 
     71 
     72 
     73