#include "ZGo.h"



//---- ZGoFader

ZGoFader::ZGoFader(ZGo *zgo, ZGoPARAMS *input, ZGoPARAMS *output)
{
  this->zgo = zgo;
  this->input = input->setInput(this);
  this->output = output->setOutput(this);

  this->fnType = new ZGoNAME(zgo, "ZGoFader");

  //  Parameters

  im1 = (ZGoIMAGE *)input->get("image1");
  im2 = (ZGoIMAGE *)input->get("image2");
  alpha = (ZGoREAL *)input->get("alpha");
  result = (ZGoIMAGE *)output->get("result");
}

void ZGoFader::process()
{
  int *buf1, *buf2, *rbuf;

  buf1 = im1->buf;
  buf2 = im2->buf;
  rbuf = result->buf;

  int r1, g1, b1, a1;
  int r2, g2, b2, a2;
  
  alpha->process();
  
  int a = (int)(255*alpha->value), aa = 255-a;

  if(a <= 0)
  {
    im1->process();

    int i, j, w, h;

    w = im1->w; if(w > result->w) w = result->w;
    h = im1->h; if(h > result->h) h = result->h;

    int o1 = 0, o2 = 0, o3 = 0;

    for(j=0; j<h; j++)
    {
      for(i=0; i<w; i++) rbuf[o3++] = buf1[o1++];

      o1 += im1->w - w;
      o3 += result->w - w;
    }
  }
  else if(a >= 255)
  {
    im2->process();

    int i, j, w, h;

    w = im2->w; if(w > result->w) w = result->w;
    h = im2->h; if(h > result->h) h = result->h;

    int o1 = 0, o2 = 0, o3 = 0;

    for(j=0; j<h; j++)
    {
      for(i=0; i<w; i++) rbuf[o3++] = buf2[o2++];

      o2 += im2->w - w;
      o3 += result->w - w;
    }
  }
  else
  {
    im1->process();
    im2->process();
    
    int i, j, w, h;

    w = im1->w; if(w > im2->w) w = im2->w; if(w > result->w) w = result->w;
    h = im1->h; if(h > im2->h) h = im2->h; if(h > result->h) h = result->h;

    int o1 = 0, o2 = 0, o3 = 0;
    int c;
    
    for(j=0; j<h; j++)
    {
      for(i=0; i<w; i++)
      {
        c = buf1[o1++]; a1 = (c>>24)&255; r1 = (c>>16)&255; g1 = (c>>8)&255; b1 = c&255;
        c = buf2[o2++]; a2 = (c>>24)&255; r2 = (c>>16)&255; g2 = (c>>8)&255; b2 = c&255;
        
        a1 = (a1*aa + a2*a)>>8;
        r1 = (r1*aa + r2*a)>>8;
        g1 = (g1*aa + g2*a)>>8;
        b1 = (b1*aa + b2*a)>>8;
        
        rbuf[o3++] = (a1<<24) + (r1<<16) + (g1<<8) + (b1);
      }

      o1 += im1->w - w;
      o2 += im2->w - w;
      o3 += result->w - w;
    }
  }
}


