/*--------------------------------------------------------------
  
   File        : pde_heatflow2D.cpp

   Description : A simple Heat flow on 2D images

   Author      : David Tschumperlé
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   -------------------------------------------------------------*/

#include "../CImg.h"

int main(int argc,char **argv) {
  cimg_usage("Perform a simple Heat Flow on 2D images");
  cimg_library::CImg<> img(cimg_option("-i","img/milla.ppm","Input image")), veloc(img,false);
  const double dt = cimg_option("-dt",1.0,"Adapting time step");
  img.
    noise(cimg_option("-ng",0.0,"Add gaussian noise"),0).
    noise(cimg_option("-nu",0.0,"Add uniform noise"),1).
    noise(cimg_option("-ns",0.0,"Add Salt&Pepper noise"),2);
  cimg_library::CImgDisplay profile(400,300,"Intensity Profile"), disp(img,"Heat flow 2D",0);
  cimg_library::CImgStats stats;
  CImg_3x3(I,float);
  float white[3]={255,255,255};

  for (int iter=0; !disp.closed && disp.key!=cimg_library::cimg::keyQ && disp.key!=cimg_library::cimg::keyESC; iter++) {
    cimg_mapV(img,k) cimg_map3x3(img,x,y,0,k,I) veloc(x,y,k) = Inc + Ipc + Icn + Icp - 4*Icc;
    stats = veloc.get_stats(0);
    const double xdt = dt/(stats.max-stats.min);
    img += veloc*xdt;
    cimg_library::CImg<>(img).draw_text(2,2,white,NULL,1,"iter = %d",iter).display(disp).wait(25);
    if (disp.mousex>=0) {
      const int
        mx = disp.mousex, my = disp.mousey,
        mnx = mx*profile.width/disp.width;
      const unsigned char red[3]={255,0,0}, green[3]={0,255,0}, blue[3]={0,0,255}, white[3]={255,255,255};
      cimg_library::CImg<unsigned char>(profile.width,profile.height,1,3,0).
        draw_graph(img.ref_line(my,0,0),red,0,0,255).
        draw_graph(img.ref_line(my,0,1),green,0,0,255).
        draw_graph(img.ref_line(my,0,2),blue,0,0,255).
        draw_line(mnx,0,mnx,profile.height-1,white,cimg_library::cimg::rol(0xFF00FF00,iter%32),0.5f).
        draw_text(2,2,white,NULL,1,"(x,y)=(%d,%d)",mx,my).        
        display(profile);
    }
    profile.resize();
    disp.resize(disp);
  }

  exit(0);
  return 0;
}
