/*   Copyright 2005,2006 Paweł Niegowski
*
*    This file is part of Fenrir.
*
*    Fenrir 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.
*
*    Fenrir 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 Fenrir; if not, write to the Free Software
*    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
#include "main.h"
#include "sky.h"
#include "map.h"

BITMAP *sky, *buf_sky, *sky_tex;
int coords_x[640][80];
int coords_y[640][80];
int horizon_color;
PALETTE sky_palette;

void sky_init()
{
 sky = create_bitmap(128,128);
 clear_bitmap(sky);
 sky_tex = load_bitmap("gfx/sky_day.bmp",sky_palette);
 horizon_color = 81;

 float step_x,distance,fx,fy;
 int mask = 127;
 float view_height = 100.0;
 float x_scale = 32.0;
 float y_scale = 32.0;
 view_height *= y_scale;
 int max_x = 320, max_y = 40;
 if(!conf_lowres)
 { max_x *= 2; max_y *= 2; x_scale *= 2; y_scale *= 2;}
 buf_sky = create_bitmap(max_x,max_y);
 clear_bitmap(buf_sky);

 for(int i = 0; i < max_y; i++)
 {
  distance = view_height / (max_y-i + 10);
  step_x = distance / x_scale;
  fx = -max_x / 2 * step_x;
  fy = distance;

  for(int j = 0; j < max_x; j++)
  {
   coords_x[j][i] = ((int)fx)&mask;
   coords_y[j][i] = ((int)fy)&mask;
   fx += step_x;
  }
 }
}

void sky_cleanup()
{
 destroy_bitmap(sky);
 destroy_bitmap(buf_sky);
 destroy_bitmap(sky_tex);
}

int scroll = 0;

void sky_update()
{
 if(!conf_sky || map_flags & MAPFLAGC_INDOOR) return;
 clear_to_color(sky,game_state==GAME_LOGIN?1:0);
 if(game_state != GAME_LOGIN)
 {
  blit(sky_tex,sky,0,0,0,scroll,128,128);
  blit(sky_tex,sky,0,0,0,scroll-128,128,128);
 }
 scroll++;
 if(scroll > 128) scroll = 0;
}


void sky_mode7_draw()
{
 if(game_state == GAME_LOGIN) return;
 if(map_flags && MAPFLAGC_INDOOR)
 clear(buf_sky);
 else
  for(int i = 0; i < buf_sky->w; i++)
   for(int j = 0; j < buf_sky->h; j++)
    buf_sky->line[j][i] = sky->line[ coords_y[i][j] ][ coords_x[i][j] ];
  blit(buf_sky,conf_triplebuffer?page[!current_page]:screen,0,0,0,0,buf_sky->w,buf_sky->h);
}
