Hi all
How to create bump form a texture by code?(Not use Editor and UnityEditor Clases).
The algorithm for this has been discussed in the forums a while ago. The source texture has to be marked as “Read/Write Enabled”. For huge textures this algorithm will take a fair amount of time.
public static Texture2D GenerateNormalMap(Texture2D source, float strength)
{
Texture2D result;
float xLeft, xRight;
float yUp, yDown;
float xDelta, yDelta;
result = new Texture2D(source.width, source.height, TextureFormat.ARGB32, true);
for (int by = 0; by < result.height; by++)
for (int bx = 0; bx < result.width; bx++)
{
xLeft = source.GetPixel(bx - 1, by).grayscale * strength;
xRight = source.GetPixel(bx + 1, by).grayscale * strength;
yUp = source.GetPixel(bx, by - 1).grayscale * strength;
yDown = source.GetPixel(bx, by + 1).grayscale * strength;
xDelta = ((xLeft - xRight) + 1) * 0.5f;
yDelta = ((yUp - yDown) + 1) * 0.5f;
result.SetPixel(bx, by, new Color(xDelta, yDelta, 1, yDelta));
}
result.Apply();
return result;
}
Using the “Pixel32” methods instead of “Pixel” will be quite a bit faster as it uses the byte based Color32 structure that uses only 48 bit compared to the 432 bit of the Color structure.
Thanks a lot.