#include "octree.h"

#include <ai.h>

AI_SHADER_NODE_EXPORT_METHODS(apIrradianceCache)

enum apIrradianceCacheParams
{
	p_passthough,

};

struct IrradianceCacheData
{
	AtRGB color;
	AtVector normal;
};

struct ShaderData
{
	Octree<IrradianceCacheData> octree;
};

node_parameters
{
	AiParameterClosure("passthough");
}

node_initialize
{
	ShaderData *data = (ShaderData *)AiMalloc(sizeof(ShaderData));
	AtNode *options = AiUniverseGetOptions();
	int xres = AiNodeGetInt(options, "xres");
	int yres = AiNodeGetInt(options, "yres");
	data->octree = Octree<IrradianceCacheData>(xres * yres);
	AiNodeSetLocalData(node, data);
}

node_update
{
	ShaderData *data = (ShaderData *)AiNodeGetLocalData(node);
}

node_finish
{
	ShaderData *data = (ShaderData *)AiNodeGetLocalData(node);
	AiFree(data);
}

shader_evaluate
{
	AiShaderEvalParamClosure(p_passthough);
	ShaderData *data = (ShaderData *)AiNodeGetLocalData(node);

	int i = sg->x + sg->y;
	AtRGB irr = AiIrradiance(sg->P, sg->N, sg->tid, i);
	IrradianceCacheData irrCache;
	irrCache.color = irr;
	irrCache.normal = sg->N;
	data->octree.set(sg->P.x, sg->P.y, sg->P.z, irrCache);
}

node_loader
{
	if (i > 0)
		return false;

	node->methods = apIrradianceCache;
	node->output_type = AI_TYPE_RGB;
	node->name = "apIrradianceCache";
	node->node_type = AI_NODE_SHADER;
	strcpy(node->version, AI_VERSION);
	return true;
}