/*

layere - pics

return:
  0 - doslo k chybe
  1 - este nezacal
  2 - prebehol v poriadku
  3 - uz skoncil
*/

#include <iostream>
#include "api3ds.h"
#include "efekt.h"
#include "efekt_06.h"
#include "syncs.h"

extern int sync_id;
extern BOOL usefog;

int  efekt_06::init()
{
  cout << "Efekt 6 init ... ";
  start=TRUE;
  counter=0;
//->init
  for (int i=0;i<l_num;i++) l_fade[i]=0.0;
//<-
  cout << "ok!" << endl;
  return 1;
}

int  efekt_06::load()
{
   l_num=0;
   cout << "Loading efekt06 ... ";
// -> load

   FILE *stream=fopen(CFGNAME06,"r");
   if (stream==NULL) return 0;
   BOOL loading=TRUE;
   float loadin,loadout,loadins,loadouts;
   char loadname[30];
   while (loading)
     {
     fscanf(stream,"%f - %f %f %f  %s\n",&loadin,&loadout,&loadins,&loadouts,loadname);
     if (loadin==-1) loading=false;
       else
       {
       l_name[l_num]=loadname;
       l_in[l_num]=loadin;
       l_out[l_num]=loadout;
       if (loadins<1.0/60.0) l_ins[l_num]=1.0;
                        else l_ins[l_num]=1.0/(loadins*refresh);
       if (loadouts<1.0/60.0) l_outs[l_num]=1.0;
                         else l_outs[l_num]=1.0/(loadouts*refresh);
       l_num++;
       }
     }

   for (int i=0;i<l_num;i++)
     {
     l_tex[i]=texture_library->GetOrCreate(l_name[i]);
     }

// <-
    cout << "ok!"<<endl;
    return 1;
}

int  efekt_06::free()  //vrati 3 ako ok, 0 ak doslo k chybe
{
end=true;
// -> free

// <-
return 3;
}

void efekt_06::uprav(float &fade,float ins,float outs,float insp, float outsp)
{
float cntr=counter/refresh;
if ((cntr>=ins)&&(cntr<outs))
  {
  if (fade<1.0) fade+=insp;
       	   else fade=1.0;
 }
if (cntr>=outs)
  {
  if (fade>0.0) fade-=outsp;
     	   else fade=0.0;
  }
;
}

int  efekt_06::update()
{
id=Sync[GetSyncNum(float(counter)/float(refresh))].id;
// -> update
for (int i=0;i<l_num;i++)
  uprav(l_fade[i], l_in[i], l_out[i], l_ins[i], l_outs[i]);
// <-
return 1;
}

void efekt_06::showtex(float color)
{
  glBegin(GL_QUADS);
  glColor3f(color,color,color);
  glTexCoord2f( 1.0, 1.0);
    glVertex2f( 1.0, 1.0);
  glTexCoord2f( 0.0, 1.0);
    glVertex2f(-1.0, 1.0);
  glTexCoord2f( 0.0, 0.0);
    glVertex2f(-1.0,-1.0);
  glTexCoord2f( 1.0, 0.0);
    glVertex2f( 1.0,-1.0);
  glEnd();
}

int efekt_06::go(double t)
{
if (!start) if (!init()) return 0;
int cur_frm=(int)(t*refresh);

if (cur_frm>counter)
  while (counter<cur_frm)
    {
    counter++;
    update();
    }
//tu sa kresli->

float sm=0.0;
for (int i=0;i<l_num;i++) sm+=l_fade[i];
if (sm>0.0)
  {
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glEnable(GL_TEXTURE_2D);
  glDisable(GL_LIGHTING);
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE,GL_ONE);
  }
  else return 2;

for (int i=0;i<l_num;i++)
if (l_fade[i]>0.0)
  {
  (l_tex[i])->GL();
  showtex(l_fade[i]);
  }
//<-
return 2;
}