import processing.core.*; 
import processing.xml.*; 

import java.applet.*; 
import java.awt.*; 
import java.awt.image.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
import java.text.*; 
import java.util.*; 
import java.util.zip.*; 
import java.util.regex.*; 

public class AtanTexOptimized extends PApplet {

 int SIZE = 400 * 400;

int pointNum = 5;

Point[] points = new Point[pointNum];

float mx = 0;
float mouse = 0;
int c = 0;
int inc = 0;
float a = 0;
float col = 0;
int[] oxp = new int[SIZE];
int[] oyp = new int[SIZE];
float[] angp = new float[SIZE*pointNum];

public void setup(){
  size(400, 400, P2D);
  
  // position some random points
  for (int i = 0; i<pointNum; i++) points[i] = new Point(random(width), random(height));
  
   // precalculate x, y and atan2 values
   for (int i = 0; i < SIZE; i++){
    oxp[i] = i / width;
    oyp[i] = i % width;
   
    for (int j = 0; j < points.length; j++){
      angp[inc] = atan2(oyp[i] - points[j].y, oxp[i] - points[j].x);
      inc++;
    }
  }
  
}


public void draw(){
  
  loadPixels();
   
  inc = 0;
  
  mouse += (mouseX - mouse) / 2;
  
  mx = 1 / (width / 2 - mouse + .000001f);
  
  for (int i = 0; i < SIZE; i++){

     col = 0;
     
     a = oxp[i]  * mx; //(oyp[i]&oxp[i]) * mx;
     
     // unrolled loop (pointnum = 7)
     col += Math.max(0,  Math.cos(angp[inc++] * a)) ; 
     col += Math.max(0,  Math.cos(angp[inc++] * a)) ;
     col += Math.max(0,  Math.cos(angp[inc++] * a)) ;
     col += Math.max(0,  Math.cos(angp[inc++] * a)) ;
     col += Math.max(0,  Math.cos(angp[inc++] * a)) ;
     
     
     col *= 25;
      
     c = (int) col;
     
     pixels[i] = 0xFF000000 | c << 16 | c << 8 | c;
  }
  updatePixels();
  
}

class Point{
 float x=0;
 float y=0; 
 
 Point(){};
 
 Point(float x, float y){
   this.x = x;
   this.y = y;
 }
}

  static public void main(String args[]) {
    PApplet.main(new String[] { "--bgcolor=#ffffff", "AtanTexOptimized" });
  }
}
