#include "object.h"
#include "../lib/math.h"
#include "../lib/geometry.h"
#include "../platform.h"
#include "string.h"
#include "state.h"
#include "2d.h"


r_object r_object_create(u64 count, r_mesh **meshes, r_material **materials, v3 position, v3 rotation, v3 scale)
{
	r_object object;

	object.meshes = (r_mesh**)p_alloc(count * sizeof(r_mesh*));
	object.mesh_material = (r_material**)p_alloc(count * sizeof(r_material*));
	object.mesh_local_transform = (m4*)p_alloc(count * sizeof(m4));

	memcpy(object.meshes, meshes, count * sizeof(r_mesh*));
	memcpy(object.mesh_material, materials, count * sizeof(r_material*));
	for(u64 i = 0; i < count; i++)
		object.mesh_local_transform[i] = m4_identity;

	object.count = count;

	object.position = position;
	object.rotation = rotation;
	object.scale = scale;

	object.has_shadow = true;

	return object;
}

r_object r_object_allocate(u64 count)
{
	r_object object;

	object.meshes = (r_mesh**)p_alloc(count * sizeof(r_mesh*));
	object.mesh_material = (r_material**)p_alloc(count * sizeof(r_material*));
	object.mesh_local_transform = (m4*)p_alloc(count * sizeof(m4));

	for(u64 i = 0; i < count; i++)
		object.mesh_local_transform[i] = m4_identity;

	object.count = count;

	object.position = v3{0,0,0};
	object.rotation = v3{0,0,0};
	object.scale = v3{1,1,1};

	object.has_shadow = true;

	return object;
}

void r_object_destroy(r_object *object)
{
	p_free(object->mesh_material);
	p_free(object->meshes);
	p_free(object->mesh_local_transform);
	object->mesh_material = NULL;
	object->meshes = NULL;
	object->mesh_local_transform = NULL;
	object->count = 0;
}

m4 r_object_transform_matrix(r_object *object)
{
	// @Performance: replace with rototranslation matrix
	return translation_v3(object->position) * rotation_v3(object->rotation) * scale_v3(object->scale);
}

m4 r_object_mesh_transform_matrix(r_object *object, u64 mesh_i)
{
	// @Performance: replace with rototranslation matrix
	if(object->mesh_local_transform)
		return r_object_transform_matrix(object) * object->mesh_local_transform[mesh_i];
	return r_object_transform_matrix(object);
}
