Recently I've been looking at Povray, pyprocessing, and cfdg (version 3.0) as tools for creating digital images. I have branched two separate blogs where I mainly explore jruby + processing and processing.py

Sunday, 18 September 2011

Cheap and cheerful voronoi generator, vanilla processing

honya posted a cheap a cheerful voronoi sketch up on openprocessing. I had a bit go at some "optimisations" in vanilla processing.
import java.util.Random;

float[] xarray = {};
float[] yarray = {};
int cellCount = 0;
int[] hues = {};
PImage img;
Random generator;

void setup() {
  size(600, 600);
  img = createImage(width, height, RGB);
  background(0);
  img.loadPixels();
  generator = new Random(1223344);
  noStroke();
}

void draw() {
  for ( int x0=0; x0 < width && (xarray.length > 0); x0 = x0 + 1 ) {
    for ( int y0 = 0; y0 < height; y0 = y0 + 1 ) {
      int idx = 0;
      float dd;
      dd = distSquared(xarray[0], yarray[0], x0, y0);
      for ( int i = 1; i < cellCount; i++ ) {
        float d0 = distSquared(xarray[i], yarray[i], x0, y0);
        if ( dd > d0 ) {
          dd = d0;
          idx = i;
        }
      }
      img.pixels[y0 * width + x0] = hues[idx];
      img.updatePixels();
    }
  }
  image(img, 0, 0);
  for ( int i=0; i<xarray.length; i++ ) {
    rect(xarray[i], yarray[i], 5, 5);
  }
}

void mousePressed() {
  xarray = append(xarray, mouseX);
  yarray = append(yarray, mouseY);
  cellCount++;
  hues = append(hues, (generator.nextInt(255) << 16)|(generator.nextInt(255) << 8)|generator.nextInt(255));
}

void keyReleased() {
  if (key == 's' || key == 'S'){
  saveFrame("voronoi.png");
  }
}

/**
 Assumed to be more efficient than using builtin dist function (with a sqrt step)
 @param x0, x1 and y0, y1 float coordinates difference is the side of the right angle triangle
 @return the square of the hypotenuse
*/
 
float distSquared(float x0, float y0, float x1, float y1) {
  return (x0 - x1) * (x0 -x1) + (y0 - y1) * (y0 -y1);
}

No comments:

Post a Comment

Followers

Blog Archive

About Me

My photo
Pembrokeshire, United Kingdom
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2