Dozed12 / p5.voronoi

A Voronoi library for p5.js
MIT License
128 stars 18 forks source link

Possibility to change centroids? #4

Closed sofian closed 3 years ago

sofian commented 3 years ago

Is it possible in the current library to change (eg. through mouseDragged()) the centroids of the cells? I have tried by accessing the sites using the diagram (voronoiGetDiagram()) but it does not work (plus I am guessing the diagram is readonly).

sofian commented 3 years ago

If not, I would like to add that functionality but I wouldn't mind getting some hints on how to proceed.

Dozed12 commented 3 years ago

I assume by centroid of the cell you mean the site. Note that the site of a cell is not necessarily its centroid too. voronoiGetDiagram() is the structure produced after voronoi(...) is ran. It contains some extra internal information which can be useful, it is readonly.

It's not the most elegant system but you could use voronoiSite() and voronoiRemoveSite() to move around the site on the diagram. You would click on a site and keep track of its position, when mouseDragged() gets called you would use voronoiRemoveSite() to remove the previous site position and use voronoiSite() to add it back at the new position under the mouse. You would have to recalculate the voronoi(...) diagram every instance.

sofian commented 3 years ago

Yes, sorry, I meant site, indeed. Yes I had thought about that idea of removing and adding a site. I just tried it. It sort-of works but there is still something strange going on. Looks like there is a problem with indexes (cellIds): https://editor.p5js.org/sofian/sketches/L6sEYOdZ8

sofian commented 3 years ago

I seem to have been able to fix the issue by adding the following function to the library:

p5.prototype.voronoiMoveSite = function(id, newX, newY) {
    sites[id].x = newX;
    sites[id].y = newY;
    cellColors[id][0] = newX;
    cellColors[id][1] = newY;
  }