/* material.c */

#include <string.h>
#include "material.h"
#include "Memory.h"

#ifdef BETTER_MEMMAN
static STORAGE *materialStor = (STORAGE *)NULL;
#define NEWMATERIAL()  	(MATERIAL *)New(sizeof(MATERIAL), &materialStor)
#define DISPOSEMATERIAL(ptr) Dispose((unsigned char *)(ptr), &materialStor)
#else /*BETTER_MEMMAN*/
#define NEWMATERIAL()	(MATERIAL *)Alloc(sizeof(MATERIAL))
#define DISPOSEMATERIAL(ptr) Free((char *)ptr, sizeof(MATERIAL))
#endif /*BETTER_MEMMAN*/

MATERIAL defaultMaterial = {
                {1., 1., 1.},	/* Ka */
                {1., 1., 1.}, 	/* Kd */
                {1., 1., 1.},	/* Ks */
                {0., 0., 0.},	/* Ed */
                0,		/* Ns */
                "_default_material"	/* naam */ 
        };

MATERIAL *MaterialCreate(char *name, COLOR *Ka, COLOR *Kd, COLOR *Ks, COLOR *Ed, float Ns)
{
	MATERIAL *m;

	m = NEWMATERIAL();
	m->Ka = *Ka;
	m->Kd = *Kd;
	m->Ks = *Ks;
	m->Ed = *Ed;
	m->Ns = Ns;
	
	m->name = Alloc(strlen(name) + 1);
	sprintf(m->name, "%s", name);

	return m;
}

void MaterialDestroy(MATERIAL *material)
{
	if (material->name) Free(material->name, strlen(material->name)+1);
	DISPOSEMATERIAL(material);
}

MATERIAL *MaterialDuplicate(MATERIAL *material)
{
	MATERIAL *newmaterial;

	newmaterial = NEWMATERIAL();
	*newmaterial = *material;

	if (material->name) {
		newmaterial->name = Alloc(strlen(material->name) + 1);
		sprintf(newmaterial->name, "%s", material->name);
	}

	return newmaterial;
}

void MaterialCopy(MATERIAL *src, MATERIAL *dest)
{
	if (dest->name) Free(dest->name, strlen(dest->name)+1);

	*dest = *src;

	if (src->name) {
		dest->name = Alloc(strlen(src->name)+1);
		sprintf(dest->name, "%s", src->name);
	} 
}

void MaterialPrint(FILE *out, MATERIAL *material)
{
	fprintf(out, "material '%s': ", material->name);
	fprintf(out, "Ka = ("); COLORPrint(out, material->Ka); fprintf(out, "), ");
	fprintf(out, "Kd = ("); COLORPrint(out, material->Kd); fprintf(out, "), ");
	fprintf(out, "Ks = ("); COLORPrint(out, material->Ks); fprintf(out, "), ");
	fprintf(out, "Ed = ("); COLORPrint(out, material->Ed); fprintf(out, "), ");
	fprintf(out, "Ns = %g\n", material->Ns);
}

