//////////////////////////////////////////////////////////////////////////////
//
// Asura_Chunk_ResourceFile_PS2_StrippedHierSkin.cpp
//
// Created by Morgan Parry.
//
// Copyright (c) 2002 Rebellion. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////

// I N C L U D E S ///////////////////////////////////////////////////////////

#include "Core/Asura.h"

// This file's header.
#include "ChunkSystem/Asura_Chunk_ResourceFile_PS2_StrippedHierSkin.h"

// Engine independent.
#include "Debugging/Asura_Logfile.h"
#include "ChunkSystem/Asura_Chunk_ResourceFile.h"
#include "Core/Asura_Handle.h"
#include "FileAccess/Asura_FileAccess.h"

// Engine platform-specific.
#include "Animation/Asura_PS2_Hierarchy.h"
#include "Animation/Asura_PS2_SkinTypes.h"
#include "Core/Asura_PlatformBasics.h"

// C L A S S   I M P L E M E N T A T I O N S /////////////////////////////////

bool Asura_Chunk_ResourceFile_PS2_StrippedHierSkin::Process( Asura_Handle hFile )
{
    // At the moment, we don't cope with any versions except the current one
    // at all. If it's too new, we don't know how; if it's old, the change
    // will always be so major that coping with old data is a huge amount of
    // work.
	if( ASURA_PS2_HIERSKIN_CUR_VERSION_NUMBER != Version )
    {
        if( ASURA_PS2_HIERSKIN_CUR_VERSION_NUMBER < Version )
        {
	        Asura_Assert( false, "This hierarchical skin's exported data is newer than the build you're using. Please update your build." );
        }
        else
        {
	        Asura_Assert( false, "This hierarchical skin data is out of date and will render with this version of the code. Please re-export the relevant data." );
        }
        return false;
    }

    // Read in name.
    u_int uSkinNameSizeInInts;
    const char* szSkinName = Asura_FileAccess::ReadString( hFile, NULL, &uSkinNameSizeInInts );

    // Allocate buffer for data.
    // (MP - 19.09.2002) Ensure buffer is cache-aligned to speed loading.
    const u_int uRemainingBytes = FileSize - (uSkinNameSizeInInts << 2);
    const u_int uCacheAlignedBytes = (((uRemainingBytes + 63) >> 6) << 6);
    void* pvBuffer = Asura_AllocateAlign( uCacheAlignedBytes, ASURA_ALIGN_64_BYTE );
    if( !pvBuffer )
    {
        Asura_OutputToDebugger_Retail(( "ERROR: Out of memory; couldn't allocate buffer for stripped hier skin data." ));
        return false;
    }

    // Read data in.
    Asura_FileAccess::ReadData( hFile, Asura_PS2_UncachedMem(pvBuffer), uRemainingBytes );

    // Store it.
    bool bOK = Asura_PS2_SkinSystem::AddHierSkinLOD( szSkinName, pvBuffer, uRemainingBytes );
    if( !bOK )
    {
        Asura_DeallocateAlign( pvBuffer );
    }

    return true;
}
