//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2021 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
// 
#include "MeshGammaFilter.hpp"
#include <Progress.hpp>
#include <omp.h>

namespace mgx 
{
  bool MeshGammaFilter::run(Mesh* mesh, float gamma)
  {
    // Check gamma
    if(gamma <= 0)
      throw(QString("Gamma must be positive"));
  
    // Get signal bounds
    Point2f sb = mesh->signalBounds();
    float sr = sb.y() - sb.x();
  
    // If the signal range is empty throw an error
    if(sr <= 0)
      throw(QString("Empty signal bounds"));
  
    // Get active vertices. These are selected vertices, or all if none selected
    const std::vector<vertex>& vs = mesh->activeVertices();
  
    // Start the progress bar
    progressStart(QString("Running Gamma Filter on mesh %1").arg(mesh->userId()), 0);
  
    #pragma omp parallel for
    for(size_t i = 0; i < vs.size(); ++i) {
      vertex v = vs[i];
      float s = trim((v->signal - sb.x()) / sr, 0.0f, 1.0f);
      s = pow(s, gamma);
      // set the signal and rescale to original range
      v->signal = s * sr + sb.x();
    }
  
    // Tell MorphoGraphX to update the triangle color
    mesh->updateTriangles();
  
    // Print message in status bar
    SETSTATUS(QString("Processed Gamma Filter on mesh %1").arg(mesh->userId()));
  
    return true;
  }
  REGISTER_PROCESS(MeshGammaFilter);
}
