//=========================================================================
//#
//#  pfCAVEhead.cc                                     #####     
//#                                                   ##   ##
//#  Author(s): Paul Rajlich                          ##
//#  Email: prajlich@ncsa.uiuc.ed                     ##   ##
//#  Date created: Jul 8, 1998                         #####
//#
//#  Description: parallel vtk pipelines pfCAVE example
//#    based on medical1.cxx from vtk 2.0 distribution
//#
//=========================================================================

#include <pfcave.h>
#include <stdio.h>
#include <stdlib.h>
#include <Performer/pf/pfLightSource.h>
#include <Performer/pf/pfDCS.h>

#include "vtkMarchingCubes.h"
#include "vtkVolume16Reader.h"
#include "vtkExtractVOI.h"
#include "vtkOutlineFilter.h"

#include "vtkActorToPFTranslatorParallel.h"

static void initSharedVars();
static void initPF(pfChannel *, int, char **);
static void initVTK(int, char **);
static void initTranslatorParallels();
static void updateVTK();
static void updateUser();
static void split(int times);

// globals... each process has copy.
vtkMarchingCubes *shellExtractor;
vtkExtractVOI *extractVOI;
vtkActor *shellActor, *outlineActor;
vtkActorToPFTranslatorParallel *translator[2];

// shared vars;
pfDCS *dcs, *transDcs;
float *isoval, *step, *center, *bounds, *range;
int *doneInitVTK, *processCount;
float *rotH;

int main(int argc, char **argv) {

  if (argc < 2) {
    cout << "Usage: pfCAVEhead splits" << endl;
    cout << "  where splits is number of recursive subdivisions\n" << endl;
    cout << "ie. 0 results in 1 VTK pipeline" << endl;
    cout << "    1 results in 2 VTK pipelines" << endl;
    cout << "    2 results in 4 VTK pipelines" << endl;
    cout << "    3 results in 8 VTK pipelines" << endl;
    exit(0);
  } 

  pfInit();
  pfCAVEConfig(&argc, argv, NULL);
  initSharedVars();
  pfConfig();
  pfCAVEInitChannels();

  // stats
  if (CAVEConfig->Simulator)
    pfCAVEMasterChan()->getFStats()->setClass(PFSTATS_ALL^PFSTATSHW_ENGFXPIPE_FILL, PFSTATS_ON);
  else
    pfCAVEMasterChan()->getFStats()->setClass(PFSTATS_ALL, PFSTATS_OFF);

  // child process(es) will need to get at this node (to add geodes).
  dcs = new pfDCS();

  // Fork
  int childPid;

  if ((childPid = fork()) == -1) {
    perror("can't fork");
    exit(1);
  }
  else if (childPid == 0) { //child process... (VTK PIPELINE)
    cout << "child process: pid = " << getpid() << " parent pid = "
         << getppid() << endl;
    initVTK(argc, argv);

    split(atoi(argv[1])); 

    //int numPipelines = pow(2, atoi(argv[1]));

    //*processCount = *processCount + 1;
    //cout << *processCount << " vtk processes ready!" << endl;
    //while (*processCount < numPipelines) { sginap(1); }

    initTranslatorParallels();
    *doneInitVTK = *doneInitVTK+1;
    cout << *doneInitVTK << " translators ready!" << endl;

    while (!CAVEgetbutton(CAVE_ESCKEY)) {
      updateVTK();      

      // idea here is that translators are continually looking to re-execute
      translator[0]->Update();
      translator[1]->Update(); // but outline should not change
      sginap(5);
    }
  }
  else { // parent process... (PERFORMER main loop)
    cout << "parent process: pid = " << getpid() << " child pid = " 
         << childPid << endl;

    // wait for VTK to init first (so that bounds info is available)
    int numPipelines = pow(2, atoi(argv[1]));
    while (*doneInitVTK < numPipelines) { sginap(1); }
    
    initPF(pfCAVEMasterChan(), argc, argv);

    while (!CAVEgetbutton(CAVE_ESCKEY)) {
      updateUser();
      pfSync();
      pfCAVEPreFrame();
      pfFrame();
      pfCAVEPostFrame();
    }
    CAVEHalt();
    pfExit();
  }
  return 0;
}

static void initSharedVars() {
  center = (float *) pfMalloc(3*sizeof(float), pfGetSharedArena());
  bounds = (float *) pfMalloc(6*sizeof(float), pfGetSharedArena());
  range = (float *) pfMalloc(2*sizeof(float), pfGetSharedArena());
  doneInitVTK = (int *) pfMalloc(sizeof(int), pfGetSharedArena());
  *doneInitVTK = 0;
  processCount = (int *) pfMalloc(sizeof(int), pfGetSharedArena());
  *processCount = 0;

  isoval = (float *) pfMalloc(sizeof(float), pfGetSharedArena());
  *isoval = 0.0;
  step = (float *) pfMalloc(sizeof(float), pfGetSharedArena());
  *step = 1.0;

  rotH = (float *) pfMalloc(sizeof(float), pfGetSharedArena());
  *rotH = 0.0;
} 

static void updateUser() {
  if (CAVEBUTTON1) {
    *isoval = *isoval + (*step)/5.0;
    cout << "setting isoval to " << *isoval << endl;
  }
  if (CAVEBUTTON2) {
    *isoval = *isoval - (*step)/5.0;
    cout << "setting isoval to " << *isoval << endl;
  }
/****
  if (CAVEButtonChange(1) == -1) {
    *isoval = *isoval + (*step);
    cout << "setting isoval to " << *isoval << endl;
  }
  if (CAVEButtonChange(2) == -1) {
    *isoval = *isoval - (*step);
    cout << "setting isoval to " << *isoval << endl;
  }
  // smaller adjustment
  if (CAVEButtonChange(3) == -1) {
    *isoval = *isoval - (*step)/4.0;
    cout << "setting isoval to " << *isoval << endl;
  }
*****/

  if (CAVE_JOYSTICK_X < -0.3 || CAVE_JOYSTICK_X > 0.3) {
    *rotH = *rotH + 5.0*CAVE_JOYSTICK_X;
    transDcs->setRot(*rotH, 180.0, 0.0); 
  }
}

// Continually reset the iso value based on shared memory variable (isoval).
// This is ok because if *isoval has not changed, then SetValue() will
// not change the MTime (will not cause re-execution).
static void updateVTK() {
  shellExtractor->SetValue(0, *isoval);
}

static void initVTK(int argc, char **argv) {
  cout << "entering initVTK()..." << endl;

  // ****** setup vtk pipeline
  vtkVolume16Reader *volReader = vtkVolume16Reader::New();
  volReader->SetDataDimensions(64, 64);
  volReader->SwapBytesOn();
  volReader->SetFilePrefix("../../vtkdata/headsq/quarter");
  volReader->SetDataSpacing(3.2, 3.2, 1.5);
  volReader->SetImageRange(1, 93);
  volReader->Update(); // load so that we can get range...

  vtkStructuredPoints *vol = volReader->GetOutput();

  float *theRange;
  theRange = vol->GetScalarRange();
  // put range info into shared mem variables.
  range[0] = theRange[0];
  range[1] = theRange[1];
  cout << "range = " << range[0] << ".." << range[1] << endl;

  // set initial isoval
  *isoval = 500.0; 
  *step = (range[1]-range[0])/10.0; // step in increments of 10% of range
  cout << "step = " << *step << endl;

  // center and bounds... stored in shared mem.
  vol->GetCenter(center);
  vol->GetBounds(bounds);

  // volume of interest... will be used to do data decomp.
  extractVOI = vtkExtractVOI::New();
  extractVOI->SetInput(vol);
  int *dims = vol->GetDimensions();
  extractVOI->SetVOI(0, dims[0], 0, dims[1], 0, dims[2]);

  vtkOutlineFilter *outlineF = vtkOutlineFilter::New();
  outlineF->SetInput(extractVOI->GetOutput());

  vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New();
  outlineMapper->SetInput(outlineF->GetOutput());
  outlineMapper->ScalarVisibilityOff();

  outlineActor = vtkActor::New();
  outlineActor->SetMapper(outlineMapper);
  outlineActor->GetProperty()->SetColor(0.7, 0.7, 0.7);

  shellExtractor = vtkMarchingCubes::New();
  shellExtractor->SetInput(extractVOI->GetOutput());
  shellExtractor->SetValue(0, *isoval);

  vtkPolyDataMapper *shellMapper = vtkPolyDataMapper::New();
  shellMapper->SetInput(shellExtractor->GetOutput());
  shellMapper->ScalarVisibilityOff(); // use overall color

  shellActor = vtkActor::New();
  shellActor->SetMapper(shellMapper);
  shellActor->GetProperty()->SetColor(1.0, 1.0, 1.0);
  // ****** end vtk stuff

  cout << "exiting initVTK()." << endl;
}

void initTranslatorParallels() {
  cout << "entering initTranslatorParallels()." << endl;

  translator[0] = vtkActorToPFTranslatorParallel::New(shellActor);
  translator[0]->Update();

  translator[1] = vtkActorToPFTranslatorParallel::New(outlineActor);
  translator[1]->Update();

  // need to lock this!
  dcs->addChild(translator[0]->GetGeode());
  dcs->addChild(translator[1]->GetGeode()); 

  cout << "exiting initTranslatorParallels()." << endl;
}

static void initPF(pfChannel *chan, int, char **) {
  cout << "entering initPF()..." << endl;
  pfScene *scene;
  pfGeoState *gstate;
  pfLightSource *light;
  scene = new pfScene;
  gstate = new pfGeoState;
  gstate->setMode(PFSTATE_ENLIGHTING, PF_ON);
  gstate->setMode(PFSTATE_CULLFACE, PFCF_OFF);
  scene->setGState(gstate);
  
  light = new pfLightSource;
  light->setColor(PFLT_DIFFUSE, 1.0, 1.0, 1.0);
  light->setAmbient(0.0, 0.0, 0.0);
  scene->addChild(light);

  // create pfDCS that will center/scale the geometry
  float scaleFactor = 5.0/(bounds[1] - bounds[0]);

  // order in DCS is S*R*T. Centered vtk geometry (see below) will be
  // scaled, rotated, then translated.
  transDcs = new pfDCS();
  transDcs->setScale(scaleFactor, scaleFactor, scaleFactor);
  transDcs->setRot(*rotH, 180.0f, 0.0);
  transDcs->setTrans(0.0, 5.0, 5.0);

  // center vtk geometry
  dcs->setTrans(-center[0], -center[1], -center[2]);

  transDcs->addChild(dcs);
  scene->addChild(transDcs);

  chan->setScene(scene);
  cout << "exiting initPF()." << endl;
}

// function that recursively forks off new processes. The idea is that
// you have a process with a VTK pipeline in it. After the fork, the
// resulting parent process takes half of the data and the child
// process takes the other half. The splitting of the data is done
// through the use of the vtkExtractVOI filter.
static void split(int times) {
  // already been split...
  if (times <= 0) {
    int v[6];
    extractVOI->GetVOI(v);
    cout << "voi: " << v[0] << " " << v[1] << " " << v[2]
         << " " << v[3] << " " << v[4] << " " << v[5] << endl;
    extractVOI->Update(); // cause VOI to be extracted
    extractVOI->GetInput()->ReleaseData(); // release full dataset
  }
  else {
    int v[6];
    extractVOI->GetVOI(v);
    int diffx = v[1] - v[0];
    int diffy = v[3] - v[2];
    int diffz = v[5] - v[4];

    // Fork
    int childPid;

    if ((childPid = fork()) == -1) {
      perror("can't fork"); 
      exit(1);
    }
    else if (childPid == 0) { //child process
      cout << "split(): child process: pid = " << getpid() << " parent pid = "
           << getppid() << endl;

      if (diffz > diffx && diffz > diffy) 
        extractVOI->SetVOI(v[0], v[1], v[2], v[3], v[4], v[4]+diffz/2);
      else if (diffy > diffx && diffy > diffz)
        extractVOI->SetVOI(v[0], v[1], v[2], v[2]+diffy/2, v[4], v[5]);
      else
        extractVOI->SetVOI(v[0], v[0]+diffx/2, v[2], v[3], v[4], v[5]);
    }
    else { // parent process...
      cout << "split(): parent process: pid = " << getpid() << " child pid = "
            << childPid << endl;

      if (diffz > diffx && diffz > diffy) 
        extractVOI->SetVOI(v[0], v[1], v[2], v[3], v[4]+diffz/2, v[5]);
      else if (diffy > diffx && diffy > diffz)
        extractVOI->SetVOI(v[0], v[1], v[2]+diffy/2, v[3], v[4], v[5]);
      else
        extractVOI->SetVOI(v[0]+diffx/2, v[1], v[2], v[3], v[4], v[5]);
    }
    split(times-1);
  }
}
