// newton fractal globals

PShader       nf_myShader;
float         nf_previousTime = 0.0;
boolean       nf_mouseDragged = false;
PVector       nf_lastMousePosition;
float         nf_mouseClickState = 0.0;

void setup_newton_fractal()
{
  // Load the shader file from the "data" folder
  nf_myShader = loadShader("defaultShader.cpp");
  
  // We assume the dimension of the window will not change over time, 
  // therefore we can pass its values in the setup() function  
  nf_myShader.set("iResolution", float(width), float(height), 0.0);
  
  nf_lastMousePosition = new PVector(float(mouseX),float(mouseY));
  
  // needed cuz noFill means no shader
  fill(255);
  noStroke();
}

void draw_newton_fractal()
{
  // shader playback time (in seconds)
  float currentTime = millis()/1000.0 - myTime;
  nf_myShader.set("iTime", currentTime);
  
  // render time (in seconds)
  float timeDelta = currentTime - nf_previousTime;
  nf_previousTime = currentTime;
  nf_myShader.set("iDeltaTime", timeDelta);
  
  // shader playback frame
  nf_myShader.set("iFrame", frameCount);
  
  // mouse pixel coords. xy: current (if MLB down), zw: click
  if(mousePressed) { 
    nf_lastMousePosition.set(float(mouseX),float(mouseY));
    nf_mouseClickState = 1.0;
  } else {
    nf_mouseClickState = 0.0;
  }
  nf_myShader.set( "iMouse", nf_lastMousePosition.x, nf_lastMousePosition.y, nf_mouseClickState, nf_mouseClickState);

  // Set the date
  // Note that iDate.y and iDate.z contain month-1 and day-1 respectively, 
  // while x does contain the year (see: https://www.shadertoy.com/view/ldKGRR)
  float timeInSeconds = hour()*3600 + minute()*60 + second();
  nf_myShader.set("iDate", year(), month()-1, day()-1, timeInSeconds );  

  // This uniform is undocumented so I have no idea what the range is
  nf_myShader.set("iFrameRate", frameRate);

  // Apply the specified shader to any geometry drawn from this point
  shader(nf_myShader);
  // Draw the output of the shader onto a rectangle that covers the whole viewport.
  fill(255);
  rect(0, 0, width, height);
  
  resetShader();
}
