#include <mitsuba/render/scene.h>
#include <mitsuba/render/texture.h>
#include <mitsuba/core/warp.h>
#include <mitsuba/hw/basicshader.h>

MTS_NAMESPACE_BEGIN

static float pdot(Vector a, Vector b) {
	return std::max(0.f, dot(a, b));
}

static Vector wt(Vector wp) {
	return normalize(Vector(-wp.x, -wp.y, 0.f));
}

static float G1(Vector wp, Vector w) {
	return std::min(1.f,
		std::max(0.f, Frame::cosTheta(w)) * std::max(0.f, Frame::cosTheta(wp))
		/ (pdot(w, wp) + pdot(w, wt(wp)) * Frame::sinTheta(wp))
	);
}

static float lambda_p(Vector wp, Vector wi) {
	float i_dot_p = pdot(wp, wi);
	return i_dot_p / (i_dot_p + pdot(wt(wp), wi) * Frame::sinTheta(wp));
}

class NormalMapMicrofacetDefault : public BSDF {
public:
	NormalMapMicrofacetDefault(const Properties &props) : BSDF(props) { }

	NormalMapMicrofacetDefault(Stream *stream, InstanceManager *manager)
			: BSDF(stream, manager) {
		m_normals = static_cast<Texture *>(manager->getInstance(stream));
		m_nested = static_cast<BSDF *>(manager->getInstance(stream));

		configure();
	}

	void configure() {
		if (!m_nested)
			Log(EError, "A child BSDF instance is required");
		if (!m_normals)
			Log(EError, "A normal map texture must be specified");

		m_components.clear();
		for (int i=0; i<m_nested->getComponentCount(); ++i)
			m_components.push_back(m_nested->getType(i) | ESpatiallyVarying | EAnisotropic);

		m_usesRayDifferentials = true;
		BSDF::configure();
	}

	void serialize(Stream *stream, InstanceManager *manager) const {
		BSDF::serialize(stream, manager);

		manager->serialize(stream, m_nested.get());
		manager->serialize(stream, m_normals.get());
	}

	Spectrum getDiffuseReflectance(const Intersection &its) const {
		return m_nested->getDiffuseReflectance(its);
	}

	Spectrum getSpecularReflectance(const Intersection &its) const {
		return m_nested->getSpecularReflectance(its);
	}

	void addChild(const std::string &name, ConfigurableObject *child) {
		if (child->getClass()->derivesFrom(MTS_CLASS(BSDF))) {
			if (m_nested != NULL)
				Log(EError, "Only a single nested BSDF can be added!");
			m_nested = static_cast<BSDF *>(child);
		} else if (child->getClass()->derivesFrom(MTS_CLASS(Texture))) {
			if (m_normals != NULL)
				Log(EError, "Only a single normal texture can be specified!");
			const Properties &props = child->getProperties();
			if (props.getPluginName() == "bitmap" && !props.hasProperty("gamma"))
				Log(EError, "When using a bitmap texture as a normal map, please explicitly specify "
						"the 'gamma' parameter of the bitmap plugin. In most cases the following is the correct choice: "
						"<float name=\"gamma\" value=\"1.0\"/>");
			m_normals = static_cast<Texture *>(child);
		} else {
			BSDF::addChild(name, child);
		}

	}

	Spectrum eval(const BSDFSamplingRecord &bRec, EMeasure measure) const {
		if (measure != ESolidAngle
			|| Frame::cosTheta(bRec.wi) <= 0
			|| Frame::cosTheta(bRec.wo) <= 0)
			return Spectrum(0.0f);
		Vector wp;
		m_normals->eval(bRec.its, false).toLinearRGB(wp.x, wp.y, wp.z);
		wp = normalize(2.f * wp - Vector(1.f));

		if (Frame::cosTheta(wp) <= 0 || (std::abs(wp.x) < 1e-6 && std::abs(wp.y) < 1e-6)) {
			return m_nested->eval(bRec, measure);
		}

		Frame frame_wp(bRec.its.toWorld(wp));
		Intersection perturbed_wp(bRec.its);
		perturbed_wp.geoFrame = frame_wp;
		perturbed_wp.shFrame = frame_wp;
		perturbed_wp.wi = perturbed_wp.toLocal(bRec.its.toWorld(bRec.wi));

		Vector wo_wp = perturbed_wp.toLocal(bRec.its.toWorld(bRec.wo));
		Vector wt_ = bRec.its.toWorld(wt(wp));
		Vector wo = bRec.its.toWorld(bRec.wo);
		Vector wi = bRec.its.toWorld(bRec.wi);
		Vector wo_reflected = normalize(wo - 2.0f * dot(wo, wt_) * wt_);
		float notShadowedWpMirror = 1.f - G1(wp, bRec.its.toLocal(wo_reflected));
		wo_reflected = perturbed_wp.toLocal(wo_reflected);
		float shadowing = G1(wp, bRec.wo);

		Spectrum value(0.f);

		float lambda_p_ = lambda_p(wp, bRec.wi);

		// i -> p -> o
		BSDFSamplingRecord evalSingleP(perturbed_wp, wo_wp);
		value += m_nested->eval(evalSingleP, measure) * (lambda_p_ * shadowing);

		// i -> p -> t -> o
		if (dot(wo, wt_) > 0) {
			BSDFSamplingRecord evalDoubleP(perturbed_wp, wo_reflected);
			value += m_nested->eval(evalDoubleP, measure) * (lambda_p_ * notShadowedWpMirror * shadowing);
		}

		// i -> t -> p -> o
		if (dot(wi, wt_) > 0) {
			Vector wi_reflected = normalize(wi - 2.0f * dot(wi, wt_) * wt_);
			BSDFSamplingRecord evalDoubleT(perturbed_wp, perturbed_wp.toLocal(wi_reflected), wo_wp);
			value += m_nested->eval(evalDoubleT, measure) * ((1.f - lambda_p_) * shadowing);
		}

		return value;
	}

	Float pdf(const BSDFSamplingRecord &bRec, EMeasure measure) const {
		if (measure != ESolidAngle
			|| Frame::cosTheta(bRec.wi) <= 0
			|| Frame::cosTheta(bRec.wo) <= 0)
			return 0.0f;
		Vector wp;
		m_normals->eval(bRec.its, false).toLinearRGB(wp.x, wp.y, wp.z);
		wp = normalize(2.f * wp - Vector(1.f));

		if (Frame::cosTheta(wp) <= 0 || (std::abs(wp.x) < 1e-6 && std::abs(wp.y) < 1e-6)) {
			return m_nested->pdf(bRec, measure);
		}

		Float probability_wp = lambda_p(wp, bRec.wi);
		Frame frameWp(bRec.its.toWorld(wp));
		Intersection perturbed_wp(bRec.its);
		perturbed_wp.geoFrame = frameWp;
		perturbed_wp.shFrame = frameWp;
		Vector wi = bRec.its.toWorld(bRec.wi);
		Vector wo = bRec.its.toWorld(bRec.wo);
		Vector wt_ = bRec.its.toWorld(wt(wp));
		float pdf = 0.f;
		if (probability_wp > 0.f) {
			BSDFSamplingRecord queryWp(perturbed_wp, perturbed_wp.toLocal(wi),
				perturbed_wp.toLocal(wo));
			pdf += probability_wp * m_nested->pdf(queryWp, measure)
				* G1(wp, bRec.wo);

			if (dot(wo, wt_) > 1e-6) {
				Vector woReflected = normalize(wo - 2.0f * dot(wo, wt_) * wt_);
				BSDFSamplingRecord queryWpt(perturbed_wp, perturbed_wp.toLocal(wi),
					perturbed_wp.toLocal(woReflected));
				pdf += probability_wp * m_nested->pdf(queryWpt, measure)
					* (1.f - G1(wp, bRec.its.toLocal(woReflected)));
			}
		}

		if (probability_wp < 1.f && dot(wi, wt_) > 1e-6) {
			Vector wiReflected = normalize(wi - 2.0f * dot(wi, wt_) * wt_);
			BSDFSamplingRecord queryWtp(perturbed_wp, perturbed_wp.toLocal(wiReflected),
				perturbed_wp.toLocal(wo));
			pdf += (1.f - probability_wp) * m_nested->pdf(queryWtp, measure);
		}

		return pdf;
	}

	Spectrum sample(BSDFSamplingRecord &bRec, const Point2 &sample) const {
		if (Frame::cosTheta(bRec.wi) <= 0)
			return Spectrum(0.0f);

		bRec.eta = 1.0f;
		bRec.sampledComponent = 0;
		bRec.sampledType = ESmooth;

		Vector wp;
		m_normals->eval(bRec.its, false).toLinearRGB(wp.x, wp.y, wp.z);
		wp = normalize(2.f * wp - Vector(1.f));

		if (Frame::cosTheta(wp) <= 0 || (std::abs(wp.x) < 1e-6 && std::abs(wp.y) < 1e-6)) {
			return m_nested->sample(bRec, sample);
		}

		Frame frame_wp(bRec.its.toWorld(wp));
		Intersection perturbed_wp(bRec.its);
		perturbed_wp.geoFrame = frame_wp;
		perturbed_wp.shFrame = frame_wp;

		Vector wt_ = bRec.its.toWorld(wt(wp));

		Vector wr = -bRec.its.toWorld(bRec.wi);
		Spectrum energy(1.f);
		if (bRec.sampler->next1D() < lambda_p(wp, bRec.wi)) {
			// sample on wp
			perturbed_wp.wi = -perturbed_wp.toLocal(wr);
			BSDFSamplingRecord query_wp(perturbed_wp, NULL);
			energy *= m_nested->sample(query_wp, sample);
			// did sampling fail?
			if (energy.isZero()) return energy;
			wr = perturbed_wp.toWorld(query_wp.wo);
			float G1_ = G1(wp, bRec.its.toLocal(wr));

			// is the sampled direction shadowed?
			if (bRec.sampler->next1D() > G1_) {
				// reflect on wt
				wr = normalize(wr + 2.0f * dot(-wr, wt_) * wt_);
				energy *= G1(wp, bRec.its.toLocal(wr));
			}
		} else {
			// do one reflection if we start at wt
			wr = normalize(wr + 2.0f * dot(-wr, wt_) * wt_);
			// sample on wp
			perturbed_wp.wi = -perturbed_wp.toLocal(wr);
			BSDFSamplingRecord query_wp(perturbed_wp, NULL);
			energy *= m_nested->sample(query_wp, sample);
			// did sampling fail?
			if (energy.isZero()) return energy;
			wr = perturbed_wp.toWorld(query_wp.wo);
			energy *= G1(wp, bRec.its.toLocal(wr));
		}
		bRec.wo = bRec.its.toLocal(wr);
		if (Frame::cosTheta(bRec.wo) <= 0.) return Spectrum(0.f);
		return energy;
	}

	Spectrum sample(BSDFSamplingRecord &bRec, Float &pdf_, const Point2 &sample_) const {
		Spectrum weight = sample(bRec, sample_);
		pdf_ = pdf(bRec, ESolidAngle);
		return weight;
	}

	Float getRoughness(const Intersection &its, int component) const {
		return m_nested->getRoughness(its, component);
	}

	std::string toString() const {
		std::ostringstream oss;
		oss << "NormalMapMicrofacetDefault[" << endl
			<< "  id = \"" << getID() << "\"," << endl
			<< "  normals = " << indent(m_normals->toString()) << endl
			<< "  nested = " << indent(m_nested->toString()) << endl
			<< "]";
		return oss.str();
	}

	Shader *createShader(Renderer *renderer) const;

	MTS_DECLARE_CLASS()
protected:
	ref<BSDF> m_nested;
	ref<Texture> m_normals;
	int maxScatteringOrder;
	int minScatteringOrder;
};

// ================ Hardware shader implementation ================

/**
 * This is a quite approximate version of the normal map model -- it likely
 * won't match the reference exactly, but it should be good enough for
 * preview purposes
 */
class NormalMapShader : public Shader {
public:
	NormalMapShader(Renderer *renderer, const BSDF *nested, const Texture *normals)
		: Shader(renderer, EBSDFShader), m_nested(nested), m_normals(normals) {
		m_nestedShader = renderer->registerShaderForResource(m_nested.get());
		m_normalShader = renderer->registerShaderForResource(m_normals.get());
	}

	bool isComplete() const {
		return m_nestedShader.get() != NULL;
	}

	void cleanup(Renderer *renderer) {
		renderer->unregisterShaderForResource(m_nested.get());
		renderer->unregisterShaderForResource(m_normals.get());
	}

	void putDependencies(std::vector<Shader *> &deps) {
		deps.push_back(m_nestedShader.get());
		deps.push_back(m_normalShader.get());
	}

	void generateCode(std::ostringstream &oss,
			const std::string &evalName,
			const std::vector<std::string> &depNames) const {
		oss << "vec3 " << evalName << "(vec2 uv, vec3 wi, vec3 wo) {" << endl
			<< "    vec3 n = normalize(2.0*" << depNames[1] << "(uv) - vec3(1.0));" << endl
			<< "    vec3 s = normalize(vec3(1.0-n.x*n.x, -n.x*n.y, -n.x*n.z)); " << endl
			<< "    vec3 t = cross(s, n);" << endl
			<< "    wi = vec3(dot(wi, s), dot(wi, t), dot(wi, n));" << endl
			<< "    wo = vec3(dot(wo, s), dot(wo, t), dot(wo, n));" << endl
			<< "    return " << depNames[0] << "(uv, wi, wo);" << endl
			<< "}" << endl
			<< endl
		    << "vec3 " << evalName << "_diffuse(vec2 uv, vec3 wi, vec3 wo) {" << endl
			<< "    vec3 n = normalize(2.0*" << depNames[1] << "(uv) - vec3(1.0));" << endl
			<< "    vec3 s = normalize(vec3(1.0-n.x*n.x, -n.x*n.y, -n.x*n.z)); " << endl
			<< "    vec3 t = cross(s, n);" << endl
			<< "    wi = vec3(dot(wi, s), dot(wi, t), dot(wi, n));" << endl
			<< "    wo = vec3(dot(wo, s), dot(wo, t), dot(wo, n));" << endl
			<< "    return " << depNames[0] << "_diffuse(uv, wi, wo);" << endl
			<< "}" << endl
			<< endl;
	}

	MTS_DECLARE_CLASS()
private:
	ref<const BSDF> m_nested;
	ref<const Texture> m_normals;
	ref<Shader> m_nestedShader;
	ref<Shader> m_normalShader;
};

Shader *NormalMapMicrofacetDefault::createShader(Renderer *renderer) const {
	return new NormalMapShader(renderer, m_nested.get(), m_normals.get());
}

MTS_IMPLEMENT_CLASS(NormalMapShader, false, Shader)
MTS_IMPLEMENT_CLASS_S(NormalMapMicrofacetDefault, false, BSDF)
MTS_EXPORT_PLUGIN(NormalMapMicrofacetDefault, "Normal map modifier");
MTS_NAMESPACE_END
