/******************************************************************************
    Xplanet 0.43 - render an image of the earth into an X window
    Copyright (C) 1999 Hari Nair <hari@alumni.caltech.edu>

    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.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

******************************************************************************/

#include <fstream.h>
#include <iostream.h>
#include <limits.h>
#include <stdlib.h>

#include <Imlib.h>

#include "location.h"
#include "options.h"
#include "planet.h"
#include "text.h"
#include "util.h"
#include "xplanet.h"

int window_width, window_height;          // w and h of display window
int image_width, image_height;            // w and h of image
Display *disp = NULL;
int screen_num;
Window root, window;

unsigned char *elevation = NULL;

extern ImlibImage *compute_ortho (ImlibImage *image_merc, 
				 ImlibImage *image_ortho);

static ImlibData *id;
static ImlibImage *imday;
static ImlibImage *imnight;

#ifdef __sparc__
int texture_width=512, texture_height=512;
#else
int texture_width=1024, texture_height=1024;
#endif

unsigned char *rgb_data = NULL;

void add_cloud (ImlibImage *imcloud, ImlibImage *image, float shade);

void 
init_display ()
{
  disp = XOpenDisplay (NULL);
  if ( disp == NULL )
    { 
      cerr << "Can't open display\n";
      exit (EXIT_FAILURE);
    }

  screen_num = DefaultScreen (disp);
  int screen_width = DisplayWidth (disp, screen_num);
  int screen_height = DisplayHeight (disp, screen_num);

  root = RootWindow (disp, screen_num);
  
  if (opts.display == ROOT) 
    {
      window_width = screen_width;
      window_height = screen_height;
    }
  else  // ANIMATE, OUTPUT, or WINDOW
    {
      window_width = opts.window_width;
      window_height = opts.window_height;
    }

  switch (opts.display)
    {
    case WINDOW:
      if (window_width > screen_width) 
	{
	  window_width = screen_width;
	  cerr << "Width set to " << window_width << endl;
	}
      if (window_height > screen_height) 
	{
	  window_height = screen_height;
	  cerr << "Height set to " << window_height << endl;
	}
      /*
	Check if we've already specified a window to use.  
	If not, create one.
      */
      if (opts.XID)              // Running xplanet from xplanetbg
	window = opts.XID;
      else
	{
	  int x=0, y=0;
	  window = XCreateSimpleWindow (disp, root, x, y, window_width,
					window_height, 4, 
					WhitePixel (disp, screen_num),
					BlackPixel (disp, screen_num));
	  
	  XTextProperty windowName;
	  if (opts.title != NULL) 
	    XStringListToTextProperty (&opts.title, 1, &windowName);
	  else
	    XStringListToTextProperty (&versionstring, 1, &windowName);
	  XSetWMName (disp, window, &windowName);
	}      
      break;
    case ANIMATE:
    case OUTPUT:
    case ROOT:
      window = root;
      break;
    }

  // (x,y) of the globe's center
  if (opts.centx < 0 || opts.centy < 0)
    {
      opts.centx = window_width / 2;
      opts.centy = window_height / 2;
    }

  // convert opts.radius from percent to pixels
  opts.radius = int (0.01 * opts.radius * window_height);
}

void 
read_image ()
{
  ImlibInitParams *params=NULL;
  id = Imlib_init_with_params (disp, params);  

  if (opts.day == NULL) 
    {
      opts.day = new char [300];
      strcpy (opts.day, prefix);
      strcat (opts.day, current_body);
      strcat (opts.day, defaultmapext);
    }
  imday = Imlib_load_image (id, opts.day);

  if (imday == NULL) 
    {
      cerr << "Can't load image file " << opts.day << endl;
      exit (EXIT_FAILURE);
    }

  if (opts.mode == MERCATOR)
    {
      if (opts.display == ANIMATE)
	{
	  image_width = texture_width;
	  image_height = texture_height;
	}
      else
	{
	  image_width = window_width;
	  image_height = window_height;
	}
      imday = Imlib_clone_scaled_image (id, imday, image_width, image_height);
    } 
  else 
    {
      image_width = imday->rgb_width;
      image_height = imday->rgb_height;
    }

  if (imday == NULL) 
    {
      cerr << "Can't create day image\n";
      exit (EXIT_FAILURE);
    }

  if (opts.night != NULL) 
    {
      imnight = Imlib_load_image (id, opts.night);
      if (imnight == NULL) 
	{
	  cerr << "Can't load night image file " << opts.night << endl;
	  exit (EXIT_FAILURE);
	}
    }	  
  else
    imnight = imday;
  
  imnight = Imlib_clone_scaled_image (id, imnight, 
				      image_width, image_height);
  
  if (imnight == NULL) 
    {
      cerr << "Can't create night image\n";
      exit (EXIT_FAILURE);
    }
  
  if (opts.night == NULL)
    for (int i = 0; i < 3 * image_width * image_height; i++) 
      *(imnight->rgb_data + i) = ((unsigned char) 
				  (*(imnight->rgb_data + i) * opts.shade));
  
  if (opts.cloud != NULL) 
    {
      ImlibImage *imcloud = Imlib_load_image (id, opts.cloud);
      if (imcloud == NULL) 
	{
	  cerr << "Can't load cloud image file " << opts.cloud << endl;
	  exit (EXIT_FAILURE);
	}
      imcloud = Imlib_clone_scaled_image (id, imcloud, image_width, 
					  image_height);
      if (imcloud == NULL) 
	{
	  cerr << "Can't create cloud image\n";
	  exit (EXIT_FAILURE);
	}
      add_cloud (imcloud, imnight, opts.shade); 
      add_cloud (imcloud, imday, 1.0);

      Imlib_destroy_image (id, imcloud);
    }

  if (opts.dem != NULL) 
    {
      ImlibImage *imdem = Imlib_load_image (id, opts.dem);
      if (imdem == NULL) 
	{
	  cerr << "Can't load digital elevation map file " << opts.dem << endl;
	  exit (EXIT_FAILURE);
	}
      imdem = Imlib_clone_scaled_image (id, imdem, image_width, image_height);
  
      if (imdem == NULL) 
	{
	  cerr << "Can't create digital elevation map\n";
	  exit (EXIT_FAILURE);
	}
      
      // assume digital elevation map is made of 1 byte values
      elevation = new unsigned char[image_width*image_height];

      for (int i = 0; i < image_height * image_width; i++)
	elevation[i] = imdem->rgb_data[3*i];
      Imlib_destroy_image (id, imdem);
    }	  
  
}

/******************************************************************************
add_cloud: overlays the input cloud image onto the input image.

The brightness of each pixel in each color is also taken to be its
opacity.  The brightness of the pixel in the output image is the
weighted average of the cloud pixel and the input image pixel.

******************************************************************************/
void 
add_cloud (ImlibImage *imcloud, ImlibImage *image, float shade)
{
  for (int i = 0; i < 3 * image_height * image_width; i++) 
    {
      float opacity = float (imcloud->rgb_data[i] / 255.);
      image->rgb_data[i] = (unsigned char) 
	(opacity * (shade * imcloud->rgb_data[i]) 
	 + (1-opacity) * (image->rgb_data[i]));
    }
}

void
add_grid ()
{
  int i, j;
  int lonstep = 4 * opts.grid;
  int lonspac = image_width / lonstep;
  int gstep = image_height / (2 * opts.gridspace);
  if (gstep < 1) gstep = 1;
  for (i = 0; i < image_height; i+=gstep) 
    for (j = 0; j < lonstep; j++)
      memset (imday->rgb_data + 3 * (i * image_width + j * lonspac), 255, 3);
  
  int latstep = 2 * opts.grid;
  int latspac = image_height / latstep;
  gstep = image_width / (4 * opts.gridspace);
  if (gstep < 1) gstep = 1;
  for (i = 0; i < latstep; i++)
    for (j = 0; j < image_width; j+=gstep)
      memset (imday->rgb_data + 3 * (i * latspac * image_width + j), 255, 3);
}

void 
create_merc () 
{
  int i, j, ii, jj;

  if (opts.fuzz == 0) 
    {
      double del_lat = M_PI / image_height; 
      // number of rows at top and bottom that are in polar day/night
      int ipolar = abs (int (sunlat/del_lat));

      if (sunlat < 0) // North pole is dark
	memcpy (imday->rgb_data, imnight->rgb_data, 3*ipolar*image_width);
      else            // South pole is dark
	memcpy (imday->rgb_data+3*((image_height-ipolar)*image_width),
		imnight->rgb_data+3*((image_height-ipolar)*image_width), 
		3*ipolar*image_width);

      // subsolar longitude pixel column - this is where it's noon
      int inoon = int (image_width/2 * (sunlon / M_PI - 1)); 
      while (inoon < 0) inoon += image_width;
      while (inoon >= image_width) inoon -= image_width;

      for (i = ipolar; i < image_height - ipolar; i++) 
	{ 
	  float lat = M_PI_2 - (i+0.5) * del_lat;
	  float length_of_day, H0;

	  /* compute length of daylight as a fraction of the day at 
	     the current latitude.  Based on Chapter 42 of Astronomical 
	     Formulae for Calculators by Meeus. */

	  H0 = tan (lat) * tan (sunlat);
	  if (H0 > 1) length_of_day = 1;
	  else if (H0 < -1) length_of_day = 0;
	  else length_of_day = 1 - (acos (H0) / M_PI);

	  // ilight = number of pixels from noon to the terminator
	  int ilight = int (image_width/2 * length_of_day + 0.5);  

	  /* idark = number of pixels that are in darkness at the current 
	     latitude */
	  int idark = image_width - 2 * ilight;

	  // start at the evening terminator
	  int start_row = i * image_width;
	  int ipos = inoon + ilight;

	  for (j = 0; j < idark; j++) 
	    {
	      if (ipos >= image_width) ipos -= image_width;
	      memcpy(imday->rgb_data+3*(start_row + ipos),
		     imnight->rgb_data+3*(start_row + ipos), 3);
	      ipos++;
	    }
	} 
    }
  else  // opts.fuzz > 0
    {
      ImlibImage *imtemp = Imlib_clone_image (id, imday);
      double del_lon_deg = 360. / image_width;
      double del_lat_deg = 180. / image_height; 

      location sunloc (sunlat/deg_to_rad, sunlon/deg_to_rad, 1, NULL);
      sunloc.spher_to_rect ();

      float border = sin (opts.fuzz * deg_to_rad);

      // break the image up into a 100x100 grid
      int istep = image_width/100;
      int jstep = image_height/100;
      if (istep == 0) istep = 1; 
      if (jstep == 0) jstep = 1;
      for (j = 0; j < image_height; j += jstep)
	for (i = 0; i < image_width; i += istep)
	  {
	    double lat = 90 - (j + 0.5) * del_lat_deg;
	    double lon = (i + 0.5) * del_lon_deg - 180;
	    location point (lat, lon, 1, NULL);
	    point.spher_to_rect ();
	    double x = point.dot (sunloc);
	    if (x < -2*border)  // NIGHT
	      {
		for (jj = 0; jj < jstep; jj++) 
		  {
		    if ((j + jj) >= image_height) break;
		    memcpy(imtemp->rgb_data + 3 * ((j+jj) * image_width + i),
			   imnight->rgb_data + 3 * ((j+jj) * image_width + i), 
			   3*istep);
		  }
	      }
	    else if (x < 2*border ) // TWILIGHT
	      {
		for (jj = 0; jj < jstep; jj++)
		  {
		    int ilat = j + jj;
		    if (ilat >= image_height) break;
		    for (ii = 0; ii < istep; ii++)
		      {
			int ilon = i + ii;
			if (ilon >= image_width) ilon -= image_width;
			double lat = 90 - (ilat + 0.5) * del_lat_deg;
			double lon = (ilon + 0.5) * del_lon_deg - 180;
			location point (lat, lon, 1, NULL);
			point.spher_to_rect ();
			float dayweight = ((border + point.dot(sunloc))
					   /(2*border));
			int ipos = 3 * (ilat * image_width + ilon);
			if (dayweight < 0)
			  memcpy(imtemp->rgb_data + ipos,
				 imnight->rgb_data + ipos, 3);
			else if (dayweight < 1) 
			  {
			    dayweight = 0.5 * (1 - cos (dayweight * M_PI));
			    for (int k = 0; k < 3; k++)
			      {
				imtemp->rgb_data[ipos + k] = 
				  ((unsigned char) 
				   (dayweight * imday->rgb_data[ipos + k]
				    + ((1 - dayweight) 
				       * imnight->rgb_data[ipos + k])));
			      }
			  }
		      } // for ( ii = ... ) block
		  }     // for ( jj = ... ) block
	      }         // end TWILIGHT block
	  }             // for ( i = ... ) block
      imday = Imlib_clone_image (id, imtemp);
    }                   // end (opts.fuzz > 0) block
  
  // Don't need night image any more
  Imlib_destroy_image (id, imnight);

  if (opts.grid > 0) add_grid ();

  if (opts.display == ANIMATE) 
    {
      imday = Imlib_clone_scaled_image (id, imday, texture_width, 
					texture_height);
      rgb_data = new unsigned char[texture_width * texture_height*3];
      Imlib_flip_image_horizontal (id, imday);
      memcpy (rgb_data, imday->rgb_data, 3 * texture_width * texture_height);
    }
}

void 
create_ortho () 
{
  ImlibImage *image_ortho = NULL; 
  if (opts.background != NULL)
    {
      image_ortho = Imlib_load_image (id, opts.background);
      if (image_ortho == NULL)
	cerr << "Can't load image file " << opts.background << endl;
      else
	image_ortho = Imlib_clone_scaled_image (id, image_ortho, 
						window_width, window_height);
    }

  if (image_ortho == NULL)
    {
      image_ortho = 
	Imlib_clone_scaled_image (id, imday, window_width, window_height);
  
      // Set the image to black
      memset (image_ortho->rgb_data, 0, 3 * window_width * window_height);
      
      // add random stars
      int num_stars = int (window_width * window_height * opts.star_den);
      
      srandom ((unsigned int) opts.time.tv_sec);
      for (int i = 0; i < num_stars; i++)
	{
	  int j = int (random() % window_width);
	  int k = int (random() % window_height);
	  int brightness = int (random() % 256);
	  memset (image_ortho->rgb_data + 3 * (k * window_width + j), 
		  brightness, 3);
	}
    }

  imday = Imlib_clone_image (id, compute_ortho (imday, image_ortho));
}

void
swap_planes (ImlibImage *image)
{
  char tmp;

  for (int i = 0; i < window_height * window_width; i++) 
    {
      // Swap the red and blue values
      tmp = image->rgb_data[3*i];
      image->rgb_data[3*i] = image->rgb_data[3*i+2]; 
      image->rgb_data[3*i+2] = tmp;
    }
}

void 
render_image ()
{
  if (opts.obslon && opts.mode == MERCATOR)
    {
      ImlibImage *imtemp = Imlib_clone_image (id, imday);
      int istart = (int) (image_width * (1 - opts.obslon / (2*M_PI)));
      if (istart >= image_width) istart -= image_width;
      for (int i = 0; i < image_height; i++)
	{
	  memcpy (imday->rgb_data + 3 * i * image_width, 
		  imtemp-> rgb_data + 3 * ((i+1) * image_width - istart), 
		  3*istart);
	  memcpy (imday->rgb_data + 3 * (istart + i * image_width), 
		  imtemp-> rgb_data + 3 * (i * image_width), 
		  3*(image_width - istart));
	}
    }

  Imlib_render (id, imday, window_width, window_height);
  Pixmap p = Imlib_copy_image (id, imday);

  if (opts.label || opts.markers) 
    {
      if (init_text (p))
	{
	  if (opts.label) draw_label ();
	  if (opts.markers) read_markers ();
	}
    }
  
  if (opts.display == OUTPUT)
    {
      Pixmap mask = 0;       // not used
      ImlibSaveInfo *info = NULL;
      imday = Imlib_create_image_from_drawable (id, p, mask, 0, 0, 
						window_width, window_height);

      if (opts.swap) swap_planes (imday);
	
      Imlib_save_image (id, imday, opts.output, info);
      ifstream check (opts.output);
       if (check.bad ()) cerr << "Can't create " << opts.output << endl;
      check.close ();
    }
  else 
    {
      if (opts.display == WINDOW) 
	{
	  // Set the icon pixmap
	  Imlib_render (id, imday, 56, 56);
	  Pixmap icon_pixmap = Imlib_copy_image (id, imday);
	  XWMHints *wm_hints = XAllocWMHints();
	  wm_hints->flags = IconPixmapHint;
	  wm_hints->icon_pixmap = icon_pixmap;
	  XSetWMHints (disp, window, wm_hints);
	  XMapWindow (disp, window);
	}
      else // root window
	{
	  if (opts.trans)
	    {
	      /* 
		 Set the background pixmap for Eterms and aterms.  Most of
		 this is taken from the Esetroot source code.
	      */
	      
	      Atom prop_root = XInternAtom (disp, "_XROOTPMAP_ID", True);
	      Atom prop_esetroot = XInternAtom (disp, "ESETROOT_PMAP_ID", 
						True);
	      
	      if (prop_root != None && prop_esetroot != None)
		{
		  Atom type;
		  int format;
		  unsigned long length, after;
		  unsigned char *data_root;
		  unsigned char *data_esetroot;
		  
		  XGetWindowProperty (disp, window, prop_root, 0L, 1L, 
				      False, AnyPropertyType, &type, 
				      &format, &length, &after, &data_root);
		  if (type == XA_PIXMAP) 
		    {
		      XGetWindowProperty (disp, window, prop_esetroot, 
					  0L, 1L, False, AnyPropertyType, 
					  &type, &format, &length, 
					  &after, &data_esetroot);
		      if (data_root && data_esetroot && type == XA_PIXMAP 
			  && (*((Pixmap *) data_root) 
			      == *((Pixmap *) data_esetroot)))
			XKillClient (disp, *((Pixmap *) data_root));
		    }
		}
	      
	      prop_root = XInternAtom (disp, "_XROOTPMAP_ID", False);
	      prop_esetroot = XInternAtom(disp, "ESETROOT_PMAP_ID", False);
	      
	      XChangeProperty (disp, window, prop_root, XA_PIXMAP, 32, 
			       PropModeReplace, (unsigned char *) &p, 1);
	      XChangeProperty (disp, window, prop_esetroot, XA_PIXMAP, 32, 
			       PropModeReplace, (unsigned char *) &p, 1);
	      XSetCloseDownMode (disp, RetainPermanent);
	    }
	}
      
      XSetWindowBackgroundPixmap (disp, window, p);
      XClearWindow (disp, window);
      XFlush (disp);

      if (opts.display == WINDOW && !opts.XID)
	{
	  Atom wmDeleteWindow = XInternAtom (disp, "WM_DELETE_WINDOW", 
					     False);
	  XSetWMProtocols (disp, window, &wmDeleteWindow, 1);
	  
	  // now listen for a delete event
	  XEvent report;
	  while (1)
	    {
	      XNextEvent (disp, &report);
	      if (report.type == ClientMessage && 
		  (unsigned int) report.xclient.data.l[0] == wmDeleteWindow) 
		exit (EXIT_SUCCESS);
	    }
	}
    } 
}
