/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


		#include "core/shader_tree_to_shader.h"
		#include "core/shader_tree_compiler_isl.h"
		#include "core/shader_tree.h"
		#include "core/shader.h"
		#include "memory/nauto_ptr.h"

		using namespace GS;


//------------------------------------------------------------------------------
bool		Core::ConvertShaderTreeToShader(const Core::ShaderTree &tree, Core::Shader &shader)
{
	ISLShaderTreeCompiler cp;
	cp.RestartCompiler(&shader);

	struct ShaderTreeOutput
	{
		const char *builtin;
		ShaderTree::ShaderSinkType	sink;
		const char *default_value;
	};

	static ShaderTreeOutput	vertex_sink[] =
	{
		{ "%position%", ShaderTree::SinkVertex, "vec4(a_position, 1.0)" },
		{ NULL, ShaderTree::SinkInvalid }
	};

	for	(uint n = 0; vertex_sink[n].builtin; ++n)
		if	(CShaderBlock *cblock = cp.CompileShaderBlock(tree.sink[vertex_sink[n].sink]))
			shader.vertex += String::Format("%s = %s;\n", vertex_sink[n].builtin, cblock->variable.c_str());

	static ShaderTreeOutput	pixel_sink[] =
	{
		{ "%normal%", ShaderTree::SinkNormal, "vec3(0.0, 0.0, 0.0)" },
		{ "%diffuse%", ShaderTree::SinkDiffuse, "vec4(0.75, 0.75, 0.75, 1.0)" },
		{ "%specular%", ShaderTree::SinkSpecular, "vec4(0.5, 0.5, 0.5, 1.0)" },
		{ "%glossiness%", ShaderTree::SinkGlossiness, "0.25" },
		{ "%constant%", ShaderTree::SinkConstant, "vec4(0.0, 0.0, 0.0, 1.0)" },
		{ "%opacity%", ShaderTree::SinkOpacity, "1.0" },
		{ NULL, ShaderTree::SinkInvalid }
	};

	for	(uint n = 0; pixel_sink[n].builtin; ++n)
		if	(CShaderBlock *cblock = cp.CompileShaderBlock(tree.sink[pixel_sink[n].sink]))
			shader.pixel += String::Format("%s = %s;\n", pixel_sink[n].builtin, cblock->variable.c_str());

	shader.name = cp.GetId();
	shader.vertex = cp.GetVertexSource() + shader.vertex;
	shader.pixel = cp.GetPixelSource() + shader.pixel;

	return true;
}
//------------------------------------------------------------------------------
