#include "m3dme.h"
#include "file.h"
#include "m3derror.h"
#include <string.h>
#include <errno.h>

namespace M3D {

M3DME::M3DME()
{
}


M3DME::~M3DME()
{
}


void M3DME::set_header( M3DME_Header * value )
{
	_header_ = value;
	memcpy(_header_->signature, M3DME_SIGNATURE, strlen(M3DME_SIGNATURE));
	_header_->version = M3DME_VER_MAGIC;
}

void M3DME::save( std::string fname )
{
	File fdesc ( fname.c_str(), true );
	//Скорректируем заголовок
	int base_offset = sizeof(M3DME_Header);
	_header_->vertex_data_offset = base_offset;
	_header_->index_data_offset = base_offset + _header_->vertex_data_size;
	
	//Сохраним заголовок
	if(write(fdesc, _header_, sizeof(M3DME_Header)) != sizeof(M3DME_Header))THROW ( strerror ( errno ) );
	
	//Сохраним данные
	if(write(fdesc, _vertex_data_, _header_->vertex_data_size) != _header_->vertex_data_size)
		THROW ( strerror ( errno ) );
	if(write(fdesc, _index_data_, _header_->index_data_size) != _header_->index_data_size)
		THROW ( strerror ( errno ) );
}

void M3DME::load( std::string fname )
{
	//Отобразим файл в память
	_mapped_file_.mmap ( fname.c_str() );
	char *mapped_file_pointer = _mapped_file_.get_pointer();

	_header_ = (M3DME_Header*)mapped_file_pointer;
	
	_vertex_data_ = (M3DME_Vertex_Data*)(mapped_file_pointer + _header_->vertex_data_offset);
	_index_data_ = (M3DME_Index_Data*)(mapped_file_pointer + _header_->index_data_offset);
}

}
