sketch_200210a

sketch_200210a.pde


final int MAX_TRIAL = 1000;

int[] nVerticesList;
Star[] starList;

color[] palette;

void setup() {
  size(800, 800);
  nVerticesList = new int[] {5, 6, 8, 13};
  palette = selectPalette();
  initStarList();
  noLoop();
}

void initStarList() {
  
  starList = new Star[100];
  
  for (int k = 0; k < starList.length; k++) {
    int trial = 0;
    while (trial < MAX_TRIAL) {
      int n = nVerticesList[(int)random(nVerticesList.length)];
      float r = random(24.0, 256.0);
      float x = random(-width / 2.0, width / 2.0);
      float y = random(-height / 2.0, height / 2.0);
      Star newStar = new Star(n, new PVector(x, y), r);
      
      if (!intersects(starList, newStar)) {
        starList[k] = newStar;
        break;
      }
      
      trial++;
    }
    
    if (trial == MAX_TRIAL) {
      starList[k] = new Star(0, new PVector(0.0, 0.0), -1.0);
    }
  }
}

void draw() {
  translate(width / 2.0, height / 2.0);
  
  background(palette[0]);
  strokeWeight(1.5);
  
  for (Star star : starList) {
    pushMatrix();
    fill(0);
    noStroke();
    translate(width / 100.0, height / 100.0);
    star.draw();
    popMatrix();
    
    fill(palette[1]);
    noStroke();
    star.draw();
  }

  filter(BLUR, 0.7);
}

void mousePressed() {
  palette = selectPalette();
  initStarList();
  redraw();
}

void keyReleased() {
  saveFrame(String.format("frames/%s", timestamp("Project", ".png")));
}

static final String timestamp(final String name, final String ext) {
  return name + "-" + year() + nf(month(), 2) + nf(day(), 2) +
    "-" + nf(hour(), 2) + nf(minute(), 2) + nf(second(), 2) + ext;
}

color[] selectPalette() {
  // {bg, fg}
  color[][] palettes = new color[][] {
    {color(255, 0, 0), color(255)},
    {color(16, 16, 255), color(255)},
    {color(0x8A, 0xC3, 0x2B), color(0xDE, 0x40, 0x97)},
    {color(0x1F, 0xA2, 0xE5), color(0xFF, 0x9E, 0x50)},
  };
  return palettes[(int)random(palettes.length)];
}

class Star {
  int n;
  PVector pos;
  float r;
  Star(int n, PVector pos, float r) {
    this.n = n;
    this.pos = pos;
    this.r = r;
  }
  
  void draw() {
    if (r < 0.0) {
      return;
    }
    
    pushMatrix();
    translate(this.pos.x, this.pos.y);
    beginShape();
    for (int k = 0; k < this.n * 2; k++) {
      float t = TWO_PI * k / (float)(this.n * 2);
      float s = (k % 2 == 0 ? this.r : this.r / 2.0);
      float x = s * cos(t - HALF_PI);
      float y = s * sin(t - HALF_PI);
      
      vertex(x, y);
    }
    endShape(CLOSE);
    popMatrix();
  }
}

boolean intersects(Star[] stars, Star newStar) {
  for (Star star : stars) {
    if (star != null) {
      PVector diffVec = PVector.sub(star.pos, newStar.pos);
      float d = diffVec.mag();
      
      if (d < star.r + newStar.r) {
        return true;
      }
    }
  }
  return false;
}