﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class GenNormalMap : EditorWindow
{
	[MenuItem("Tools/DSS/Normal map prepare")]
	public static void ShowWindow() {
		EditorWindow w = GetWindow<GenNormalMap>(false, "Normal map prepare", true);
		w.minSize = new Vector2(300, 170);
	}

	Texture2D hm;
	float normalStr = 10f;

	private void OnGUI() {
		EditorGUI.BeginChangeCheck();
		hm = (Texture2D)EditorGUILayout.ObjectField("Heightmap", hm, typeof(Texture2D), true);
		normalStr = EditorGUILayout.Slider(normalStr, 0.1f, 50);
		if(hm != null) {
			if(GUILayout.Button("Generate", GUILayout.Width(100), GUILayout.Height(30))) {
				Texture2D normals = new Texture2D(hm.width, hm.height);
				for(int i = 0; i < hm.width; i++) {
					for(int j = 0; j < hm.height; j++) {
						float curr = hm.GetPixel(i, j).g + hm.GetPixel(i, j).b * 0.1f;
						float h1 = hm.GetPixel(i + 1, j).g + hm.GetPixel(i + 1, j).b * 0.1f;
						float h2 = (hm.GetPixel(i, j + 1).g + hm.GetPixel(i, j + 1).b * 0.1f) * 0.5f + curr * 0.5f;
						float h3 = hm.GetPixel(i - 1, j).g + hm.GetPixel(i - 1, j).b * 0.1f;
						float h4 = (hm.GetPixel(i, j - 1).g + hm.GetPixel(i, j - 1).b * 0.1f) * 0.5f + curr * 0.5f;

						Vector3 w = Vector3.Normalize(new Vector3(h3 - h1, 1.0f / normalStr, h2 - h4));

						float x = (float)i / (float)hm.width;
						float y = (float)j / (float)hm.height;

						w = Quaternion.Euler(y * 180, 0, 0) * w;
						w = Quaternion.Euler(0, x * 360 + 270, 0) * w;
						w = Quaternion.Euler(0, 0, 180) * w;
						w = Vector3.Normalize(w);

						w.x += 1;
						w.y += 1;
						w.z += 1;
						w /= 2.0f;

						normals.SetPixel(i, j, new Color(w.x, w.y, w.z));
					}
				}
				normals.Apply();
				byte[] texData = normals.EncodeToPNG();
				System.IO.FileStream stream = System.IO.File.Create(AssetDatabase.GetAssetPath(hm) + "_converted.png");
				stream.Write(texData, 0, texData.Length);
				stream.Dispose();
				AssetDatabase.Refresh();
			}
		}
	}
}
