Unity – Generar Normalmap de textura en runtime

Script para obtener la textura de NormalMap de un Texture2D en runtime, el cual fue una pregunta de una alumna que se hizo interesante compartir su solución.

Nota: El proceso es algo lento, pero logra su cometido.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Basado en: https://forum.unity.com/threads/bumpmap-grayscale-to-normalmap-rgb.5714/
public class TextureToNormalmap : MonoBehaviour
{
//---CODIGO DE EJEMPLO------------------------------
public Texture2D textura;
[Range(10f, 20f)]
public float distortion= 10.0f;
// Use this for initialization
void Start () {
Material mat = GetComponent<Renderer> ().material;
Texture2D Normal = GraytoNormalMap (textura, distortion);
mat.mainTexture = Normal;
}
//---TERMINA CODIGO DE EJEMPLO-----------------------
//Ayuda a clampear y exagerar el efecto
float sCurve(float _x, float _distortion = 10.0f)
{
return 1f / ( 1f + Mathf.Exp(-Mathf.Lerp(5f,15f,_distortion)*(_x-0.5f)));
}
Texture2D GraytoNormalMap(Texture2D t, float _distortion)
{
Texture2D n = new Texture2D(t.width,t.height,TextureFormat.ARGB32,true);
for(int y=1;y<t.width-1;y++)
{
for(int x=1;x<t.height*2-1;x++)
{
float xLeft = t.GetPixel(x-1,y).grayscale;
float xRight = t.GetPixel(x+1,y).grayscale;
float yUp = t.GetPixel(x,y-1).grayscale;
float yDown = t.GetPixel(x,y+1).grayscale;
float xDelta = ((xLeft-xRight)+1)*.5f;
float yDelta = ((yUp-yDown)+1)*.5f;
n.SetPixel(x,y,new Color( Mathf.Clamp01(sCurve(xDelta, distortion)) , Mathf.Clamp01(sCurve(yDelta, distortion)),1f,1.0f));
}
}
n.Apply();
return n;
}
Texture2D NormalmapToGray(Texture2D t)
{
Texture2D n = new Texture2D(t.width,t.height,TextureFormat.ARGB32,true);
Color oldColor = new Color();
Color newColor = new Color();
for (int x=0; x<t.width; x++){
for (int y=0; y<t.height; y++){
oldColor = t.GetPixel(x,y);
newColor.r = oldColor.g;
newColor.b = oldColor.g;
newColor.g = oldColor.g;
newColor.a = oldColor.r;
n.SetPixel(x,y, newColor);
}
}
n.Apply();
return n;
}
}

Un comentario en “Unity – Generar Normalmap de textura en runtime

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.