Skip to content

Instantly share code, notes, and snippets.

@lardratboy
Last active November 23, 2015 23:28
Show Gist options
  • Save lardratboy/34ce943f06aa50a29ae2 to your computer and use it in GitHub Desktop.
Save lardratboy/34ce943f06aa50a29ae2 to your computer and use it in GitHub Desktop.
Unity3d Utility Extension to render a Material to a .PNG (or JPG)
using UnityEngine;
#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
#endif
namespace BPT {
// Instructions place this file inside your project
// it will then add a 'Tools/BPT/Render Material As' menu item
/*
Copyright (c) 2015 Brad P. Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if UNITY_EDITOR
[CustomEditor(typeof(BPTRenderMaterialAs))]
public class BPTRenderMaterialAsEditor : Editor {
internal const int MIN_TEXTURE_DIM = 8;
internal const int MAX_TEXTURE_DIM = 8192;
private BPTRenderMaterialAs _myTarget;
private bool showExplanation = false;
private void OnEnable () {
_myTarget = (BPTRenderMaterialAs)target;
}
public override void OnInspectorGUI () {
showExplanation = EditorGUILayout.Foldout( showExplanation, "Render Material Info" );
if ( showExplanation ) {
EditorGUILayout.LabelField( "This asset allows you to save the rendering" );
EditorGUILayout.LabelField( "of a Meterial to a file which can be used as" );
EditorGUILayout.LabelField( "a texture. I wrote this so I could build" );
EditorGUILayout.LabelField( "value/lookup textures for various shders." );
EditorGUILayout.LabelField( "e.g. rgba(u,v) = f(u,v) { math }" );
EditorGUILayout.LabelField( "Regards -BPT" );
EditorGUILayout.Separator();
}
_myTarget.material = (Material)EditorGUILayout.ObjectField(
"1. Material", _myTarget.material, typeof(Material), true );
if ( _myTarget.material ) {
_myTarget.sourceTexture = (Texture)EditorGUILayout.ObjectField(
"2. Source Texture", _myTarget.sourceTexture, typeof(Texture), true );
_myTarget.renderTextureReadWrite = (RenderTextureReadWrite)EditorGUILayout.EnumPopup(
"3. Color space conversion", _myTarget.renderTextureReadWrite );
#if false // TODO (floating point textures)
_myTarget.renderFormat = (BPTRenderMaterialAs.RenderFormat)EditorGUILayout.EnumPopup(
"renderTextureFormat", _myTarget.renderFormat );
_myTarget.textureFormat = (BPTRenderMaterialAs.IntermediateTextureFormat)EditorGUILayout.EnumPopup(
"textureFormat", _myTarget.textureFormat );
#endif
_myTarget.width = EditorGUILayout.IntSlider(
"4. Width", _myTarget.width, MIN_TEXTURE_DIM, MAX_TEXTURE_DIM );
_myTarget.height = EditorGUILayout.IntSlider(
" Height", _myTarget.height, MIN_TEXTURE_DIM, MAX_TEXTURE_DIM );
_myTarget.fileType = (BPTRenderMaterialAs.FileOutputType)EditorGUILayout.EnumPopup(
"5. Output Format", _myTarget.fileType );
bool renderAndSave = GUILayout.Button(
"Render and Save...",
GUILayout.Height(2 * EditorGUIUtility.singleLineHeight));
if ( renderAndSave ) {
_myTarget.RenderAndSave();
}
} else {
EditorGUILayout.LabelField(
"*** Choose a material to render. ***" );
}
}
}
// ==========================================================================
public class AssetHelpers {
public static T CreateAsset<T>(string path)
where T : ScriptableObject {
T dataClass = (T) ScriptableObject.CreateInstance<T>();
AssetDatabase.CreateAsset(dataClass, path);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
return dataClass;
}
public static bool DoestAssetExist<T>( ref string path)
where T : ScriptableObject {
string filter = "t:" + typeof(T).FullName;
string [] found = AssetDatabase.FindAssets( filter );
if ( 0 >= found.Length ) return false;
path = AssetDatabase.GUIDToAssetPath(found[0]);
return true;
}
public static T GetOrCreateAsset<T>( string path )
where T : ScriptableObject {
if ( !DoestAssetExist<T>( ref path ) ) {
return CreateAsset<T>( path );
}
return AssetDatabase.LoadAssetAtPath<T>( path );
}
}
// ==========================================================================
[Serializable]
public class BPTRenderMaterialAs : ScriptableObject {
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[MenuItem ("Tools/BPT/Render Material As")]
public static void CreateBPTRenderMaterialAs() {
BPTRenderMaterialAs asset = AssetHelpers.GetOrCreateAsset<BPTRenderMaterialAs>(
"Assets/BPTRenderMaterialAs.asset" );
UnityEditor.Selection.activeObject = asset;
EditorGUIUtility.PingObject( asset );
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
public enum RenderFormat {
ARGB32 = RenderTextureFormat.ARGB32
//, ARGBFloat = RenderTextureFormat.ARGBFloat
//, ARGBHalf = RenderTextureFormat.ARGBHalf
}
public enum IntermediateTextureFormat {
ARGB32 = TextureFormat.ARGB32
//, RGB24 = TextureFormat.RGB24
//, RGBAFloat = TextureFormat.RGBAFloat
//, RGBAHalf = TextureFormat.RGBAHalf
}
public enum FileOutputType {
PNG = 1, JPG //, TODO (floating point textures)
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
public Material material;
public Texture sourceTexture;
public RenderFormat renderFormat = RenderFormat.ARGB32;
public RenderTextureReadWrite renderTextureReadWrite = RenderTextureReadWrite.Linear;
public IntermediateTextureFormat textureFormat = IntermediateTextureFormat.ARGB32;
public int width = 256;
public int height = 256;
public FileOutputType fileType = FileOutputType.PNG;
// -----------------------------------------------------------------------
string Extension() {
return (FileOutputType.JPG == fileType) ? "JPG" : "PNG";
}
byte [] Encode( Texture2D texture ) {
if ( FileOutputType.JPG == fileType ) {
return texture.EncodeToJPG();
}
return texture.EncodeToPNG();
}
// -------------------------------------------------------------
bool HandleRenderAndSave() {
if ( !material ) return false;
RenderTexture tempRT = RenderTexture.GetTemporary(
width, height, 0, (RenderTextureFormat)renderFormat, renderTextureReadWrite );
if ( !tempRT ) return false;
tempRT.generateMips = false;
bool result = false;
if ( tempRT.Create() ) {
if ( material ) {
Graphics.Blit( sourceTexture, tempRT, material );
string defaultName;
if ( sourceTexture ) {
defaultName = String.Format(
"{0}_{1}_{2}x{3}", material.name, sourceTexture.name, width, height );
} else {
defaultName = String.Format(
"{0}_{1}x{2}", material.name, width, height );
}
string path = EditorUtility.SaveFilePanelInProject(
"Save As", defaultName, Extension(), "Choose filename" );
if ( 0 != path.Length ) {
RenderTexture oldRT = RenderTexture.active;
RenderTexture.active = tempRT;
Texture2D tempTex = new Texture2D( width, height, (TextureFormat)textureFormat, false );
tempTex.ReadPixels( new Rect(0f,0f,width,height), 0, 0 );
File.WriteAllBytes(path,Encode(tempTex));
if ( Application.isPlaying ) {
Texture.Destroy(tempTex);
} else {
Texture.DestroyImmediate(tempTex);
}
RenderTexture.active = oldRT;
result = true;
}
if ( result ) {
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
}
}
RenderTexture.ReleaseTemporary( tempRT );
return result;
}
// -------------------------------------------------------------
[ExecuteInEditMode]
class EndOfFrameHelper : MonoBehaviour {
public IEnumerator Handle( Action action, bool autoDestroy ) {
yield return new WaitForEndOfFrame();
action();
if ( autoDestroy ) {
Destroy( gameObject );
}
}
static public EndOfFrameHelper Instance( Action action, bool autoDestroy = true ) {
HideFlags hideFlags = HideFlags.HideAndDontSave |
HideFlags.DontSaveInBuild |
HideFlags.DontSaveInEditor;
GameObject host = new GameObject();
host.hideFlags = hideFlags;
EndOfFrameHelper helper = host.AddComponent<EndOfFrameHelper>();
helper.hideFlags = hideFlags;
helper.StartCoroutine( helper.Handle( action, autoDestroy ) );
return helper;
}
}
public void RenderAndSave() {
if ( Application.isPlaying ) {
EndOfFrameHelper.Instance(()=>{HandleRenderAndSave();});
} else {
HandleRenderAndSave();
}
}
void OnValidate() {
width = Mathf.Clamp(width,
BPTRenderMaterialAsEditor.MIN_TEXTURE_DIM,
BPTRenderMaterialAsEditor.MAX_TEXTURE_DIM);
height = Mathf.Clamp(height,
BPTRenderMaterialAsEditor.MIN_TEXTURE_DIM,
BPTRenderMaterialAsEditor.MAX_TEXTURE_DIM);
}
}
#endif
}
@lardratboy
Copy link
Author

Hopefully a picture is worth a thousand words... here is a link to example of how I have been using this.

https://s-media-cache-ak0.pinimg.com/originals/a4/5e/ae/a45eae6558364da5e7473bfa393655b6.jpg

What you should be seeing if the link worked is a screenshot of four panels from unity from left to right. The project explorer with the output file selected, the inspector for the material, the inspector for the tool and finally the inspector for the output texture.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment