//
// Clear class for PTC 2.0 C++ API (HERMES INTERFACE PACKAGE)
// Copyright (c) 1998 Glenn Fiedler (ptc@gaffer.org)
// This source code is licensed under the GNU LGPL
//

// include files
#include <memory.h>
#include "Clear.h"
#include "Color.h"
#include "Error.h"
#include "Format.h"




Clear::Clear()
{ 
    // initialize hermes
    if (!Hermes_Init()) throw Error("could not initialize hermes");

    // static default format
    static Format default_format;

    // default current format
    m_format = &default_format;

    // create hermes clearer instance
    m_handle = Hermes_ClearerInstance();

    // check hermes clearer instance
    if (!m_handle) throw Error("could not create hermes clearer instance"); 
}


Clear::~Clear()
{ 
    // return the clearer instance
    Hermes_ClearerReturn(m_handle);

    // free hermes
    Hermes_Done();
}




void Clear::request(const Format &format)
{ 
    // cast from const format to hermes format pointer
    HermesFormat *hermes_format = const_cast<HermesFormat*>(&format.m_format);

    // request surface clear for this format
    if (!Hermes_ClearerRequest(m_handle,hermes_format)) throw Error("unsupported clear format");

    // update current format
    *m_format = format;
}




void Clear::clear(void *pixels,int x,int y,int width,int height,int pitch,const Color &color)
{ 
    #ifdef __DEBUG__

        //
        // This checking is performed only when __DEBUG__ is defined,
        // and can be used to track down errors early caused by passing
        // null pointers to the clear function.
        //
        // Even though technically clear should never recieve a null
        // pointer, we provide a check here to assist in debugging
        // just in case it ever does!
        //

        // check pixels pointer
        if (!pixels) throw Error("null pixels pointer in clear");

    #else

        // In release build no checking is performed for the sake of efficiency.

    #endif

    // check format type
    if (m_format->direct())
    {
        // check color type
        if (!color.direct()) throw Error("direct pixel formats can only be cleared with direct color");

        // setup clear color
        int32 r = (int32) ( color.r() * 255.0f );
        int32 g = (int32) ( color.g() * 255.0f );
        int32 b = (int32) ( color.b() * 255.0f );
        int32 a = (int32) ( color.a() * 255.0f );

        // perform the clearing
        Hermes_ClearerClear(m_handle,pixels,x,y,width,height,pitch,r,g,b,a);
    }
    else
    {
        // check color type
        if (!color.indexed()) throw Error("indexed pixel formats can only be cleared with indexed color");

        // perform the clearing
        Hermes_ClearerClear(m_handle,pixels,x,y,width,height,pitch,0,0,0,color.index());
    }
}
