///////////////////////////////////////////////////////////////////////////////
// $Id: Sprite.cxx,v 1.1 1995/01/12 02:09:54 bmott Exp $
///////////////////////////////////////////////////////////////////////////////
//
// Sprite.cxx - Sprite class
//
//
// Bradford W. Mott
// Copyright (C) 1994
// November 11,1994
//
///////////////////////////////////////////////////////////////////////////////
// $Log: Sprite.cxx,v $
// Revision 1.1  1995/01/12  02:09:54  bmott
// Initial revision
//
///////////////////////////////////////////////////////////////////////////////

#include "Sprite.hxx"
#include "UIApplication.hxx"

// Raw sprite header
typedef struct {
  unsigned char widthMSB;
  unsigned char widthLSB;
  unsigned char heightMSB;
  unsigned char heightLSB;
  unsigned char numberOfColors;
  unsigned char transparentColor;
  unsigned char lengthOfName;
} RawSprite;

///////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////
Sprite::Sprite(unsigned char* spriteData) 
{
  RawSprite rawSprite;

  // get the sprite's header
  memcpy(&rawSprite, spriteData, sizeof(rawSprite));
  spriteData += sizeof(rawSprite);

  // Get the width and height of the sprite
  myWidth = (((int)rawSprite.widthMSB) << 8) + (int)rawSprite.widthLSB;
  myHeight = (((int)rawSprite.heightMSB) << 8) + (int)rawSprite.heightLSB;

  // Build a pixel mapping table
  unsigned long PixelMapping[256];
  unsigned char pal[256][3];
  memcpy(pal, spriteData, rawSprite.numberOfColors*3);
  spriteData += rawSprite.numberOfColors*3;

  for(int t=0;t<rawSprite.numberOfColors;++t)
  {
    XColor color;

    color.red = (short)(pal[t][0]) << 8;
    color.green = (short)(pal[t][1]) << 8;
    color.blue = (short)(pal[t][2]) << 8;

    XAllocColor(application->display(), application->colormap(), &color);
    PixelMapping[t] = color.pixel;
  }

  // Allocate space for the sprite data
  myData = new unsigned char[myWidth * myHeight]; 

  for(t=0; t < myWidth*myHeight; ++t)
  {
    unsigned char i;
    i = *spriteData;
    spriteData += 1;
    myData[t] = PixelMapping[i];
  }

  // Create my x image
  myImage = XCreateImage(application->display(), application->visual(),
      8, ZPixmap, 0, (char*)myData, myWidth, myHeight, 8, myWidth); 

  // Get my name
  myName = new char[rawSprite.lengthOfName + 1];
  memcpy(myName, spriteData, rawSprite.lengthOfName);
  spriteData += rawSprite.lengthOfName;
  myName[rawSprite.lengthOfName] = '\0';
}

///////////////////////////////////////////////////////////////////////////////
// Destructor
///////////////////////////////////////////////////////////////////////////////
Sprite::~Sprite()
{
  // Free memory that holds my name
  delete[] myName;

  // Free image data
  delete[] myData;

  // Free the XImage structure
  myImage->data = 0;
  XDestroyImage(myImage);
}

