Initial commit

This commit is contained in:
gunnbr committed 2021-01-11 22:20:43 -08:00
1 parent ee9615239e
commit 16feac691f
4093 files changed
+1030491

No files matched your search

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b56b0eb9650e9194e8bcfbb7af37aa68
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: deda9a0740f5a3e4d92e8743f5d6a486
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,69 @@
using System.Text;
using UnityEngine;
using UnityEngine.Experimental.TerrainAPI;
namespace Gaia
{
public delegate void ResetBrush();
public interface IBrushUIGroup {
/// <summary>
/// The normalized size of the brush.
/// </summary>
float brushSize { get; }
/// <summary>
/// The rotation of the brush (in degrees).
/// </summary>
float brushRotation { get; }
/// <summary>
/// The normalized strength of the brush when applied.
/// </summary>
float brushStrength { get; }
/// <summary>
/// The spacing used when applying certain brushes.
/// </summary>
float brushSpacing { get; }
string validationMessage { get; set; }
/// <summary>
/// Are we allowed to paint with this brush?
/// </summary>
bool allowPaint { get; }
bool InvertStrength { get; }
bool isInUse { get; }
//FilterStackView brushMaskFilterStackView { get; }
//FilterStack brushMaskFilterStack { get; }
Terrain terrainUnderCursor { get; }
bool isRaycastHitUnderCursorValid { get; }
RaycastHit raycastHitUnderCursor { get; }
//void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext);
//void OnEnterToolMode();
//void OnExitToolMode();
//void OnPaint(Terrain terrain, IOnPaint editContext);
//void OnSceneGUI2D(Terrain terrain, IOnSceneGUI editContext);
// void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext);
//void AppendBrushInfo(Terrain terrain, IOnSceneGUI editContext, StringBuilder builder);
//RenderTexture GetBrushMask(FilterContext fc, RenderTexture heightContext);
/// <summary>
/// Scatters the brush around the specified UV on the specified terrain. If the scattered UV leaves
/// the current terrain then the terrain AND UV are modified for the terrain the UV is now over.
/// </summary>
/// <param name="terrain">The terrain the scattered UV co-ordinate is actually on.</param>
/// <param name="uv">The UV co-ordinate passed in transformed into the UV co-ordinate relative to the scattered terrain.</param>
/// <returns>"true" if we scattered to a terrain, "false" if we fell off ALL terrains.</returns>
bool ScatterBrushStamp(ref Terrain terrain, ref Vector2 uv);
//bool ModifierActive(BrushModifierKey k);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6df698f1e9a4fad4b81a0debb01615ff
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,768 @@
#if UNITY_EDITOR
using System;
using UnityEngine;
using UnityEditor;
using UnityEngine.Rendering;
using UnityEditor.Experimental.TerrainAPI;
namespace Gaia
{
public interface IFloatMinMaxSlider {
float value { get; set; }
float minValue { get; set; }
float maxValue { get; set; }
void DrawInspectorGUI();
}
[Serializable]
public class TerrainFloatMinMaxValue : IFloatMinMaxSlider {
[SerializeField]
private bool m_Expanded = false;
[SerializeField]
private float m_Value = 0.0f;
[SerializeField]
private float m_MinValue = 0.0f;
[SerializeField]
private float m_MaxValue = 1.0f;
[SerializeField]
private float m_MouseSensitivity = 1.0f;
[SerializeField]
private bool m_WrapValue = false;
private bool m_EditRange = true;
private readonly bool m_EditSensitivity = true;
private readonly GUIContent m_Label;
public float value
{
get => m_Value;
set
{
if(m_WrapValue)
{
float difference = m_MaxValue - m_MinValue;
while(value < m_MinValue)
{
value += difference;
}
while(value > m_MaxValue)
{
value -= difference;
}
m_Value = value;
}
else
{
m_Value = Mathf.Clamp(value, m_MinValue, m_MaxValue);
}
}
}
public float minValue {
get => m_MinValue;
set => m_MinValue = value;
}
public float maxValue {
get => m_MaxValue;
set => m_MaxValue = value;
}
public float mouseSensitivity {
get => m_MouseSensitivity;
set => m_MouseSensitivity = value;
}
public bool wrapValue
{
get => m_WrapValue;
set => m_WrapValue = value;
}
public TerrainFloatMinMaxValue(GUIContent label, float value, float minValue, float maxValue, bool editRange = true) {
m_Expanded = false;
m_Value = value;
m_MinValue = minValue;
m_MaxValue = maxValue;
m_EditRange = editRange;
m_EditSensitivity = false;
m_Label = label;
}
public TerrainFloatMinMaxValue(GUIContent label, float value, float minValue, float maxValue, bool editRange, float mouseSensitivity) : this(label, value, minValue, maxValue, editRange) {
m_MouseSensitivity = mouseSensitivity;
m_EditSensitivity = true;
}
public void DrawInspectorGUI() {
float fieldWidth = EditorGUIUtility.fieldWidth;
float indentOffset = EditorGUI.indentLevel * 15f;
Rect totalRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
Rect labelRect = new Rect(totalRect.x, totalRect.y, EditorGUIUtility.labelWidth - indentOffset, totalRect.height);
Rect foldoutRect = new Rect(labelRect.xMax - 8, labelRect.y, 8, totalRect.height);
Rect sliderRect = new Rect(foldoutRect.xMax, labelRect.y, totalRect.width - labelRect.width, totalRect.height);
int rectHeight = 1;
EditorGUI.PrefixLabel(labelRect, m_Label);
m_Value = EditorGUI.Slider(sliderRect, m_Value, minValue, maxValue);
if (m_EditRange)
{
m_Expanded = EditorGUI.Foldout(foldoutRect, m_Expanded, GUIContent.none);
if (m_Expanded)
{
if (m_EditRange)
{
totalRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
Rect rangeLabelRect = new Rect(sliderRect.x, sliderRect.yMax, sliderRect.width / 2, totalRect.height);
Rect minRect = new Rect(totalRect.xMax - 2 * fieldWidth + indentOffset, totalRect.y, fieldWidth, totalRect.height);
Rect maxRect = new Rect(totalRect.xMax - fieldWidth, totalRect.y, fieldWidth, totalRect.height);
EditorGUI.PrefixLabel(rangeLabelRect, new GUIContent("Range:"));
m_MinValue = EditorGUI.FloatField(minRect, m_MinValue);
m_MaxValue = EditorGUI.FloatField(maxRect, m_MaxValue);
}
if (m_EditSensitivity)
{
totalRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
Rect sensitivityLabelRect = new Rect(sliderRect.x, totalRect.y, sliderRect.width / 2, totalRect.height);
Rect sensitivityValueRect = new Rect(totalRect.xMax - fieldWidth, totalRect.y, fieldWidth, totalRect.height);
EditorGUI.PrefixLabel(sensitivityLabelRect, new GUIContent("Mouse Sensitivity:"));
m_MouseSensitivity = EditorGUI.FloatField(sensitivityValueRect, m_MouseSensitivity);
}
}
}
GUILayoutUtility.GetRect(1, rectHeight);
}
}
public interface IIntMinMaxSlider {
int value { get; set; }
int minValue { get; set; }
int maxValue { get; set; }
void DrawInspectorGUI();
}
[Serializable]
public class TerrainIntMinMaxValue : IIntMinMaxSlider {
[SerializeField]
private bool m_Expanded = false;
[SerializeField]
private int m_Value = 0;
[SerializeField]
private int m_MinValue = 0;
[SerializeField]
private int m_MaxValue = 10;
private GUIContent m_Label;
public int value {
get => m_Value;
set => m_Value = Mathf.Clamp(value, m_MinValue, m_MaxValue);
}
public int minValue {
get => m_MinValue;
set => m_MinValue = value;
}
public int maxValue {
get => m_MaxValue;
set => m_MaxValue = value;
}
public GUIContent label {
get => m_Label;
set => m_Label = value;
}
public TerrainIntMinMaxValue(GUIContent label, int value, int minValue, int maxValue) {
m_Expanded = false;
m_Value = value;
m_MinValue = minValue;
m_MaxValue = maxValue;
m_Label = label;
}
public void DrawInspectorGUI() {
float fieldWidth = EditorGUIUtility.fieldWidth;
float indentOffset = EditorGUI.indentLevel * 15f;
Rect totalRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
Rect labelRect = new Rect(totalRect.x, totalRect.y, EditorGUIUtility.labelWidth - indentOffset, totalRect.height);
Rect foldoutRect = new Rect(labelRect.xMax - 8, labelRect.y, 8, totalRect.height);
Rect sliderRect = new Rect(foldoutRect.xMax, labelRect.y, totalRect.width - labelRect.width, totalRect.height);
EditorGUI.PrefixLabel(labelRect, m_Label);
m_Value = EditorGUI.IntSlider(sliderRect, m_Value, minValue, maxValue);
m_Expanded = EditorGUI.Foldout(foldoutRect, m_Expanded, new GUIContent());
if (m_Expanded) {
totalRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
Rect rangeLabelRect = new Rect(sliderRect.x, sliderRect.yMax, sliderRect.width / 2, totalRect.height);
Rect minRect = new Rect(totalRect.xMax - 2 * fieldWidth + indentOffset, totalRect.y, fieldWidth, totalRect.height);
Rect maxRect = new Rect(totalRect.xMax - fieldWidth, totalRect.y, fieldWidth, totalRect.height);
EditorGUI.PrefixLabel(rangeLabelRect, new GUIContent("Range:"));
m_MinValue = EditorGUI.IntField(minRect, m_MinValue);
m_MaxValue = EditorGUI.IntField(maxRect, m_MaxValue);
}
GUILayoutUtility.GetRect(1, 2);
}
}
public static class TerrainToolGUIHelper
{
public static GUILayoutOption dontExpandWidth = GUILayout.ExpandWidth(false);
public static GUIStyle buttonActiveStyle = null;
public static GUIStyle buttonNormalStyle = null;
public static GUIStyle toolbarNormalStyle = null;
public static GUIStyle toolbarActiveStyle = null;
public static GUIStyle leftToolbarStyle = null;
public static GUIStyle midToolbarStyle = null;
public static GUIStyle midToolbarActiveStyle = null;
public static GUIStyle rightToolbarStyle = null;
static TerrainToolGUIHelper() {
buttonNormalStyle = new GUIStyle("Button");
buttonActiveStyle = new GUIStyle("Button");
buttonActiveStyle.normal.background = buttonNormalStyle.active.background;
toolbarNormalStyle = new GUIStyle("ToolbarButton");
toolbarActiveStyle = new GUIStyle("ToolbarButton");
toolbarActiveStyle.normal.background = toolbarNormalStyle.hover.background;
leftToolbarStyle = new GUIStyle("CommandLeft");
midToolbarStyle = new GUIStyle("CommandMid");
midToolbarActiveStyle = new GUIStyle("CommandMid");
midToolbarActiveStyle.normal.background = midToolbarStyle.active.background;
rightToolbarStyle = new GUIStyle("CommandRight");
}
public static GUIStyle GetButtonToggleStyle(bool isToggled)
{
return isToggled ? buttonActiveStyle : buttonNormalStyle;
}
public static GUIStyle GetToolbarToggleStyle(bool isToggled)
{
return isToggled ? toolbarActiveStyle : toolbarNormalStyle;
}
public static bool DrawToggleHeaderFoldout(GUIContent title, bool state, ref bool enabled)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 32f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.xMin += 13f;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
var toggleRect = foldoutRect;
toggleRect.x = foldoutRect.xMax + 4f;
// Background rect should be full-width
backgroundRect.xMin = 16f * EditorGUI.indentLevel;
backgroundRect.xMin = 0;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
// Enabled toggle
enabled = GUI.Toggle(toggleRect, enabled, GUIContent.none, EditorStyles.toggle);
var e = Event.current;
if (e.type == EventType.MouseDown && e.button == 0)
{
if (toggleRect.Contains(e.mousePosition))
{
enabled = !enabled;
e.Use();
}
else if (backgroundRect.Contains(e.mousePosition))
{
state = !state;
e.Use();
}
}
return state;
}
public static bool DrawToggleHeaderFoldout(GUIContent title, bool state, ref bool enabled, float padding)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 32f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.xMin += padding;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
var toggleRect = foldoutRect;
toggleRect.x = foldoutRect.xMax + 4f;
// Background rect should be full-width
backgroundRect.xMin = padding;
backgroundRect.xMin = 0;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
// Enabled toggle
enabled = GUI.Toggle(toggleRect, enabled, GUIContent.none, EditorStyles.toggle);
var e = Event.current;
if (e.type == EventType.MouseDown && e.button == 0)
{
if (toggleRect.Contains(e.mousePosition))
{
enabled = !enabled;
e.Use();
}
else if (backgroundRect.Contains(e.mousePosition))
{
state = !state;
e.Use();
}
}
return state;
}
public static bool DrawHeaderFoldout(GUIContent title, bool state)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
var e = Event.current;
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
state = !state;
e.Use();
}
return state;
}
#if GAIA_PRO_PRESENT
public static bool DrawHeaderFoldoutForErosion(GUIContent title, bool state, ResetTool resetMethod)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0;
backgroundRect.width += 4f;
var gearIconRect = new Rect();
gearIconRect.y = backgroundRect.y;
gearIconRect.x = backgroundRect.width - 30f;
gearIconRect.width = 16f;
gearIconRect.height = 16f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
bool reset = false;
//icon
reset = GUI.Toggle(gearIconRect, reset, EditorGUIUtility.IconContent("_Popup"), EditorStyles.label);
var e = Event.current;
if (reset)
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Reset"), false, () => { resetMethod(); });
menu.ShowAsContext();
e.Use();
}
else if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
state = !state;
e.Use();
}
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 1)
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Reset"), false, () => { resetMethod(); });
menu.ShowAsContext();
e.Use();
}
return state;
}
#endif
public static bool DrawHeaderFoldoutForBrush(GUIContent title, bool state, ResetBrush resetMethod)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0;
backgroundRect.width += 4f;
var gearIconRect = new Rect();
gearIconRect.y = backgroundRect.y;
gearIconRect.x = backgroundRect.width - 30f;
gearIconRect.width = 16f;
gearIconRect.height = 16f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
bool reset = false;
//icon
reset = GUI.Toggle(gearIconRect, reset, EditorGUIUtility.IconContent("_Popup"), EditorStyles.label);
var e = Event.current;
if (reset)
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Reset"), false, () => { resetMethod(); });
menu.ShowAsContext();
e.Use();
}
else if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
state = !state;
e.Use();
}
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 1)
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Reset"), false, () => { resetMethod(); });
menu.ShowAsContext();
e.Use();
}
return state;
}
public static bool DrawToggleFoldout(SerializedProperty prop, GUIContent title, Action func, bool toggled)
{
bool state = prop.isExpanded;
state = DrawToggleHeaderFoldout(title, state, ref toggled);
if (state)
{
EditorGUI.indentLevel++;
if (func != null)
{
func();
}
--EditorGUI.indentLevel;
}
prop.isExpanded = state;
return toggled;
}
public static bool DrawFoldout(bool expanded, GUIContent title, Action func)
{
bool state = expanded;
state = DrawHeaderFoldout(title, state);
if (state)
{
EditorGUI.indentLevel++;
if (func != null)
{
func();
}
EditorGUI.indentLevel--;
}
return state;
}
public static void DrawFoldout(SerializedProperty prop, GUIContent title, Action func)
{
prop.isExpanded = DrawFoldout(prop.isExpanded, title, func);
}
public static bool ToggleButton(GUIContent content, bool value, params GUILayoutOption[] options)
{
if (GUILayout.Button(content, GetButtonToggleStyle(value), options))
{
value = !value;
}
return value;
}
public static bool ToggleButton(Rect rect, GUIContent content, bool value)
{
if ( GUI.Button( rect, content, GetButtonToggleStyle( value ) ) )
{
value = !value;
}
return value;
}
private static Rect GetToolbarRect(GUIContent[] toolbarContent, params GUILayoutOption[] options)
{
Debug.Assert(toolbarContent.Length > 0);
Rect maxRect = EditorGUILayout.GetControlRect(false, 0f);
Rect totalRect = new Rect(maxRect.xMin, maxRect.yMin, 0f, 0f);
Vector2 buttonPos = new Vector2(maxRect.xMin, maxRect.yMin);
GUIStyle skin = GetToolbarToggleStyle(false);
//bool newLine = true;
int linecount = 1;
Vector2 buttonSize = skin.CalcSize(toolbarContent[0]);
for (int i = 0; i < toolbarContent.Length; ++i) {
buttonSize = skin.CalcSize(toolbarContent[i]);
if (buttonPos.x + buttonSize.x > maxRect.xMax) {
buttonPos.x = maxRect.xMin;
buttonPos.y += buttonSize.y;
linecount++;
} else {
totalRect.xMax = Mathf.Max(buttonPos.x + buttonSize.x, totalRect.xMax);
}
buttonPos.x += buttonSize.x;
}
totalRect.height = buttonSize.y * linecount;
return totalRect;
}
public static int HorizontalFlagToolbar(GUIContent[] toolbarContent, int[] enumValues, int selection, params GUILayoutOption[] options)
{
Rect toolbarRect = GetToolbarRect(toolbarContent, options);
// GUI.Box(totalRect, GUIContent.none);
GUILayoutUtility.GetRect(toolbarRect.width, toolbarRect.height / 4);
// GUI.Box(totalRect, GUIContent.none);
// Rect maxRect = EditorGUILayout.GetControlRect(false, totalRect.height);
Vector2 buttonPos = new Vector2(toolbarRect.xMin, toolbarRect.yMin);
for (int i = 0; i < toolbarContent.Length; ++i) {
int enumVal = enumValues[i];
bool wasActive = (selection & enumVal) == enumVal && enumVal != 0;
GUIStyle skin = GetToolbarToggleStyle(wasActive);
Vector2 buttonSize = skin.CalcSize(toolbarContent[i]);
if (buttonPos.x + buttonSize.x > toolbarRect.xMax) {
buttonPos.x = toolbarRect.xMin;
buttonPos.y += buttonSize.y;
}
Rect buttonRect = new Rect(buttonPos.x, buttonPos.y, buttonSize.x, buttonSize.y);
if (GUI.Button(buttonRect, toolbarContent[i], skin)) {
if (enumVal == 0) {
selection = enumVal;
} else if (enumVal == ~0) {
selection = wasActive ? ~enumVal : enumVal;
} else {
selection = wasActive ? (selection & ~enumVal) : (selection | enumVal);
}
}
buttonPos.x += buttonSize.x;
}
return selection;
}
// assumes that an enum value of 0 = None and ~0 = Everything
private static int OLDHorizontalFlagToolbar(GUIContent[] toolbarContent, int[] enumValues, int selection, params GUILayoutOption[] options)
{
// TODO(wyatt): Change to use EditorGUIUtility.GetFlowLayoutedRects instead of Begin/EndHorizontal
Rect widthRect = GUILayoutUtility.GetRect(Screen.width, 17f);
// GetToolbarRect(true, toolbarContent, options);
// GUI.Box(widthRect, GUIContent.none);
Vector2 currPos = widthRect.position;
Rect totalRect = widthRect;
bool newLine = true;
//int skinID = 0; // left = 0, 1 = mid, 2 = right
for (int i = 0; i < toolbarContent.Length; ++i) {
int enumVal = enumValues[i];
bool wasActive = (selection & enumVal) == enumVal && enumVal != 0;
GUIStyle skin = GetToolbarToggleStyle(wasActive);
Vector2 size = skin.CalcSize(toolbarContent[i]);
Rect buttonRect = new Rect(currPos.x, currPos.y, size.x, size.y);
currPos.x += size.x;
totalRect.yMax = Mathf.Max(currPos.y + size.y, totalRect.yMax);
if (currPos.x + size.x > widthRect.xMax) {
currPos.x = widthRect.xMin;
currPos.y += size.y;
newLine = true;
}
if (newLine) {
// reserve a rect for the line
Rect reservedRect = GUILayoutUtility.GetRect(widthRect.width, size.y);
// GUI.Box(reservedRect, GUIContent.none);
newLine = false;
}
if (GUI.Button(buttonRect, toolbarContent[i], skin)) {
if (enumVal == 0) {
selection = enumVal;
} else if (enumVal == ~0) {
selection = wasActive ? ~enumVal : enumVal;
} else {
selection = wasActive ? (selection & ~enumVal) : (selection | enumVal);
}
}
}
return selection;
}
public static int MinMaxSliderInt(GUIContent label, int value, ref int minValue, ref int maxValue) {
float fieldWidth = EditorGUIUtility.fieldWidth;
float indentOffset = EditorGUI.indentLevel * 15f;
Rect totalRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
Rect labelRect = new Rect(totalRect.x, totalRect.y, EditorGUIUtility.labelWidth - indentOffset, totalRect.height);
Rect sliderRect = new Rect(labelRect.xMax, labelRect.y, totalRect.width - labelRect.width - 2 * fieldWidth - 4, totalRect.height);
Rect minLabelRect = new Rect(sliderRect.xMax + 4 - indentOffset, labelRect.y, fieldWidth, totalRect.height);
Rect minRect = new Rect(minLabelRect.xMax, labelRect.y, fieldWidth / 2 + indentOffset, totalRect.height);
Rect maxRect = new Rect(minRect.xMax - indentOffset, sliderRect.y, fieldWidth / 2 + indentOffset, totalRect.height);
EditorGUI.PrefixLabel(labelRect, label);
value = EditorGUI.IntSlider(sliderRect, value, minValue, maxValue);
EditorGUI.PrefixLabel(minLabelRect, new GUIContent("Range:"));
minValue = EditorGUI.IntField(minRect, minValue);
maxValue = EditorGUI.IntField(maxRect, maxValue);
return value;
}
public static float MinMaxSlider(GUIContent label, float value, ref float minValue, ref float maxValue) {
float fieldWidth = EditorGUIUtility.fieldWidth;
float indentOffset = EditorGUI.indentLevel * 15f;
Rect totalRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
Rect labelRect = new Rect(totalRect.x, totalRect.y, EditorGUIUtility.labelWidth - indentOffset, totalRect.height);
Rect sliderRect = new Rect(labelRect.xMax, labelRect.y, totalRect.width - labelRect.width - 2 * fieldWidth - 4, totalRect.height);
Rect minLabelRect = new Rect(sliderRect.xMax + 4 - indentOffset, labelRect.y, fieldWidth, totalRect.height);
Rect minRect = new Rect(minLabelRect.xMax, labelRect.y, fieldWidth / 2 + indentOffset, totalRect.height);
Rect maxRect = new Rect(minRect.xMax - indentOffset, sliderRect.y, fieldWidth / 2 + indentOffset, totalRect.height);
EditorGUI.PrefixLabel(labelRect, label);
value = EditorGUI.Slider(sliderRect, value, minValue, maxValue);
EditorGUI.PrefixLabel(minLabelRect, new GUIContent("Range:"));
minValue = EditorGUI.FloatField(minRect, minValue);
maxValue = EditorGUI.FloatField(maxRect, maxValue);
return value;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 288487cb63c6bd143aa83198cef71a57
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,31 @@
using UnityEngine;
namespace Gaia {
#region Utility
public static class TerrainToolsUtility {
//assume this a 1D texture that has already been created
public static Vector2 AnimationCurveToRenderTexture(AnimationCurve curve, ref Texture2D tex) {
tex.wrapMode = TextureWrapMode.Clamp;
tex.filterMode = FilterMode.Bilinear;
float val = curve.Evaluate(0.0f);
Vector2 range = new Vector2(val, val);
Color[] pixels = new Color[tex.width];
for (int i = 1; i < tex.width; i++) {
float pct = (float)i / (float)tex.width;
pixels[i].r = curve.Evaluate(pct);
range[0] = Mathf.Min(range[0], pixels[i].r);
range[1] = Mathf.Max(range[1], pixels[i].r);
}
tex.SetPixels(pixels);
tex.Apply();
return range;
}
}
#endregion
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: efccdd846892bd64594f3deedfcf5443
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1fc74a704857b7c488dcd57e5df1a155
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cb4c6151aeead304c80d208fde16c825
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,32 @@
namespace Gaia
{
/// <summary>
/// An enum used for defining which n-dimensional spaces a particular
/// NoiseType or FractalType implementation supports
/// </summary>
[System.Serializable]
[System.Flags]
public enum NoiseDimensionFlags
{
/// <summary>
/// No dimensions are supported
/// </summary>
None = 0,
/// <summary>
/// One-dimensional noise is supported
/// </summary>
_1D = ( 1 << 0 ),
/// <summary>
/// Two-dimensional noise is supported
/// </summary>
_2D = ( 1 << 1 ),
/// <summary>
/// Three-dimensional noise is supported
/// </summary>
_3D = ( 1 << 2 ),
/// <summary>
/// Four-dimensional noise is supported
/// </summary>
_4D = ( 1 << 3 ),
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 14213647eda690542800b4e4e82ff4f0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,180 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Gaia
{
/// <summary>
/// Struct that provides a definition for a FractalType implementation. Information in this
/// struct is used during Shader generation and used to determine NoiseType and
/// FractalType compatibilities.
/// </summary>
public struct FractalTypeDescriptor
{
/// <summary>
/// The name to be used for the FractalType
/// </summary>
public string name;
/// <summary>
/// The Asset path to the .noisehlsltemplate file to be used when generating shaders
/// for this FractalType variant
/// </summary>
public string templatePath;
/// <summary>
/// A flag definition the supported number of dimensions that this FractalType implements.
/// This currently is unused.
/// </summary>
public NoiseDimensionFlags supportedDimensions;
/// <summary>
/// List of HlslInput structures defining the HLSL function parameter list for this FractalType
/// </summary>
public List<HlslInput> inputStructDefinition;
/// <summary>
/// Additional include paths to be included in the generated Shader. You can add them to this
/// list or hardcode them somewhere in the Shader itself.
/// </summary>
public List<string> additionalIncludePaths;
// public List<HlslOutput> outputStructDefinition;
}
/// <summary>
/// Interface used for custom FractalType implementations. This should only be used by
/// the FractalType< T > abstract class.
/// </summary>
public interface IFractalType
{
/// <summary>
/// Returns a descriptor struct defining the FractalType
/// </summary>
FractalTypeDescriptor GetDescription();
/// <summary>
/// Returns a string that represents the default data state for the FractalType implementation
/// </summary>
string GetDefaultSerializedString();
/// <summary>
/// Sets up a Material to be used with the FractalType implementation. This function is called
/// from within NoiseSettings.SetupMaterial( Material mat )
/// </summary>
/// <param name="mat"> The Material to setup for use with this FractalType implementation </param>
/// <param name="serializedString">
/// The serialized string representing the FractalType data to
/// be used when setting up the provided Material
/// </param>
void SetupMaterial(Material mat, string serializedString);
/// <summary>
/// Renders the GUI for the FractalType implementation using the data provided by the serialized string.
/// </summary>
/// <param name="serializedString"> A string for the serialized data used by the FractalType implementation </param>
/// <returns>
/// A string for the FractalType implementation's serialized data after having gone through possible
/// changes from user interaction with the GUI
/// </returns>
string DoGUI(string serializedString);
/// <summary>
/// Renders the GUI for the FractalType implementation using the data provided by the serialized string.
/// </summary>
/// <param name="serializedString"> A string for the serialized data used by the FractalType implementation </param>
/// <returns>
/// A string for the FractalType implementation's serialized data after having gone through possible
/// changes from user interaction with the GUI
/// </returns>
string DoGUI(Rect rect, string serializedString);
/// <summary>
/// Converts an object representing the data for a FractalType implementation to a string.
/// This is later serialized and stored in a NoiseSettings Asset.
/// </summary>
/// <param name="target">
/// The data representation for the FractalType implementation to be converted
/// into a string
/// </param>
/// <returns> The string representation of the provided target object </returns>
string ToSerializedString(object target);
/// <summary>
/// Converts a string representing the data for the FractalType implementation into an
/// an actual object reference to be used with said FractalType implementation.
/// </summary>
/// <param name="serializedString">
/// A string representing a serialized object that is
/// used by the FractalType implementation
/// </param>
/// <returns> An object deserialized from the provided string </returns>
object FromSerializedString(string serializedString);
}
/// <summary>
/// A Singleton class used for representing a FractalType implementation. A FractalType class must
/// inherit from this in order to be considered a valid FractalType and included in the noise
/// shader generation and available for use with the various noise tools.
/// </summary>
public abstract class FractalType<T> : ScriptableSingleton<T>, IFractalType where T : FractalType<T>
{
/// <summary>
/// Returns a descriptor struct defining the FractalType
/// </summary>
public abstract FractalTypeDescriptor GetDescription();
/// <summary>
/// When overidden, returns a string that represents the default data state for the FractalType implementation
/// </summary>
public virtual string GetDefaultSerializedString() { return null; }
/// <summary>
/// When overidden, sets up a Material to be used with the FractalType implementation. This function is called
/// from within NoiseSettings.SetupMaterial( Material mat )
/// </summary>
/// <param name="mat"> The Material to setup for use with this FractalType implementation </param>
/// <param name="serializedString">
/// The serialized string representing the FractalType data to
/// be used when setting up the provided Material
/// </param>
public virtual void SetupMaterial(Material mat, string serializedString) { }
/// <summary>
/// When overidden, renders the GUI for the FractalType implementation using the data provided by the serialized string.
/// </summary>
/// <param name="serializedString"> A string for the serialized data used by the FractalType implementation </param>
/// <returns>
/// A string for the FractalType implementation's serialized data after having gone through possible
/// changes from user interaction with the GUI
/// </returns>
public virtual string DoGUI(string serializedString) { return null; }
/// <summary>
/// When overidden, renders the GUI for the FractalType implementation using the data provided by the serialized string.
/// </summary>
/// <param name="serializedString"> A string for the serialized data used by the FractalType implementation </param>
/// <returns>
/// A string for the FractalType implementation's serialized data after having gone through possible
/// changes from user interaction with the GUI
/// </returns>
public virtual string DoGUI(Rect rect, string serializedString) { return null; }
/// <summary>
/// When overidden, converts an object representing the data for a FractalType implementation to a string.
/// This is later serialized and stored in a NoiseSettings Asset.
/// </summary>
/// <param name="target">
/// The data representation for the FractalType implementation to be converted into a string
/// </param>
/// <returns> The string representation of the provided target object </returns>
public virtual string ToSerializedString(object target) { return null; }
/// <summary>
/// When overidden, converts a string representing the data for the FractalType implementation into an
/// an actual object reference to be used with said FractalType implementation.
/// </summary>
/// <param name="serializedString">
/// A string representing a serialized object that is used by the FractalType implementation
/// </param>
/// <returns> An object deserialized from the provided string </returns>
public virtual object FromSerializedString(string serializedString) { return null; }
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 30f8740de321d6044a89ba67e33d3d86
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,216 @@
using UnityEngine;
using UnityEditor;
using System.Text;
using System.Collections.Generic;
namespace Gaia
{
/// <summary>
/// Utility struct for creating all the different shader snippets that are
/// used when generating the shaders for the various NoiseTypes and FractalTypes
/// </summary>
internal struct GeneratedShaderInfo
{
#if UNITY_EDITOR
public FractalTypeDescriptor fractalDesc;
public NoiseTypeDescriptor noiseDesc;
#endif
public string generatedIncludePath { get; private set; }
public string additionalIncludePaths { get; private set; }
public string noiseIncludeStr { get; private set; }
public string variantName { get; private set; }
public string outputDir { get; private set; }
public string noiseStructName {get; private set;}
public string noiseStructDef {get; private set;}
public string fractalStructName {get; private set;}
public string fractalStructDef {get; private set;}
public string fractalParamStr {get; private set;}
public string noiseParamStr {get; private set;}
public string functionInputStr {get; private set;}
public string functionParamStr {get; private set;}
public string getDefaultInputsStr {get; private set;}
public string getInputsStr {get; private set;}
public string getNoiseInputStr {get; private set;}
public string getFractalInputStr {get; private set;}
public string getDefaultFractalInputStr {get; private set;}
public string getDefaultNoiseInputStr {get; private set;}
public string fractalPropertyDefStr {get; private set;}
public int numFractalInputs {get; private set;}
public int numNoiseInputs {get; private set;}
#if UNITY_EDITOR
public GeneratedShaderInfo(IFractalType fractalType, INoiseType noiseType)
{
this.fractalDesc = fractalType.GetDescription();
this.noiseDesc = noiseType.GetDescription();
this.noiseIncludeStr = string.Format("#include \"{0}\"", noiseDesc.sourcePath);
if(!string.IsNullOrEmpty(fractalDesc.name))
{
this.variantName = string.Format("{0}{1}", fractalDesc.name, noiseDesc.name);
}
else
{
this.variantName = noiseDesc.name;
}
// set the path of the generated file. this will be used when writing the file
// to disk and when adding the include in any generated shaders that use this
// fractal and noise type variant
this.generatedIncludePath = string.Format("{0}/{1}/{2}.hlsl", noiseDesc.outputDir,
fractalDesc.name,
noiseDesc.name);
this.outputDir = string.Format("{0}/{1}", noiseDesc.outputDir, fractalDesc.name);
fractalStructName = string.Format("{0}FractalInput", fractalDesc.name);
noiseStructName = string.Format("{0}NoiseInput", noiseDesc.name);
numFractalInputs = fractalDesc.inputStructDefinition == null ? 0 : fractalDesc.inputStructDefinition.Count;
numNoiseInputs = noiseDesc.inputStructDefinition == null ? 0 : noiseDesc.inputStructDefinition.Count;
fractalParamStr = null;
noiseParamStr = null;
functionInputStr = "";
// construct include paths string
additionalIncludePaths = "\n";
for(int i = 0; i < fractalDesc.additionalIncludePaths.Count; ++i)
{
additionalIncludePaths += $"#include \"{ fractalDesc.additionalIncludePaths[ i ] }\"\n";
}
additionalIncludePaths += "\n";
// generate the string for the fractal type structure as it would appear as a parameter
// in an HLSL function declaration
if( numFractalInputs > 0)
{
fractalParamStr = string.Format("{0} {1}", fractalStructName, "fractalInput");
}
// generate the string for the noise type structure as it would appear as a parameter
// in an HLSL function declaration
if( numNoiseInputs > 0 )
{
noiseParamStr = string.Format("{0} {1}", noiseStructName, "noiseInput");
}
// generate the argument string for an HLSL function declaration that would be
// using this combination of noise and fractal type structure definitions
functionParamStr = "";
if(fractalParamStr != null)
{
functionParamStr += fractalParamStr;
functionInputStr += "fractalInput";
}
if(fractalParamStr != null && noiseParamStr != null)
{
functionParamStr += ", ";
functionInputStr += ", ";
}
if(noiseParamStr != null)
{
functionParamStr += noiseParamStr;
functionInputStr += "noiseInput";
}
fractalStructDef = "";
if(numFractalInputs > 0)
{
fractalStructDef = NoiseLib.BuildStructString(fractalStructName, fractalDesc.inputStructDefinition);
string getDefaultFuncStr = NoiseLib.GetDefaultFunctionString(fractalStructName, fractalDesc.inputStructDefinition);
fractalStructDef += $"\n\n{ getDefaultFuncStr }\n\n";
}
noiseStructDef = "";
if(numNoiseInputs > 0)
{
noiseStructDef = NoiseLib.BuildStructString(noiseStructName, noiseDesc.inputStructDefinition);
}
// get input str construction
getInputsStr = "";
getFractalInputStr = NoiseLib.GetInputFunctionCallString(fractalStructName);
getNoiseInputStr = NoiseLib.GetInputFunctionCallString(fractalStructName);
if (numFractalInputs > 0)
{
getInputsStr += getFractalInputStr;
}
if (numFractalInputs > 0 && numNoiseInputs > 0)
{
getInputsStr += ", ";
}
if (numNoiseInputs > 0)
{
getInputsStr += getNoiseInputStr;
}
// get default input str construction
getDefaultInputsStr = "";
getDefaultFractalInputStr = NoiseLib.GetDefaultInputFunctionCallString(fractalStructName);
getDefaultNoiseInputStr = NoiseLib.GetDefaultInputFunctionCallString(noiseStructName);
if(numFractalInputs > 0)
{
getDefaultInputsStr += getDefaultFractalInputStr;
}
if(numFractalInputs > 0 && numNoiseInputs > 0)
{
getDefaultInputsStr += ", ";
}
if(numNoiseInputs > 0)
{
getDefaultInputsStr += getDefaultNoiseInputStr;
}
fractalPropertyDefStr = "";
if(fractalDesc.inputStructDefinition != null &&
fractalDesc.inputStructDefinition.Count > 0)
{
fractalPropertyDefStr = NoiseLib.GetPropertyDefinitionStr(fractalDesc.name, fractalDesc.inputStructDefinition);
fractalPropertyDefStr += "\n" + NoiseLib.GetPropertyFunctionStr(fractalStructName, fractalDesc.name, fractalDesc.inputStructDefinition);
}
}
#endif
public void ReplaceTags(StringBuilder sb)
{
string fractalMacroDef = fractalStructName.ToUpper() + "_DEF";
string guardedFractalDataDefinitions =
$@"
#ifndef { fractalMacroDef } // [ { fractalMacroDef }
#define { fractalMacroDef }
{fractalStructDef}
{fractalPropertyDefStr}
#endif // ] { fractalMacroDef }
";
#if UNITY_EDITOR
sb.Replace(NoiseLib.Strings.k_tagIncludes, noiseIncludeStr + additionalIncludePaths); // add the noise include
sb.Replace(NoiseLib.Strings.k_tagFractalName, fractalDesc.name); // add fractal name
sb.Replace(NoiseLib.Strings.k_tagNoiseName, noiseDesc.name); // add noise name
sb.Replace(NoiseLib.Strings.k_tagVariantName, variantName); // add combined fractal and noise name
sb.Replace(NoiseLib.Strings.k_tagFractalDataDefinitions, guardedFractalDataDefinitions);
sb.Replace(NoiseLib.Strings.k_tagFunctionParams, functionParamStr);
sb.Replace(NoiseLib.Strings.k_tagFunctionInputs, functionInputStr);
sb.Replace(NoiseLib.Strings.k_tagGetDefaultFractalInput, getDefaultFractalInputStr);
sb.Replace(NoiseLib.Strings.k_tagGetDefaultNoiseInput, getDefaultNoiseInputStr);
sb.Replace(NoiseLib.Strings.k_tagGetDefaultInputs, getDefaultInputsStr);
sb.Replace(NoiseLib.Strings.k_tagGetInputs, getInputsStr);
#endif
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8ac63c2d0bf925e4fba52fa5c5c65736
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,303 @@
using System.Collections.Generic;
using System.Globalization;
namespace Gaia
{
/// <summary>
/// Enum for determining the type of a given HLSL value during shader generation
/// </summary>
public enum HlslValueType
{
Float = 0,
Float2,
Float3,
Float4,
}
/// <summary>
/// Representation for an HLSL float
/// </summary>
public struct HlslFloat
{
/// <summary>
/// The value for the HLSL float
/// </summary>
public float val;
/// <summary>
/// The constructor for an HlslFloat
/// </summary>
/// <param name="val"> The GPU value for this HlslFloat </param>
public HlslFloat(float val)
{
this.val = val;
}
}
/// <summary>
// Representation for an HLSL float2
/// </summary>
public struct HlslFloat2
{
/// <summary>
/// The x-compenent for the HLSL float2
/// </summary>
public float x;
/// <summary>
/// The y-compenent for the HLSL float2
/// </summary>
public float y;
/// <summary>
/// The constructor for an HlslFloat2
/// </summary>
/// <param name="x"> The GPU value of the x-component to be used for this HlslFloat2 </param>
/// <param name="y"> The GPU value of the y-component to be used for this HlslFloat2 </param>
public HlslFloat2(float x, float y)
{
this.x = x;
this.y = y;
}
}
/// <summary>
/// Representation for an HLSL float3
/// </summary>
public struct HlslFloat3
{
/// <summary>
/// The x-compenent for the HLSL float3
/// </summary>
public float x;
/// <summary>
/// The y-compenent for the HLSL float3
/// </summary>
public float y;
/// <summary>
/// The z-compenent for the HLSL float3
/// </summary>
public float z;
/// <summary>
/// The constructor for an HlslFloat3
/// </summary>
/// <param name="x"> The GPU value of the x-component to be used for this HlslFloat3 </param>
/// <param name="y"> The GPU value of the y-component to be used for this HlslFloat3 </param>
/// <param name="z"> The GPU value of the z-component to be used for this HlslFloat3 </param>
public HlslFloat3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
/// <summary>
/// Representation for an HLSL float4
/// </summary>
public struct HlslFloat4
{
/// <summary>
/// The x-compenent for the HLSL float4
/// </summary>
public float x;
/// <summary>
/// The y-compenent for the HLSL float4
/// </summary>
public float y;
/// <summary>
/// The z-compenent for the HLSL float4
/// </summary>
public float z;
/// <summary>
/// The w-compenent for the HLSL float4
/// </summary>
public float w;
/// <summary>
/// The constructor for an HlslFloat4
/// </summary>
/// <param name="x"> The GPU value of the x-component to be used for this HlslFloat4 </param>
/// <param name="y"> The GPU value of the y-component to be used for this HlslFloat4 </param>
/// <param name="z"> The GPU value of the z-component to be used for this HlslFloat4 </param>
/// <param name="w"> The GPU value of the w-component to be used for this HlslFloat4 </param>
public HlslFloat4(float x, float y, float z, float w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
}
/// <summary>
/// Representation for an HLSL function input parameter
/// </summary>
public struct HlslInput
{
/// <summary>
/// The name of this HLSL function input parameter
/// </summary>
public string name;
/// <summary>
/// Returns the value type for the variable this HlslInput represents
/// </summary>
public HlslValueType valueType
{
get;
private set;
}
private HlslFloat m_floatValue;
/// <summary>
/// Returns the HLSL float value. Sets the HLSL float value and value
/// type to HlslValueType.Float
/// </summary>
public HlslFloat floatValue
{
get { return m_floatValue; }
set
{
valueType = HlslValueType.Float;
m_floatValue = value;
}
}
private HlslFloat2 m_float2Value;
/// <summary>
/// Returns the HLSL float2 value. Sets the HLSL float value and value
/// type to HlslValueType.Float2
/// </summary>
public HlslFloat2 float2Value
{
get { return m_float2Value; }
set
{
valueType = HlslValueType.Float2;
m_float2Value = value;
}
}
private HlslFloat3 m_float3Value;
/// <summary>
/// Returns the HLSL float3 value. Sets the HLSL float value and value
/// type to HlslValueType.Float3
/// </summary>
public HlslFloat3 float3Value
{
get { return m_float3Value; }
set
{
valueType = HlslValueType.Float3;
m_float3Value = value;
}
}
private HlslFloat4 m_float4Value;
/// <summary>
/// Returns the HLSL float4 value. Sets the HLSL float value and value
/// type to HlslValueType.Float4
/// </summary>
public HlslFloat4 float4Value
{
get { return m_float4Value; }
set
{
valueType = HlslValueType.Float4;
m_float4Value = value;
}
}
/// <summary>
/// Returns the string representation of the HlslValueType for this struct
/// </summary>
public string GetHlslValueTypeString()
{
switch(valueType)
{
case HlslValueType.Float:
return "float";
case HlslValueType.Float2:
return "float2";
case HlslValueType.Float3:
return "float3";
case HlslValueType.Float4:
return "float4";
}
return "unsupported_type";
}
/// <summary>
/// Returns the formatted HLSL string for the default value declaration for this struct's HlslValueType
/// </summary>
public string GetDefaultValueString()
{
string valueTypeString = GetHlslValueTypeString();
string constructedValueString = null;
switch(valueType)
{
case HlslValueType.Float:
constructedValueString = floatValue.val.ToString( CultureInfo.InvariantCulture );
break;
case HlslValueType.Float2:
constructedValueString = string.Format( CultureInfo.InvariantCulture,
"{0}({1})", valueTypeString,
float2Value.x.ToString( CultureInfo.InvariantCulture ) + ", " +
float2Value.y.ToString( CultureInfo.InvariantCulture ) );
break;
case HlslValueType.Float3:
constructedValueString = string.Format( CultureInfo.InvariantCulture,
"{0}({1})", valueTypeString,
float3Value.x.ToString( CultureInfo.InvariantCulture ) + ", " +
float3Value.y.ToString( CultureInfo.InvariantCulture ) + ", " +
float3Value.z.ToString( CultureInfo.InvariantCulture ) );
break;
case HlslValueType.Float4:
constructedValueString = string.Format( CultureInfo.InvariantCulture,
"{0}({1})", valueTypeString,
float4Value.x.ToString( CultureInfo.InvariantCulture ) + ", " +
float4Value.y.ToString( CultureInfo.InvariantCulture ) + ", " +
float4Value.z.ToString( CultureInfo.InvariantCulture ) + ", " +
float4Value.w.ToString( CultureInfo.InvariantCulture ) );
break;
default:
return "unsupported_type()";
}
return constructedValueString;
}
}
// public struct HlslOutput
// {
// public string name;
// public HlslValueType valueType;
// public HlslOutput(string name, HlslValueType valueType)
// {
// this.name = name;
// this.valueType = valueType;
// }
// }
// public struct HlslStructDescriptor
// {
// public List<HlslInput> members;
// }
// public struct HlslFunctionDescriptor
// {
// public List<HlslInput> inputs;
// public List<HlslOutput> outputs;
// }
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8ed0c9e52d7bd0f41a31a70e15466f65
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0632acc5c6752b44cb61ea7d5928279f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,64 @@
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
namespace Gaia
{
/// <summary>
/// Struct defining the description for a NoiseShaderGenerator
/// </summary>
public struct ShaderGeneratorDescriptor
{
/// <summary>
/// The name of the NoiseShaderGenerator
/// </summary>
public string name;
/// <summary>
/// The Shader Category for Shaders generated by the NoiseShaderGenerator
/// </summary>
public string shaderCategory;
/// <summary>
/// The path specifying where the Shaders generated by the NoiseShaderGenerator
/// should be written to disk
/// </summary>
public string outputDir;
/// <summary>
/// The path to the ".noisehlsltemplate" file to be used in the NoiseShaderGenerator's
/// Shader generation.
/// </summary>
public string templatePath;
}
/// <summary>
/// Interface for NoiseShaderGenerator. Do not implement this directly. Inherit from the
/// NoiseShaderGenerator< T > generic abstract class, instead.
/// </summary>
public interface INoiseShaderGenerator
{
/// <summary>
/// Returns a description for the NoiseShaderGenerator implementation
/// </summary>
ShaderGeneratorDescriptor GetDescription();
}
/// <summary>
/// Singleton base class for a NoiseShaderGenerator implementation. Inherit from this if you want
/// your shaders to get generated
/// </summary>
public abstract class NoiseShaderGenerator<T> : ScriptableSingleton<T>, INoiseShaderGenerator where T : NoiseShaderGenerator<T>
{
/// <summary>
/// Returns a description for the NoiseShaderGenerator implementation
/// </summary>
public abstract ShaderGeneratorDescriptor GetDescription();
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 687e8089080b8ef4aafcfe30ba68ee6e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,25 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor.Experimental.AssetImporters;
namespace Gaia
{
/// <summary>
/// Asset importer for noise template files. Used to detect when a noise template is imported and checks to see if the shaders need to be regenerated.
/// </summary>
//public class NoiseTemplateImporter : ScriptedImporter
//{
// /// <summary>
// /// Function that is called when an asset with the ".noisehlsltemplate" extension is imported by the AssetDatabase
// /// </summary>
// /// <param name = "ctx"> The context for the imported asset </param>
// public override void OnImportAsset(AssetImportContext ctx)
// {
// //NoiseLib.GenerateHeaderFiles();
// //NoiseLib.GenerateShaders();
// }
//}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a5326fcdff837a045886b69226c13139
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,162 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Gaia
{
/// <summary>
/// Struct used for defining a NoiseType implementation. Information in this struct
/// is used in shader generation and for determining compatabilities with
/// FractalType implementations.
/// </summary>
public struct NoiseTypeDescriptor
{
/// <summary>
/// The name of the NoiseType implementation
/// </summary>
public string name;
/// <summary>
/// The path to the directory where the generated shader files for this NoiseType
/// should be written to disk.
/// </summary>
public string outputDir;
/// <summary>
/// The file path of the HLSL file containing the implementation for this NoiseType
/// </summary>
public string sourcePath;
/// <summary>
/// Flags that represented the dimensions this NoiseType implementation supports
/// </summary>
public NoiseDimensionFlags supportedDimensions;
/// <summary>
/// List of HlslInput structs defining the HLSL function parameter list for this
/// NoiseType implementation. This is used in the noise shader generation.
/// </summary>
public List<HlslInput> inputStructDefinition;
// TODO(wyatt): output structs would be useful for things like curl
// noise and anything requiring derivatives
// public List<HlslOutput> outputStructDefinition;
}
/// <summary>
/// Interface for defining a NoiseType implementation. Don't implement directly from this but
/// instead make your NoiseType implementation inherit from the NoiseType< T > generic abstract class.
/// </summary>
public interface INoiseType
{
/// <summary>
/// Returns a description of the NoiseType implementation
/// </summary>
NoiseTypeDescriptor GetDescription();
/// <summary>
/// Returns a string representing the default state of the data that this NoiseType
/// implementation uses.
/// </summary>
string GetDefaultSerializedString();
/// <summary>
/// Renders the GUI for the NoiseType implementation using the data provided by the serialized string.
/// </summary>
/// <param name="serializedString"> A string for the serialized data used by the NoiseType implementation </param>
/// <returns>
/// A string for the NoiseType implementation's serialized data after having gone through possible
/// changes from user interaction with the GUI
/// </returns>
string DoGUI(string serializedString);
/// <summary>
/// Sets up a Material to be used with the NoiseType implementation. This function is called
/// from within NoiseSettings.SetupMaterial( Material mat )
/// </summary>
/// <param name="mat"> The Material to setup for use with this NoiseType implementation </param>
/// <param name="serializedString">
/// The serialized string representing the NoiseType data to
/// be used when setting up the provided Material
/// </param>
void SetupMaterial(Material mat, string serializedString);
/// <summary>
/// When overidden, converts an object representing the data for a NoiseType implementation to a string.
/// This is later serialized and stored in a NoiseSettings Asset.
/// </summary>
/// <param name="target">
/// The data representation for the NoiseType implementation to be converted
/// into a string
/// </param>
/// <returns> The string representation of the provided target object </returns>
string ToSerializedString(object target);
/// <summary>
/// When overidden, converts a string representing the data for the NoiseType implementation into an
/// an actual object reference to be used with said NoiseType implementation.
/// </summary>
/// <param name="serializedString">
/// A string representing a serialized object that is
/// used by the NoiseType implementation
/// </param>
/// <returns> An object deserialized from the provided string </returns>
object FromSerializedString(string serializedString);
}
#if UNITY_EDITOR
/// <summary>
/// A Singleton class used for representing a NoiseType implementation. A NoiseType class must
/// inherit from this in order to be considered a valid NoiseType and included in the noise
/// shader generation and available for use with the various noise tools.
/// </summary>
public abstract class NoiseType<T> : ScriptableSingleton<T>, INoiseType where T : NoiseType<T>
{
/// <summary>
/// Returns a descriptor struct defining the NoiseType
/// </summary>
public abstract NoiseTypeDescriptor GetDescription();
/// <summary>
/// When overidden, returns a string that represents the default data state for the NoiseType implementation
/// </summary>
public virtual string GetDefaultSerializedString() { return null; }
/// <summary>
/// When overidden, sets up a Material to be used with the NoiseType implementation. This function is called
/// from within NoiseSettings.SetupMaterial( Material mat )
/// </summary>
/// <param name="mat"> The Material to setup for use with this NoiseType implementation </param>
/// <param name="serializedString">
/// The serialized string representing the NoiseType data to
/// be used when setting up the provided Material
/// </param>
public virtual void SetupMaterial(Material mat, string serializedString) { }
/// <summary>
/// When overidden, renders the GUI for the NoiseType implementation using the data provided by the serialized string.
/// </summary>
/// <param name="serializedString"> A string for the serialized data used by the NoiseType implementation </param>
/// <returns>
/// A string for the NoiseType implementation's serialized data after having gone through possible
/// changes from user interaction with the GUI
/// </returns>
public virtual string DoGUI(string serializedString) { return null; }
/// <summary>
/// When overidden, converts an object representing the data for a NoiseType implementation to a string.
/// This is later serialized and stored in a NoiseSettings Asset.
/// </summary>
/// <param name="target">
/// The data representation for the NoiseType implementation to be converted into a string
/// </param>
/// <returns> The string representation of the provided target object </returns>
public virtual string ToSerializedString(object target) { return null; }
/// <summary>
/// When overidden, converts a string representing the data for the NoiseType implementation into an
/// an actual object reference to be used with said NoiseType implementation.
/// </summary>
/// <param name="serializedString">
/// A string representing a serialized object that is used by the NoiseType implementation
/// </param>
/// <returns> An object deserialized from the provided string </returns>
public virtual object FromSerializedString(string serializedString) { return null; }
}
#endif
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c544eb5e7747bd54db98ea4b9de043f3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,329 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
using System;
using System.Collections.Generic;
using UnityEngine.Experimental.Rendering;
namespace Gaia
{
/// <summary>
/// A utility class for rendering noise defined by NoiseSettings into various Texture types.
/// </summary>
public static class NoiseUtils
{
// private static readonly int kAllSlices = -1;
/// <summary>
/// Number of passes that the builtin noise blit shader contains. The passes include
/// one for blitting 2D noise and one for blitting 3D noise.
/// </summary>
public static readonly int kNumBlitPasses = 2;
private static bool supportsCopyTexture3D
{
get { return (SystemInfo.copyTextureSupport & CopyTextureSupport.Copy3D) != 0; }
}
private static bool supportsCopyTextureRTToTexture
{
get { return (SystemInfo.copyTextureSupport & CopyTextureSupport.RTToTexture) != 0; }
}
static NoiseUtils()
{
}
/*=========================================================================
Material Getter Functions
=========================================================================*/
private static Material s_defaultPreviewMaterial;
private static Material GetDefaultPreviewMaterial()
{
if(s_defaultPreviewMaterial == null)
{
s_defaultPreviewMaterial = new Material(Shader.Find("Hidden/TerrainTools/Noise/Preview"));
}
return s_defaultPreviewMaterial;
}
/// <summary>
/// Returns a Material reference to the default blit material for the given Type of FractalType.
/// </summary>
/// <remarks> Usage is: Material mat = GetDefaultBlitMaterial( typeof(FbmFractalType) ); </remarks>
/// <returns> A reference to the default blit Material for the specified Type of FractalType </return>
/// <param name="fractalType"> The Type for a given FractalType </param>
public static Material GetDefaultBlitMaterial(Type fractalType)
{
return NoiseLib.GetGeneratedMaterial(typeof(NoiseBlitShaderGenerator), fractalType);
}
/// <summary>
/// Returns a Material reference to the default blit material for the given NoiseSettings object.
/// </summary>
/// <remarks>
/// Internally, this uses noise.domainSettings.fractalTypeName to get it's FractalType
/// </remarks>
/// <returns> A reference to the default blit Material for the specified NoiseSettings instance </returns>
public static Material GetDefaultBlitMaterial(NoiseSettings noise)
{
IFractalType fractal = NoiseLib.GetFractalTypeInstance( noise.domainSettings.fractalTypeName );
if(fractal == null)
{
return null;
}
return GetDefaultBlitMaterial( fractal.GetType() );
}
/*=========================================================================
Blit Noise using Preview shader
=========================================================================*/
/// <summary>
/// Blits the source RenderTexture into the destination RenderTexture using the default Preview Blit Material.
/// This is the blit Material that is used when rendering the NoiseSettings Preview.
/// </summary>
/// <param name = "source"> The source RenderTexture used in the Blit operation </param>
/// <param name = "destination">
/// The destination RenderTexture in the Blit operation
/// This will have the noise preview shader logic applied to it.
/// </param>
public static void BlitPreview2D(RenderTexture source, RenderTexture destination)
{
BlitPreview2D(source, destination, GetDefaultPreviewMaterial());
}
/// <summary>
/// Blits the source RenderTexture into the destination RenderTexture using the specified Material.
/// </summary>
/// <param name = "source"> The source RenderTexture used in the Blit operation </param>
/// <param name = "destination">
/// The destination RenderTexture in the Blit operation
/// This will have the noise preview shader logic applied to it.
/// </param>
/// <param name="mat"> The material to be used in the blit operation </param>
public static void BlitPreview2D(RenderTexture src, RenderTexture dest, Material mat)
{
if(mat == null)
{
Debug.LogError("NoiseUtils::BlitPreview2D: Provided preview material is NULL");
Graphics.Blit(src, dest);
return;
}
Graphics.Blit(src, dest, mat, 0);
}
/*=========================================================================
Blit
- Blit raw noise data into texture
=========================================================================*/
/// <summary>
/// Blits 2D noise defined by the given NoiseSettings instance into the destination RenderTexture.
/// </summary>
/// <param name = "noise"> An instance of NoiseSettings defining the type of noise to render </param>
/// <param name = "dest"> The destination RenderTexture that the noise will be rendered into. </param>
public static void Blit2D(NoiseSettings noise, RenderTexture dest)
{
Material mat = GetDefaultBlitMaterial( noise );
if( mat == null )
{
return;
}
Blit2D( noise, dest, mat );
}
/// <summary>
/// Blits 2D noise defined by the given NoiseSettings instance into the destination RenderTexture
/// using the provided Material.
/// </summary>
/// <param name = "noise"> An instance of NoiseSettings defining the type of noise to render </param>
/// <param name = "dest"> The destination RenderTexture that the noise will be rendered into. </param>
/// <param name = "mat"> The Material to be used for rendering the noise </param>
public static void Blit2D(NoiseSettings noise, RenderTexture dest, Material mat)
{
int pass = NoiseLib.GetNoiseIndex( noise.domainSettings.noiseTypeName );
INTERNAL_Blit2D( noise, dest, mat, pass * kNumBlitPasses + 0 );
}
private static void INTERNAL_Blit2D(NoiseSettings noise, RenderTexture dest, Material mat, int pass)
{
noise.SetupMaterial( mat );
RenderTexture tempRT = RenderTexture.GetTemporary(dest.descriptor);
RenderTexture prev = RenderTexture.active;
RenderTexture.active = tempRT;
Graphics.Blit(tempRT, mat, pass);
RenderTexture.active = dest;
// if(noise.filterSettings.filterStack != null)
// {
// noise.filterSettings.filterStack.Eval(tempRT, dest);
// }
// else
{
Graphics.Blit( tempRT, dest );
}
RenderTexture.active = prev;
RenderTexture.ReleaseTemporary(tempRT);
}
/// <summary>
/// Blits 3D noise defined by the given NoiseSettings instance into the destination RenderTexture.
/// </summary>
/// <param name = "noise"> An instance of NoiseSettings defining the type of noise to render </param>
/// <param name = "dest"> The destination RenderTexture that the noise will be rendered into. </param>
public static void Blit3D(NoiseSettings noise, RenderTexture dest)
{
throw new NotImplementedException("NoiseUtils::Blit3D: Function not implemented yet");
// Debug.Assert(dest.dimension == UnityEngine.Rendering.TextureDimension.Tex3D,
// "NoiseUtils::Blit3D: Provided RenderTexture is not a 3D texture. You have to manually create it as a volume");
// Material mat = GetDefaultBlitMaterial(noise);
// if(mat == null)
// {
// return;
// }
// int pass = NoiseLib.GetNoiseIndex(noise.domainSettings.noiseTypeName);
// RenderTexture prev = RenderTexture.active;
// Graphics.SetRenderTarget(dest, 0, CubemapFace.Unknown, kAllSlices);
// // Graphics.Blit( dest, mat, )
// RenderTexture.active = prev;
}
/// <summary>
/// Bakes 2D noise defined by the given NoiseSettings instance into a Texture2D instance and returns
/// a reference to it.
/// </summary>
/// <param name = "noise"> An instance of NoiseSettings defining the type of noise to bake </param>
/// <param name = "width"> The width of the baked Texture2D </param>
/// <param name = "height"> The height of the baked Texture2D </param>
/// <param name = "format"> The GraphicsFormat for the baked Texture2D. In most cases, you will want to use GraphicsFormat.R16_UNorm </param>
/// <param name = "flags"> TextureCreation flags for the baked Texture2D </param>
/// <returns> A reference to the baked Texture2D instance </returns>
public static Texture2D BakeToTexture2D(NoiseSettings noise, int width, int height,
GraphicsFormat format = GraphicsFormat.R16_UNorm,
TextureCreationFlags flags = TextureCreationFlags.None)
{
RenderTexture rt = RenderTexture.GetTemporary(width, height, 0, GraphicsFormat.R16_UNorm);
Texture2D texture = new Texture2D( width, height, format, flags );
Blit2D(noise, rt);
RenderTexture.active = rt;
bool mipChain = ( (int)flags & (int)TextureCreationFlags.MipChain ) != 0;
texture.ReadPixels( new Rect( 0, 0, width, height ), 0, 0, mipChain );
RenderTexture.active = null;
RenderTexture.ReleaseTemporary( rt );
return texture;
}
/// <summary>
/// Bakes 3D noise defined by the given NoiseSettings instance into a Texture3D instance and returns
/// a reference to it.
/// </summary>
/// <param name = "noise"> An instance of NoiseSettings defining the type of noise to bake </param>
/// <param name = "width"> The width of the baked Texture3D </param>
/// <param name = "height"> The height of the baked Texture3D </param>
/// <param name = "depth"> The depth of the baked Texture3D </param>
/// <param name = "format"> The GraphicsFormat for the baked Texture3D. In most cases, you will want to use GraphicsFormat.R16_UNorm </param>
/// <param name = "flags"> TextureCreation flags for the baked Texture3D. </param>
/// <returns> A reference to the baked Texture3D instance </returns>
/// <remarks>
/// Be careful when specifying TextureCreation flags. If you specify that mipmaps should be generated for
/// a Texture3D, that will use a lot more memory than if you were generating mipmaps for a Texture2D.
/// </remarks>
public static Texture3D BakeToTexture3D(NoiseSettings noise, int width, int height, int depth,
GraphicsFormat format = GraphicsFormat.R16_UNorm,
TextureCreationFlags flags = TextureCreationFlags.None)
{
Material mat = GetDefaultBlitMaterial( noise );
if(mat == null)
{
return null;
}
RenderTexture sliceRT = RenderTexture.GetTemporary(width, height, 0, GraphicsFormat.R16_UNorm);
Texture2D slice2D = new Texture2D(width, height, format, flags);
Color[] colors = new Color[width * height * depth];
noise.SetupMaterial(mat);
int pass = NoiseLib.GetNoiseIndex(noise);
RenderTexture.active = sliceRT;
List<Color[]> sliceColors = new List<Color[]>(depth);
for(int i = 0; i < depth; ++i)
{
float uvy = ((float)i + 0.5f) / depth;
mat.SetFloat("_UVY", uvy);
Graphics.Blit(null, sliceRT, mat, pass * kNumBlitPasses + 1);
slice2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
sliceColors.Add(slice2D.GetPixels(0, 0, width, height));
}
int pixPerSlice = width * height;
for(int sliceID = 0; sliceID < sliceColors.Count; ++sliceID)
{
for(int pixelID = 0; pixelID < sliceColors[sliceID].Length; ++pixelID)
{
int pixel = (pixPerSlice * sliceID) + pixelID;
colors[pixel] = sliceColors[sliceID][pixelID];
}
}
bool mipChain = ( (int)flags & (int)TextureCreationFlags.MipChain ) != 0;
Texture3D texture = new Texture3D(width, height, depth, format, flags);
texture.SetPixels(colors);
texture.Apply(mipChain);
RenderTexture.active = null;
RenderTexture.ReleaseTemporary( sliceRT );
return texture;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 32f30b28138f17a44b58e260d38fb032
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace Gaia
{
/// <summary>
/// A NoiseType implementation for Billow noise
/// </summary>
[System.Serializable]
public class BillowNoise : NoiseType<BillowNoise>
{
private static NoiseTypeDescriptor desc = new NoiseTypeDescriptor()
{
name = "Billow",
outputDir = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib",
sourcePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Implementation/BillowImpl.hlsl",
supportedDimensions = NoiseDimensionFlags._1D | NoiseDimensionFlags._2D | NoiseDimensionFlags._3D,
inputStructDefinition = null
// inputStructDefinition = new List<HlslInput>()
// {
// new HlslInput() { name = "scale", valueType = HlslValueType.Float4, float4Value = new HlslFloat4(1,1,1,1) }
// }
};
public override NoiseTypeDescriptor GetDescription() => desc;
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9d4f9a13533f66141aa625dff42dcc36
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 451a2732ca7e0564ea31eed915f0d10c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,211 @@
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace Gaia
{
/// <summary>
/// Class that implements EditorWindow in order to provide options for exporting noise to
/// textures that can be saved to disk.
/// </summary>
public class ExportNoiseWindow : EditorWindow
{
public static void ShowWindow( NoiseSettings noise )
{
var wnd = ScriptableObject.CreateInstance<ExportNoiseWindow>();
wnd.titleContent = Styles.title;
wnd.Init( noise );
wnd.minSize = new Vector2( 400f, 160f );
wnd.maxSize = new Vector2( 400f, 160f );
wnd.Show();
}
private enum ExportMode
{
Texture2D = 0,
Texture3D,
}
private NoiseSettings m_noise;
private ExportMode m_exportMode = ExportMode.Texture2D;
private Vector2Int dims2D = new Vector2Int(512,512);
private Vector3Int dims3D = new Vector3Int(64, 64, 64);
private bool m_normalize;
private GraphicsFormat m_format = GraphicsFormat.R16_UNorm;
/// <summary>
/// Initializes the ExportNoiseWindow instance with the given NoiseSettings instance.
/// </summary>
/// <param name = "noise"> The NoiseSettings instance to be used with this ExportNoiseWindow instance </param>
public void Init( NoiseSettings noise )
{
m_noise = noise;
}
/// <summary>
/// Renders the GUI for the ExportNoiseWindow instance
/// </summary>
public void OnGUI()
{
GUILayout.Space(16);
using( new EditorGUI.DisabledScope(true) )
{
EditorGUILayout.ObjectField(Styles.noise, m_noise, typeof(NoiseSettings), false);
}
m_exportMode = ( ExportMode )EditorGUILayout.EnumPopup( Styles.exportMode, m_exportMode );
EditorGUILayout.BeginHorizontal();
{
if(m_exportMode == ExportMode.Texture2D)
{
EditorGUILayout.PrefixLabel( Styles.dims2D );
dims2D = EditorGUILayout.Vector2IntField(GUIContent.none, dims2D);
}
else if(m_exportMode == ExportMode.Texture3D)
{
EditorGUILayout.PrefixLabel( Styles.dims3D );
dims3D = EditorGUILayout.Vector3IntField(GUIContent.none, dims3D);
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel( Styles.normalize );
m_normalize = GUILayout.Toggle( m_normalize, GUIContent.none );
}
EditorGUILayout.EndHorizontal();
m_format = ( GraphicsFormat )EditorGUILayout.EnumPopup( Styles.format, m_format );
GUILayout.Space(16);
if( GUILayout.Button(Styles.export) )
{
if(m_exportMode == ExportMode.Texture2D)
{
Export2D();
}
else if(m_exportMode == ExportMode.Texture3D)
{
Export3D();
}
}
}
private void Export2D()
{
Texture2D texture = null;
try
{
string path = EditorUtility.SaveFilePanel("Export Noise To Texture2D",
Application.dataPath,
"New Noise Texture2D.png",
"png");
if(!path.StartsWith(Application.dataPath))
{
Debug.LogError("You must specificy a path in your project's Assets folder to export a Noise Texture");
}
if(!string.IsNullOrEmpty(path) )
{
EditorUtility.DisplayProgressBar("Exporting Noise to Texture2D", "Making some noise...", 0.1f);
texture = NoiseUtils.BakeToTexture2D( m_noise, dims2D.x, dims2D.y, m_format, TextureCreationFlags.None );
byte[] bytes = ImageConversion.EncodeToPNG(texture);
System.IO.File.WriteAllBytes(path, bytes);
Texture2D.DestroyImmediate(texture);
texture = null;
string assetPath = path.Remove(0, Application.dataPath.Length - "Assets".Length);
AssetDatabase.Refresh();
EditorUtility.ClearProgressBar();
texture = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
EditorGUIUtility.PingObject(texture);
}
}
catch(Exception e)
{
Debug.LogError( e );
if(texture != null)
{
Texture2D.DestroyImmediate( texture );
}
Debug.Log("Exception caught");
EditorUtility.ClearProgressBar();
}
}
private void Export3D()
{
Texture3D texture = null;
try
{
string path = EditorUtility.SaveFilePanel("Export Noise To Texture3D",
Application.dataPath,
"New Noise Texture3D.asset",
"asset");
if(!path.StartsWith(Application.dataPath))
{
Debug.LogError("You must specificy a path in your project's Assets folder to export a Noise Texture");
}
if(!string.IsNullOrEmpty(path) && path.StartsWith(Application.dataPath))
{
EditorUtility.DisplayProgressBar("Exporting Noise to Texture3D", "Making some noise...", 0.1f);
texture = NoiseUtils.BakeToTexture3D( m_noise, dims3D.x, dims3D.y, dims3D.z, m_format, TextureCreationFlags.None );
AssetDatabase.CreateAsset(texture, path.Remove(0, Application.dataPath.Length - "Assets".Length));
AssetDatabase.Refresh();
EditorUtility.ClearProgressBar();
EditorGUIUtility.PingObject(texture);
}
}
catch(Exception e)
{
Debug.LogError( e );
if(texture != null)
{
Texture2D.DestroyImmediate( texture );
}
EditorUtility.ClearProgressBar();
}
}
private static class Styles
{
public static GUIContent title = EditorGUIUtility.TrTextContent("Export Noise to Texture");
public static GUIContent noise = EditorGUIUtility.TrTextContent("Noise Settings");
public static GUIContent normalize = EditorGUIUtility.TrTextContent("Normalize", "Normalize pixel values so they fit between a 0 - 1 range");
public static GUIContent exportMode = EditorGUIUtility.TrTextContent("Export Mode");
public static GUIContent export = EditorGUIUtility.TrTextContent("Export");
public static GUIContent dims2D = EditorGUIUtility.TrTextContent("Dimensions", "Texture Dimensions. X = Width, Y = Height");
public static GUIContent dims3D = EditorGUIUtility.TrTextContent("Dimensions", "Texture Dimensions. X = Width, Y = Height, Z = Depth");
public static GUIContent format = EditorGUIUtility.TrTextContent("Texture Format");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 47cc22713fb2c814ba1cfea6d5d2bfd9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,267 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Gaia
{
/// <summary>
/// A FractalType implementation for Fractal Brownian Motion
/// </summary>
[System.Serializable]
public class FbmFractalType : FractalType<FbmFractalType>
{
[System.Serializable]
public struct FbmFractalInput
{
public Vector4 warpOffsets;
public Vector2 octavesMinMax;
public Vector2 amplitudeMinMax;
public Vector2 frequencyMinMax;
public Vector2 lacunarityMinMax;
public Vector2 persistenceMinMax;
public Vector2 warpIterationsMinMax;
public Vector2 warpStrengthMinMax;
public float octaves;
public float amplitude;
public float frequency;
public float persistence;
public float lacunarity;
public float warpIterations;
public float warpStrength;
public bool warpEnabled;
public bool warpExpanded;
public void Reset()
{
octaves = 8;
amplitude = .5f;
frequency = 1;
lacunarity = 2;
persistence = .5f;
octavesMinMax = new Vector2(0, 16);
amplitudeMinMax = new Vector2(0, 1);
frequencyMinMax = new Vector2(0, 2);
lacunarityMinMax = new Vector2(0, 4);
persistenceMinMax = new Vector2(0, 1);
warpExpanded = true;
warpEnabled = false;
warpIterations = 1;
warpStrength = .5f;
warpOffsets = new Vector4(2.5f, 1.4f, 3.2f, 2.7f);
warpIterationsMinMax = new Vector2(0, 8);
warpStrengthMinMax = new Vector2(-2, 2);
}
}
[SerializeField]
private FbmFractalInput m_input;
public override FractalTypeDescriptor GetDescription() => new FractalTypeDescriptor()
{
name = "Fbm",
templatePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Templates/FractalFbm.noisehlsltemplate",
supportedDimensions = NoiseDimensionFlags._1D | NoiseDimensionFlags._2D | NoiseDimensionFlags._3D,
inputStructDefinition = new List<HlslInput>()
{
new HlslInput() { name = "octaves", floatValue = new HlslFloat(8.0f) },
new HlslInput() { name = "amplitude", floatValue = new HlslFloat(.5f) },
new HlslInput() { name = "persistence", floatValue = new HlslFloat(.5f) },
new HlslInput() { name = "frequency", floatValue = new HlslFloat(1) },
new HlslInput() { name = "lacunarity", floatValue = new HlslFloat(2) },
new HlslInput() { name = "warpIterations", floatValue = new HlslFloat(0) },
new HlslInput() { name = "warpStrength", floatValue = new HlslFloat(.5f) },
new HlslInput() { name = "warpOffsets", float4Value = new HlslFloat4(2.5f, 1.4f, 3.2f, 2.7f) }
},
additionalIncludePaths = new List<string>()
{
"Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/NoiseCommon.hlsl"
}
};
public override string GetDefaultSerializedString()
{
FbmFractalInput fbm = new FbmFractalInput();
fbm.Reset();
return ToSerializedString(fbm);
}
public override string DoGUI(Rect rect, string serializedString)
{
if (string.IsNullOrEmpty(serializedString))
{
serializedString = GetDefaultSerializedString();
}
// deserialize string
FbmFractalInput fbm = (FbmFractalInput)FromSerializedString(serializedString);
// do gui here
fbm.octaves = EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.octaves, fbm.octaves, fbm.octavesMinMax.x, fbm.octavesMinMax.y);
rect.y += EditorGUIUtility.singleLineHeight;
fbm.amplitude = EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.amplitude, fbm.amplitude, fbm.amplitudeMinMax.x, fbm.amplitudeMinMax.y);
rect.y += EditorGUIUtility.singleLineHeight;
fbm.persistence = EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.persistence, fbm.persistence, fbm.persistenceMinMax.x, fbm.persistenceMinMax.y);
rect.y += EditorGUIUtility.singleLineHeight;
fbm.frequency = EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.frequency, fbm.frequency, fbm.frequencyMinMax.x, fbm.frequencyMinMax.y);
rect.y += EditorGUIUtility.singleLineHeight;
fbm.lacunarity = EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.lacunarity, fbm.lacunarity, fbm.lacunarityMinMax.x, fbm.lacunarityMinMax.y);
rect.y += EditorGUIUtility.singleLineHeight;
//bool toggled = fbm.warpEnabled;
fbm.warpExpanded = EditorGUI.Foldout(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), fbm.warpExpanded, Styles.domainWarpSettings);
if (fbm.warpExpanded)
{
EditorGUI.indentLevel++;
{
rect.y += EditorGUIUtility.singleLineHeight;
DomainWarpSettingsGUI(ref fbm, rect);
}
EditorGUI.indentLevel--;
}
//fbm.warpEnabled = toggled;
return ToSerializedString(fbm);
}
public override string DoGUI(string serializedString)
{
if (string.IsNullOrEmpty(serializedString))
{
serializedString = GetDefaultSerializedString();
}
// deserialize string
FbmFractalInput fbm = (FbmFractalInput)FromSerializedString(serializedString);
// do gui here
fbm.octaves = EditorGUILayout.Slider(Styles.octaves, fbm.octaves, fbm.octavesMinMax.x, fbm.octavesMinMax.y);
fbm.amplitude = EditorGUILayout.Slider(Styles.amplitude, fbm.amplitude, fbm.amplitudeMinMax.x, fbm.amplitudeMinMax.y);
fbm.persistence = EditorGUILayout.Slider(Styles.persistence, fbm.persistence, fbm.persistenceMinMax.x, fbm.persistenceMinMax.y);
fbm.frequency = EditorGUILayout.Slider(Styles.frequency, fbm.frequency, fbm.frequencyMinMax.x, fbm.frequencyMinMax.y);
fbm.lacunarity = EditorGUILayout.Slider(Styles.lacunarity, fbm.lacunarity, fbm.lacunarityMinMax.x, fbm.lacunarityMinMax.y);
bool toggled = fbm.warpEnabled;
fbm.warpExpanded = TerrainToolGUIHelper.DrawToggleHeaderFoldout(Styles.domainWarpSettings, fbm.warpExpanded, ref toggled);
if (fbm.warpExpanded)
{
EditorGUI.indentLevel++;
{
DomainWarpSettingsGUI(ref fbm);
}
EditorGUI.indentLevel--;
}
fbm.warpEnabled = toggled;
return ToSerializedString(fbm);
}
private void DomainWarpSettingsGUI(ref FbmFractalInput fbm)
{
using(new EditorGUI.DisabledScope(!fbm.warpEnabled))
{
fbm.warpIterations = EditorGUILayout.Slider(Styles.warpIterations, fbm.warpIterations, fbm.warpIterationsMinMax.x, fbm.warpIterationsMinMax.y);
fbm.warpStrength = EditorGUILayout.Slider(Styles.warpStrength, fbm.warpStrength, fbm.warpStrengthMinMax.x, fbm.warpStrengthMinMax.y);
fbm.warpOffsets = EditorGUILayout.Vector4Field(Styles.warpOffsets, fbm.warpOffsets);
}
}
private void DomainWarpSettingsGUI(ref FbmFractalInput fbm, Rect rect)
{
fbm.warpEnabled = EditorGUI.Toggle(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.warpEnabled, fbm.warpEnabled);
rect.y += EditorGUIUtility.singleLineHeight;
using (new EditorGUI.DisabledScope(!fbm.warpEnabled))
{
fbm.warpIterations = EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.warpIterations, fbm.warpIterations, fbm.warpIterationsMinMax.x, fbm.warpIterationsMinMax.y);
rect.y += EditorGUIUtility.singleLineHeight;
fbm.warpStrength = EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.warpStrength, fbm.warpStrength, fbm.warpStrengthMinMax.x, fbm.warpStrengthMinMax.y);
rect.y += EditorGUIUtility.singleLineHeight;
fbm.warpOffsets = EditorGUI.Vector4Field(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), Styles.warpOffsets, fbm.warpOffsets);
rect.y += EditorGUIUtility.singleLineHeight;
}
}
public override void SetupMaterial(Material mat, string serializedString)
{
if (string.IsNullOrEmpty(serializedString))
{
serializedString = GetDefaultSerializedString();
}
FbmFractalInput fbm = (FbmFractalInput)FromSerializedString(serializedString);
// set noise domain values
mat.SetFloat("_FbmOctaves", fbm.octaves);
mat.SetFloat("_FbmAmplitude", fbm.amplitude);
mat.SetFloat("_FbmFrequency", fbm.frequency);
mat.SetFloat("_FbmPersistence", fbm.persistence);
mat.SetFloat("_FbmLacunarity", fbm.lacunarity);
// warp values
mat.SetFloat("_FbmWarpIterations", fbm.warpEnabled ? fbm.warpIterations : 0);
mat.SetFloat("_FbmWarpStrength", fbm.warpStrength);
mat.SetVector("_FbmWarpOffsets", fbm.warpOffsets);
}
public override string ToSerializedString(object target)
{
if(target == null)
{
return null;
}
if(!(target is FbmFractalInput))
{
Debug.LogError($"Attempting to serialize an object that is not of type {typeof(FbmFractalInput)}");
return null;
}
FbmFractalInput fbm = (FbmFractalInput)target;
string serializedString = JsonUtility.ToJson(fbm);
return serializedString;
}
public override object FromSerializedString(string serializedString)
{
if(string.IsNullOrEmpty(serializedString))
{
serializedString = GetDefaultSerializedString();
}
// TODO(wyatt): do validation/upgrading here
FbmFractalInput target = JsonUtility.FromJson<FbmFractalInput>(serializedString);
return target;
}
private static class Styles
{
public static GUIContent warpEnabled = EditorGUIUtility.TrTextContent("Enabled", "Turn on/off warp");
public static GUIContent warpStrength = EditorGUIUtility.TrTextContent("Strength", "The overall strength of the warping effect");
public static GUIContent warpIterations = EditorGUIUtility.TrTextContent("Iterations", "The number of warping iterations applied to the Noise");
public static GUIContent warpOffsets = EditorGUIUtility.TrTextContent("Offset", "The offset direction to be used when warping the Noise");
public static GUIContent domainWarpSettings = EditorGUIUtility.TrTextContent("Warp Settings", "Settings for applying turbulence to the Noise");
public static GUIContent octaves = EditorGUIUtility.TrTextContent("Octaves", "The number of Octaves of Noise to generate. Each Octave is generally a smaller scale than the previous Octave and a larger scale than the next");
public static GUIContent amplitude = EditorGUIUtility.TrTextContent("Amplitude", "The unmodified amplitude applied to each Octave of Noise. At each Octave, the amplitude is multiplied by the Persistence");
public static GUIContent persistence = EditorGUIUtility.TrTextContent("Persistence", "The scaling factor applied to the Noise Amplitude at each Octave");
public static GUIContent frequency = EditorGUIUtility.TrTextContent("Frequency", "The unmodified frequency of Noise at each Octave. At each Octave, the Frequency is multiplied by the Lacunarity");
public static GUIContent lacunarity = EditorGUIUtility.TrTextContent("Lacunarity", "The scaling factor applied to the Noise Frequency at each Octave");
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 81f6535dc927652408d8221ab2ce0912
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,19 @@
#if UNITY_EDITOR
using UnityEngine;
namespace Gaia
{
internal class NoiseBlitShaderGenerator : NoiseShaderGenerator<NoiseBlitShaderGenerator>
{
private static ShaderGeneratorDescriptor m_desc = new ShaderGeneratorDescriptor()
{
name = "NoiseBlit",
shaderCategory = "Hidden/TerrainTools/Noise/NoiseBlit",
outputDir = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/Generated/",
templatePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Templates/Blit.noisehlsltemplate"
};
public override ShaderGeneratorDescriptor GetDescription() => m_desc;
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4ddfad2275f093643a4de5e2e367eccd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
#if UNITY_EDITOR
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Experimental.TerrainAPI;
#endif
namespace Gaia
{
public class NoiseComponent : MonoBehaviour
{
public Material mat;
public NoiseSettings noiseSettings;
void Update()
{
if(mat != null)
{
noiseSettings.SetupMaterial( mat );
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0e305e4583200c847b3bec406577f4bf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,14 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEngine.Experimental.TerrainAPI;
namespace Gaia
{
[CustomEditor(typeof(NoiseComponent))]
public class NoiseComponentEditor : Editor
{
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3781dadae292d7243895b1b2821ef903
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,281 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
namespace Gaia
{
[System.Serializable]
public enum CoordinateSpace
{
World = 0,
Brush,
}
[System.Serializable]
public struct NoiseToolSettings
{
public Vector2 worldHeightRemap;
public CoordinateSpace coordSpace;
// TODO(wyatt): what happens if they don't have an active noise settings asset?
public string noiseAssetGUID;
public void Reset()
{
worldHeightRemap = new Vector2(0, 1);
coordSpace = CoordinateSpace.World;
noiseAssetGUID = null;
}
}
/// <summary>
/// A data class that can be used to define various types of noise.
/// </summary>
[System.Serializable]
public class NoiseSettings : ScriptableObject
{
/// <summary>
/// Struct containing information about the transform (translation, rotation, scale) to be
/// applied to the noise. Usage of these values is depending on the actual noise
/// implementation.
/// </summary>
[System.Serializable]
public struct NoiseTransformSettings
{
/// <summary>
/// The translation used when generating the noise field
/// </summary>
[Tooltip("The translational offset to use when generating the noise")]
public Vector3 translation;
/// <summary>
/// The scale used when generating the noise field
/// </summary>
[Tooltip("The scale of the generated noise")]
public Vector3 scale;
/// <summary>
/// The rotation used when generating the noise field
/// </summary>
[Tooltip("The rotation of the generated noise")]
public Vector3 rotation;
/// <summary>
/// Determines whether the scale should be flipped across the x-axis
/// </summary>
[Tooltip("Whether or not the 2D noise field should be flipped along the X-axis")]
public bool flipScaleX;
/// <summary>
/// Determines whether the scale should be flipped across the y-axis
/// </summary>
[Tooltip("Whether or not the 2D noise field should be flipped along the Y-axis")]
public bool flipScaleY;
/// <summary>
/// Determines whether the scale should be flipped across the z-axis
/// </summary>
[Tooltip("Whether or not the 2D noise field should be flipped along the Z-axis")]
public bool flipScaleZ;
/// <summary>
/// Resets the members of the transform struct to their default states and values
/// </summary>
public void Reset()
{
translation = Vector3.zero;
scale = Vector3.one * 5f;
rotation = Vector3.zero;
flipScaleX = false;
flipScaleY = false;
flipScaleZ = false;
}
}
/// <summary>
/// Struct containing strings that reference the noise type and fractal type in use
/// as well as the serialized data associated with the noise and fractal type.
/// </summary>
[System.Serializable]
public struct NoiseDomainSettings
{
/// <summary>
/// String representing the name of the NoiseType that is in use
/// </summary>
[Tooltip("The type of noise being generated")]
public string noiseTypeName;
/// <summary>
/// String representing the name of the FractalType that is in use
/// </summary>
[Tooltip("The type of fractal used with the generated noise")]
public string fractalTypeName;
/// <summary>
/// String containing serialized data for the active NoiseType
/// </summary>
[Tooltip("Settings specific to noise type")]
public string noiseTypeParams;
/// <summary>
/// String containing serialized data for the active FractalType
/// </summary>
[Tooltip("Settings specific to noise type")]
public string fractalTypeParams;
/// <summary>
/// Resets the domain settings to the defaults for the built-in Perlin NoiseType and Fbm FractalType
/// </summary>
public void Reset()
{
#if UNITY_EDITOR
noiseTypeName = Gaia.PerlinNoise.instance.GetDescription().name;
fractalTypeName = Gaia.FbmFractalType.instance.GetDescription().name;
noiseTypeParams = Gaia.PerlinNoise.instance.GetDefaultSerializedString();
fractalTypeParams = Gaia.FbmFractalType.instance.GetDefaultSerializedString();
#endif
}
}
// put filter stack in separate class just for the isExpanded functionality
// of SerializedProperties
// [System.Serializable]
// public struct FilterSettings
// {
// [SerializeField]
// public FilterStack filterStack;
// }
/// <summary>
/// The transform settings for the defined noise field
/// </summary>
[Tooltip("Settings for noise transform and coordinate space")]
public NoiseTransformSettings transformSettings;
/// <summary>
/// The domain settings for the defined noise field. Contains serialized data
/// defining the NoiseType and FractalType for this NoiseSettings instance.
/// </summary>
[Tooltip("Settings for noise domain")]
public NoiseDomainSettings domainSettings;
// /// <summary>
// /// MISSING
// /// </summary>
// public FilterSettings filterSettings;
/// <summary>
/// The noise field's TRS transformation Matrix
/// </summary>
/// <returns> A Matrix4x4 for the noise field's TRS matrix </returns>
public Matrix4x4 trs
{
get
{
// set noise transform values
Vector3 scale = transformSettings.scale;
scale.x = transformSettings.flipScaleX ? -scale.x : scale.x;
scale.y = transformSettings.flipScaleY ? -scale.y : scale.y;
scale.z = transformSettings.flipScaleZ ? -scale.z : scale.z;
// scale.w = transformSettings.flipScaleW ? -scale.w : scale.w;
Matrix4x4 trs = Matrix4x4.TRS(transformSettings.translation,
Quaternion.Euler(transformSettings.rotation),
scale);
return trs;
}
}
/// <summary>
/// Copies the runtime information from a provided NoiseSettings instance.
/// </summary>
/// <param name="noiseSettings"> The NoiseSettings instance to copy from </param>
public void Copy(NoiseSettings noiseSettings)
{
transformSettings = noiseSettings.transformSettings;
domainSettings = noiseSettings.domainSettings;
// // TODO(wyatt): copy Filter Stack
// Debug.LogError("TODO(wyatt): copy filter stack");
}
/// <summary>
/// Copies the serialized information from a provided NoiseSettings instance
/// </summary>
/// <param name="noiseSettings"> The NoiseSettings instance to copy from </param>
public void CopySerialized(NoiseSettings noiseSettings)
{
SerializedObject copy = new SerializedObject(noiseSettings);
SerializedObject _this = new SerializedObject(this);
copy.Update();
_this.Update();
_this.CopyFromSerializedProperty(copy.FindProperty("transformSettings"));
_this.CopyFromSerializedProperty(copy.FindProperty("domainSettings"));
// _this.CopyFromSerializedProperty(copy.FindProperty("m_filterSettings"));
_this.ApplyModifiedProperties();
}
/// <summary>
/// Resets this NoiseSettings instance to have the default settings
/// </summary>
public void Reset()
{
transformSettings.Reset();
domainSettings.Reset();
}
/// <summary>
/// Sets up the provided Material to be used with this NoiseSettings instance. Some assumptions are made
/// here as far as definitions and variable declarations in the Material's Shader go.
/// float4 _NoiseTranslation, float4 _NoiseRotation, float4 _NoiseScale, and float4x4 _NoiseTransform are
/// assumed to be declared. Sets up the Material using the NoiseType and FractalType SetupMaterial
/// functions.
/// </summary>
/// <param name="mat"> The Material to set up for use with this NoiseSettings instance </param>
public void SetupMaterial(Material mat)
{
INoiseType noiseType = NoiseLib.GetNoiseTypeInstance(domainSettings.noiseTypeName);
IFractalType fractalType = NoiseLib.GetFractalTypeInstance(domainSettings.fractalTypeName);
// set individual transform info
mat.SetVector(ShaderStrings.translation, transformSettings.translation);
mat.SetVector(ShaderStrings.rotation, transformSettings.rotation);
mat.SetVector(ShaderStrings.scale, transformSettings.scale);
// set full transform matrix
mat.SetMatrix(ShaderStrings.transform, trs);
noiseType?.SetupMaterial(mat, domainSettings.noiseTypeParams);
fractalType?.SetupMaterial(mat, domainSettings.fractalTypeParams);
}
/// <summary>
/// Class containing the string names of shader properties used by noise shaders
/// </summary>
public static class ShaderStrings
{
/// <summary>
/// Property for noise translation. Value = "_NoiseTranslation"
/// </summary>
public static readonly string translation = "_NoiseTranslation";
/// <summary>
/// Property for noise scale. Value = "_NoiseScale"
/// </summary>
public static readonly string scale = "_NoiseScale";
/// <summary>
/// Property for noise rotation. Value = "_NoiseRotation"
/// </summary>
public static readonly string rotation = "_NoiseRotation";
/// <summary>
/// Property for the noise transform. Value = "_NoiseTransform"
/// </summary>
public static readonly string transform = "_NoiseTransform";
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cba17d399ab86974c8ef9551f6e8f8d4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace Gaia
{
[CustomEditor(typeof(NoiseSettings))]
public class NoiseSettingsEditor : Editor
{
NoiseSettingsGUI gui = new NoiseSettingsGUI();
void OnEnable()
{
gui.Init(serializedObject);
}
public override void OnInspectorGUI()
{
gui.OnGUI();
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 514f64f824c0e304f989db49f7cdb1d1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,50 @@
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace Gaia
{
/// <summary>
/// Class for creating NoiseSettings Assets. If you do not need to save the NoiseSettings
/// to disk, consider using ScriptableObject.CreateInstance< NoiseSettings >() instead.
/// </summary>
public class NoiseSettingsFactory
{
/// <summary>
/// Creates a new NoiseSettings Asset in the root Assets folder. This is the function
/// accessible via the "Assets/Create/Noise Settings" MenuItem
/// </summary>
/// <returns> A reference to the newly created NoiseSettings Asset </returns>d
//[MenuItem("Assets/Create/Noise Settings")]
//public static NoiseSettings CreateAsset()
//{
// return CreateAsset("Assets/New Noise Settings.asset");
//}
/// <summary>
/// Creates a new NoiseSettings Asset at the specified Asset path
/// </summary>
/// <param name="assetPath"> The path in the AssetDatabase where the new NoiseSettings Asset should be saved </param>
/// <returns> A reference to the newly created NoiseSettings Asset </returns>
public static NoiseSettings CreateAsset(string assetPath)
{
NoiseSettings noiseSettings = ScriptableObject.CreateInstance<NoiseSettings>();
// FilterStack filterStack = ScriptableObject.CreateInstance<FilterStack>();
// filterStack.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy | HideFlags.NotEditable;
// noiseSettings.filterSettings.filterStack = filterStack;
AssetDatabase.CreateAsset(noiseSettings, assetPath);
// AssetDatabase.AddObjectToAsset(filterStack, noiseSettings);
// AssetDatabase.ImportAsset( AssetDatabase.GetAssetPath( filterStack ) );
AssetDatabase.SaveAssets();
EditorGUIUtility.PingObject(noiseSettings);
return noiseSettings;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 69c9b63a89e2fee40850ab403a4603bc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,388 @@
#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Gaia
{
/// <summary>
/// Flags passed to NoiseSettingsGUI.OnGUI. Used to specify which portions of the Noise Settings GUI to draw.
/// </summary>
public enum NoiseSettingsGUIFlags
{
Preview = (1 << 0),
Settings = (1 << 1),
All = ( ~0 ),
}
/// <summary>
/// Class used to draw the GUI for Noise Settings.
/// </summary>
public class NoiseSettingsGUI
{
/// <summary>
/// The SerializedObject for the NoiseSettings that this NoiseSettingsGUI instance is currently rendering the GUI for.
/// </summary>
public SerializedObject serializedNoise;
// noise settings properties
// noise settings properties
// noise settings properties
// coord space settings properties
private SerializedProperty transformSettings;
public SerializedProperty translation;
public SerializedProperty rotation;
public SerializedProperty scale;
public SerializedProperty flipScaleX;
public SerializedProperty flipScaleY;
public SerializedProperty flipScaleZ;
// domain settings properties
public SerializedProperty domainSettings;
public SerializedProperty noiseTypeName;
public SerializedProperty noiseTypeParams;
public SerializedProperty fractalTypeName;
public SerializedProperty fractalTypeParams;
// filter stack settings
// private SerializedProperty filterSettings;
// private FilterStackView m_filterStackView;
// private FilterStack m_filterStack;
// private SerializedObject m_serializedFilterStack;
// private bool m_showFilterStack;
private RenderTexture m_previewRT;
private bool m_noisePreviewIsLocked = false;
/// <summary>
/// The current NoiseSettings object that is associated with this instance of NoiseSettingsGUI.
/// </summary>
public NoiseSettings target = null;
public Rect rect;
public Spawner m_spawner;
/// <summary>
/// Sets up this instance of NoiseSettingsGUI with the specified NoiseSettings object.
/// GUI will be drawn for this NoiseSettings instance.
/// </summary>
/// <param name="noiseSettings"> The NoiseSettings instance for which GUI will be drawn </param>
public void Init(NoiseSettings noiseSettings)
{
Init(new SerializedObject(noiseSettings));
}
/// <summary>
/// Sets up this instance of NoiseSettingsGUI with the specified SerializedObject containing an object reference
/// to a NoiseSettings instance. GUI will be drawn for this serialized NoiseSettings instance.
/// </summary>
/// <param name="serializedNoise"> A SerializedObject instance containing an object reference to a NoiseSettings object </param>
public void Init(SerializedObject serializedNoise)
{
this.serializedNoise = serializedNoise;
target = this.serializedNoise.targetObject as NoiseSettings;
// transform settings
transformSettings = this.serializedNoise.FindProperty("transformSettings");
translation = transformSettings.FindPropertyRelative("translation");
rotation = transformSettings.FindPropertyRelative("rotation");
scale = transformSettings.FindPropertyRelative("scale");
flipScaleX = transformSettings.FindPropertyRelative("flipScaleX");
flipScaleY = transformSettings.FindPropertyRelative("flipScaleY");
flipScaleZ = transformSettings.FindPropertyRelative("flipScaleZ");
// domain settings
domainSettings = this.serializedNoise.FindProperty("domainSettings");
noiseTypeName = domainSettings.FindPropertyRelative("noiseTypeName");
noiseTypeParams = domainSettings.FindPropertyRelative("noiseTypeParams");
fractalTypeName = domainSettings.FindPropertyRelative("fractalTypeName");
fractalTypeParams = domainSettings.FindPropertyRelative("fractalTypeParams");
// filter settings
// filterSettings = serializedNoise.FindProperty( "filterSettings" );
// m_filterStack = filterSettings.FindPropertyRelative( "filterStack" ).objectReferenceValue as FilterStack;
// m_serializedFilterStack = new SerializedObject( m_filterStack );
// m_filterStackView = new FilterStackView( new GUIContent( "Filters" ), m_serializedFilterStack, m_serializedFilterStack.targetObject as FilterStack );
}
/// <summary>
/// Renders the GUI for the NoiseSettings instance associated with this NoiseSettingsGUI instance.
/// </summary>
/// <param name="flags"> Flags specifying which portions of the GUI to draw </param>
public void OnGUI(NoiseSettingsGUIFlags flags = NoiseSettingsGUIFlags.All)
{
serializedNoise.Update();
if((flags & NoiseSettingsGUIFlags.Preview) != 0)
{
DrawPreviewTexture(256f,ref m_noisePreviewIsLocked);
}
if((flags & NoiseSettingsGUIFlags.Settings) != 0)
{
TerrainToolGUIHelper.DrawFoldout(transformSettings, Styles.transformSettings, TransformSettingsGUI);
TerrainToolGUIHelper.DrawFoldout(domainSettings, Styles.domainSettings, DomainSettingsGUI);
// TerrainToolGUIHelper.DrawFoldout(filterSettings, Styles.filterSettings, FilterSettingsGUI);
}
serializedNoise.ApplyModifiedProperties();
}
private void TransformSettingsGUI()
{
EditorGUILayout.PropertyField(translation);
EditorGUILayout.PropertyField(rotation);
EditorGUILayout.PropertyField(scale);
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel(Styles.flipScale);
flipScaleX.boolValue = TerrainToolGUIHelper.ToggleButton(Styles.flipScaleX, flipScaleX.boolValue);
flipScaleY.boolValue = TerrainToolGUIHelper.ToggleButton(Styles.flipScaleY, flipScaleY.boolValue);
flipScaleZ.boolValue = TerrainToolGUIHelper.ToggleButton(Styles.flipScaleZ, flipScaleZ.boolValue);
}
EditorGUILayout.EndHorizontal();
}
private void DomainSettingsGUI()
{
noiseTypeName.stringValue = NoiseLib.NoiseTypePopup(Styles.noiseType, noiseTypeName.stringValue);
INoiseType noiseType = NoiseLib.GetNoiseTypeInstance(noiseTypeName.stringValue);
noiseTypeParams.stringValue = noiseType?.DoGUI(noiseTypeParams.stringValue);
fractalTypeName.stringValue = NoiseLib.FractalTypePopup(Styles.fractalType, fractalTypeName.stringValue);
IFractalType fractalType = NoiseLib.GetFractalTypeInstance(fractalTypeName.stringValue);
fractalTypeParams.stringValue = fractalType?.DoGUI(fractalTypeParams.stringValue);
}
private void DoMinMaxSliderInt(GUIContent label, SerializedProperty prop, SerializedProperty minMaxProp)
{
int min = minMaxProp.vector2IntValue.x;
int max = minMaxProp.vector2IntValue.y;
prop.intValue = TerrainToolGUIHelper.MinMaxSliderInt(label, prop.intValue, ref min, ref max);
minMaxProp.vector2IntValue = new Vector2Int(min, max);
}
private void DoMinMaxSlider(GUIContent label, SerializedProperty prop, SerializedProperty minMaxProp)
{
float min = minMaxProp.vector2Value.x;
float max = minMaxProp.vector2Value.y;
prop.floatValue = TerrainToolGUIHelper.MinMaxSlider(label, prop.floatValue, ref min, ref max);
minMaxProp.vector2Value = new Vector2(min, max);
}
// private void FilterSettingsGUI()
// {
// m_filterStackView.OnGUI();
// }
private void HandlePreviewTextureInput(Rect previewRect)
{
if(GUIUtility.hotControl != 0)
{
return;
}
Vector3 t = translation.vector3Value;
Vector3 r = rotation.vector3Value;
Vector3 s = scale.vector3Value;
EventType eventType = Event.current.type;
bool draggingPreview = Event.current.button == 0 &&
(eventType == EventType.MouseDown ||
eventType == EventType.MouseDrag);
Vector2 previewDims = new Vector2(previewRect.width, previewRect.height);
Vector2 abs = new Vector2(Mathf.Abs(s.x), Mathf.Abs(s.z));
if (Event.current.type == EventType.ScrollWheel)
{
abs += Vector2.one * .001f;
float scroll = Event.current.delta.y;
s.x += abs.x * scroll * .05f;
s.z += abs.y * scroll * .05f;
scale.vector3Value = s;
Event.current.Use();
GUI.changed = true;
}
else if (draggingPreview)
{
// change noise offset panning icon
Vector2 sign = new Vector2(-Mathf.Sign(s.x), Mathf.Sign(s.z));
Vector2 delta = Event.current.delta / previewDims * abs * sign;
Vector3 d3 = new Vector3(delta.x, 0, delta.y);
d3 = Quaternion.Euler( r ) * d3;
t += d3;
translation.vector3Value = t;
Event.current.Use();
GUI.changed = true;
}
}
/// <summary>
/// Renders an interactive Noise Preview along with tooltip icons and an optional Export button that opens a new ExportNoiseWindow.
/// A background image is also rendered behind the preview that takes up the entire width of the EditorWindow currently being drawn.
/// </summary>
/// <param name = "minSize"> Minimum size for the Preview </param>
/// <param name = "showExportButton"> Whether or not to render the Export button </param>
public void DrawPreviewTexture(float minSize, ref bool isLocked)
{
// Draw label with tooltip
//GUILayout.Label( Styles.noisePreview );
float padding = 4f;
float iconWidth = 40f;
int size = (int)Mathf.Min(minSize, EditorGUIUtility.currentViewWidth);
Rect currentRect = rect;
currentRect.y += EditorGUIUtility.singleLineHeight *2f;
Rect totalRect = new Rect(currentRect.x, currentRect.y, currentRect.width, size); //GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth, size + padding * 2); // extra pixels for highlight border
Color prev = GUI.color;
GUI.color = new Color(.1f, .1f, .1f, 1f);
GUI.DrawTexture(totalRect, Texture2D.whiteTexture, ScaleMode.StretchToFill, false);
GUI.color = Color.white;
// draw info icon
// if(totalRect.Contains(Event.current.mousePosition))
{
Rect infoIconRect = new Rect( totalRect.x + padding, totalRect.y + padding, iconWidth, iconWidth );
GUI.Label( infoIconRect, Styles.infoIcon );
// GUI.Label( infoIconRect, Styles.noiseTooltip );
}
float buttonWidth = GUI.skin.button.CalcSize(Styles.buttonUnlocked).x;
float buttonHeight = EditorGUIUtility.singleLineHeight;
Rect lockButtonRect = new Rect(totalRect.x + padding, totalRect.y + padding * 2f + GUI.skin.button.CalcSize(Styles.infoIcon).y, buttonWidth, buttonHeight);
if (isLocked)
{
if (GUI.Button(lockButtonRect, Styles.buttonLocked))
{
isLocked = false;
}
}
else
{
if (GUI.Button(lockButtonRect, Styles.buttonUnlocked))
{
isLocked = true;
}
}
m_noisePreviewIsLocked = isLocked;
// draw export button
//Rect exportRect = new Rect( totalRect.xMax - buttonWidth - padding, totalRect.yMax - buttonHeight - padding, buttonWidth, buttonHeight );
//if(GUI.Button(exportRect, Styles.export))
//{
// serializedNoise.ApplyModifiedProperties();
// serializedNoise.Update();
// ExportNoiseWindow.ShowWindow( serializedNoise.targetObject as NoiseSettings );
//}
float safeSpace = Mathf.Max( iconWidth * 2, buttonWidth * 2 ) + padding * 4;
float minWidth = Mathf.Min( size, totalRect.width - safeSpace );
Rect previewRect = new Rect(totalRect.x + totalRect.width / 2 - minWidth / 2, totalRect.y + totalRect.height / 2 - minWidth / 2, minWidth, minWidth);
EditorGUIUtility.AddCursorRect(previewRect, MouseCursor.Pan);
if (previewRect.Contains(Event.current.mousePosition) && !isLocked)
{
serializedNoise.Update();
HandlePreviewTextureInput(previewRect);
serializedNoise.ApplyModifiedProperties();
}
if ( Event.current.type == EventType.Repaint )
{
// create preview RT here and keep until the next Repaint
if( m_previewRT != null )
{
RenderTexture.ReleaseTemporary( m_previewRT );
}
NoiseSettings noiseSettings = serializedNoise.targetObject as NoiseSettings;
m_previewRT = RenderTexture.GetTemporary(512, 512, 0, RenderTextureFormat.ARGB32);
RenderTexture tempRT = RenderTexture.GetTemporary(512, 512, 0, RenderTextureFormat.RFloat);
RenderTexture prevActive = RenderTexture.active;
NoiseUtils.Blit2D(noiseSettings, tempRT);
NoiseUtils.BlitPreview2D(tempRT, m_previewRT);
RenderTexture.active = prevActive;
GUI.DrawTexture(previewRect, m_previewRT, ScaleMode.ScaleToFit, false);
RenderTexture.ReleaseTemporary(tempRT);
}
GUI.color = prev;
}
static class Styles
{
public static GUIContent noiseSettings = EditorGUIUtility.TrTextContent("Noise Settings:");
public static GUIContent randomize = EditorGUIUtility.TrTextContent("Randomize");
public static GUIContent reset = EditorGUIUtility.TrTextContent("Reset");
public static GUIContent flipScale = EditorGUIUtility.TrTextContent("Flip Scale", "Flips the scale of the Noise Domain Space");
public static GUIContent flipScaleX = EditorGUIUtility.TrTextContent("X", "Flips the scale of the Noise Domain Space along the X-axis");
public static GUIContent flipScaleY = EditorGUIUtility.TrTextContent("Y", "Flips the scale of the Noise Domain Space along the Y-axis");
public static GUIContent flipScaleZ = EditorGUIUtility.TrTextContent("Z", "Flips the scale of the Noise Domain Space along the Z-axis");
public static GUIContent noiseType = EditorGUIUtility.TrTextContent("Noise Type", "The type of Noise to be used");
public static GUIContent fractalType = EditorGUIUtility.TrTextContent("Fractal Type", "The type of Fractal to be used when generating Noise");
public static GUIContent noisePreview;
public static GUIContent noiseTooltip = EditorGUIUtility.TrTextContent("",
"Scroll Mouse Wheel:\nZooms the preview in and out and changes the noise scale\n\n" +
"Left-mouse Drag:\nPans the noise field and changes the noise translation\n\n" +
"Color Key:\nCyan = negative noise values\nGrayscale = values between 0 and 1\nBlack = values are 0\nRed = Values greater than 1. Used for debugging texture normalization");
public static GUIContent seed = EditorGUIUtility.TrTextContent("Seed");
public static GUIContent domainSettings = EditorGUIUtility.TrTextContent("Domain Settings", "Settings governing the Noise Domain. This is specific to each Noise Type and Fractal Type implementation");
public static GUIContent transformSettings = EditorGUIUtility.TrTextContent("Transform Settings", "Settings governing the transformations applied to positions in the Noise Domain Space");
// public static GUIContent filterSettings = EditorGUIUtility.TrTextContent("Filter Settings");
public static GUIContent ridgePower = EditorGUIUtility.TrTextContent("Ridge Power");
public static GUIContent billowPower = EditorGUIUtility.TrTextContent("Billow Power");
public static GUIContent voronoiPower = EditorGUIUtility.TrTextContent("Voronoi Power");
public static GUIContent power = EditorGUIUtility.TrTextContent("Power");
public static GUIContent export = EditorGUIUtility.TrTextContent("Export", "Open a window providing options for exporting Noise to Textures");
public static GUIContent buttonLocked = EditorGUIUtility.TrTextContent("Locked", "The preview texture is currently locked for changes from mouse input. Click here to unlock it.");
public static GUIContent buttonUnlocked = EditorGUIUtility.TrTextContent("Unlocked", "The preview texture is currently active for changes from mouse input. Click here to lock it.");
public static GUIContent infoIcon = new GUIContent("", EditorGUIUtility.FindTexture("console.infoicon"),
"Scroll Mouse Wheel:\nZooms the preview in and out and changes the noise scale\n\n" +
"Left-mouse Drag:\nPans the noise field and changes the noise translation\n\n" +
"Color Key:\nCyan = negative noise values\nGrayscale = values between 0 and 1\nBlack = values are 0\nRed = Values greater than 1. Used for debugging texture normalization");
static Styles()
{
noisePreview = EditorGUIUtility.TrTextContent("Noise Field Preview:");
// ,
// "Scroll Mouse Wheel:\nZooms the preview in and out and changes the noise scale\n\n" +
// "Left-mouse Drag:\nPans the noise field and changes the noise translation\n\n" +
// "Color Key:\nCyan = negative noise values\nGrayscale = values between 0 and 1\nBlack = values are 0\nRed = Values greater than 1. Used for debugging texture normalization");
// noisePreview.image = infoIcon.image;
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 796f173f949995143a606f936f780207
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,25 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace Gaia
{
/// <summary>
/// A FractalType implementation for a fractal that does nothing. This will give you raw
/// noise values from the "first" fractal (from Fractal Brownian Motion, for instance) when used
/// </summary>
public class NoneFractalType : FractalType<NoneFractalType>
{
public override FractalTypeDescriptor GetDescription() => new FractalTypeDescriptor()
{
name = "None",
templatePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Templates/FractalNone.noisehlsltemplate",
supportedDimensions = NoiseDimensionFlags._1D | NoiseDimensionFlags._2D | NoiseDimensionFlags._3D,
inputStructDefinition = null,
additionalIncludePaths = new List<string>()
{
"Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/NoiseCommon.hlsl"
}
};
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 243f204cf33f56049a1b14f47aea8a8b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace Gaia
{
/// <summary>
/// A NoiseType implementation for Perlin noise
/// </summary>
[System.Serializable]
public class PerlinNoise : NoiseType<PerlinNoise>
{
private static NoiseTypeDescriptor desc = new NoiseTypeDescriptor()
{
name = "Perlin",
outputDir = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/",
sourcePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Implementation/PerlinImpl.hlsl",
supportedDimensions = NoiseDimensionFlags._1D | NoiseDimensionFlags._2D | NoiseDimensionFlags._3D,
inputStructDefinition = null
};
public override NoiseTypeDescriptor GetDescription() => desc;
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e0924f504ee0ba942b477a664503566c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace Gaia
{
/// <summary>
/// A NoiseType implementation for Ridge noise
/// </summary>
[System.Serializable]
public class RidgeNoise : NoiseType<RidgeNoise>
{
private static NoiseTypeDescriptor desc = new NoiseTypeDescriptor()
{
name = "Ridge",
outputDir = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/",
sourcePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Implementation/RidgeImpl.hlsl",
supportedDimensions = NoiseDimensionFlags._1D | NoiseDimensionFlags._2D | NoiseDimensionFlags._3D,
inputStructDefinition = null
};
public override NoiseTypeDescriptor GetDescription() => desc;
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2882602abd190e04494ee22551e5380c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace Gaia
{
/// <summary>
/// A NoiseType implementation for Value noise
/// </summary>
[System.Serializable]
public class ValueNoise : NoiseType<ValueNoise>
{
private static NoiseTypeDescriptor desc = new NoiseTypeDescriptor()
{
name = "Value",
outputDir = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/",
sourcePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Implementation/ValueImpl.hlsl",
supportedDimensions = NoiseDimensionFlags._1D | NoiseDimensionFlags._2D | NoiseDimensionFlags._3D,
inputStructDefinition = null
};
public override NoiseTypeDescriptor GetDescription() => desc;
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c79180b40a2ad9c4482d905314cfa548
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
#if UNITY_EDITOR
using System.Collections.Generic;
namespace Gaia
{
/// <summary>
/// A NoiseType implementation for Voronoi noise
/// </summary>
[System.Serializable]
public class VoronoiNoise : NoiseType<VoronoiNoise>
{
private static NoiseTypeDescriptor desc = new NoiseTypeDescriptor()
{
name = "Voronoi",
outputDir = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/",
sourcePath = "Assets/Procedural Worlds/Gaia/Shaders/Unity/Terrain Tools/NoiseLib/Implementation/VoronoiImpl.hlsl",
supportedDimensions = NoiseDimensionFlags._1D | NoiseDimensionFlags._2D | NoiseDimensionFlags._3D,
inputStructDefinition = null
};
public override NoiseTypeDescriptor GetDescription() => desc;
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0d452b763a280754ebf8d3c37faf24ad
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
The contents of these folders and their subfolders are derived from the Unity Terrain Tools Package under the following License:
Unity Companion License - https://unity3d.com/legal/licenses/Unity_Companion_License
Here is a full "offline" copy of this license in case the link above is not accessible:
Unity Companion License ("License")
v1.2
Unity Technologies ApS (“Unity”) grants to you a worldwide, non-exclusive, no-charge, and royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute the software that accompanies this License (“Software”), subject to the following terms and conditions:
1. Unity Companion Use Only. Exercise of the license granted herein is limited to exercise for the creation, use, and/or distribution of applications, software, or other content pursuant to a valid Unity content authoring and rendering engine software license (“Engine License”). That means while not limited to exercise in the software licensed under the Engine License, exercise may not be for any purpose other than the creation, use, and/or distribution of Engine License-dependent applications, software, or other content. No other exercise of the license granted herein is permitted, and in no event may the Software be used for competitive analysis or to develop a competing product or service.
2. No Modification of Engine License. Neither this License nor any exercise of the license granted herein modifies the Engine License in any way.
3. Ownership; Derivative Works.
3.1 You own your content. In this License, “derivative works” means derivatives of the Software itself--works derived only from the Software by you under this License (for example, modifying the code of the Software itself to improve its efficacy); “derivative works” of the Software do not include, for example, games, apps, or content that you create with the Software. You keep all right, title, and interest to your own content.
3.2 Unity owns its content. While you keep all right, title, and interest to your own content per the above, as between Unity and you, Unity will own all right, title, and interest to all intellectual property rights (including patent, trademark, and copyright) in the Software and derivative works of the Software, and you hereby assign and agree to assign all such rights in those derivative works to Unity. Should assignment be invalid for any reason, you grant to Unity an irrevocable, perpetual, worldwide, non-exclusive, no-charge, and royalty-free license (with the right to grant sublicenses) under those intellectual property rights to those derivative works. You also agree to waive or refrain from asserting any author’s right, moral rights, or like rights to the extent necessary to permit exploitation as contemplated under this License.
3.3 Your right to use derivative works. You will always have the right to use derivative works of the Software you create, consonant with this License.
4. Trademarks. You are not granted any right or license under this License to use any trademarks, service marks, trade names, products names, or branding of Unity or its affiliates (“Trademarks”). Descriptive uses of Trademarks are permitted; see, for example, Unity’s Branding Usage Guidelines at https://unity3d.com/public-relations/brand.
5. Notices & Third-Party Rights. This License, including the copyright notice associated with the Software, must be provided in all substantial portions of the Software and derivative works thereof (or, if that is impracticable, in any other location where such notices are customarily placed). Further, if the Software is accompanied by a Unity “third-party notices” or similar file, you acknowledge and agree that software identified in that file is governed by those separate license terms.
6. DISCLAIMER, LIMITATION OF LIABILITY. THE SOFTWARE AND ANY DERIVATIVE WORKS THEREOF IS PROVIDED ON AN "AS IS" BASIS, AND IS PROVIDED WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR NONINFRINGEMENT. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES (WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL, INCLUDING PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, AND BUSINESS INTERRUPTION), OR OTHER LIABILITY WHATSOEVER, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM OR OUT OF, OR IN CONNECTION WITH, THE SOFTWARE OR ANY DERIVATIVE WORKS THEREOF OR THE USE OF OR OTHER DEALINGS IN SAME, EVEN WHERE ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7. USE IS ACCEPTANCE and License Versions. Your access to and use of the Software constitutes your acceptance of this License and its terms and conditions. This License may be modified or updated; upon any such modification or update, you will comply with the terms of the updated License for any use of any of the Software under the updated License.
8. Use in Compliance with Law and Termination. Your exercise of the license granted herein will at all times be in compliance with applicable law and will not infringe any proprietary rights (including intellectual property rights); this License will terminate immediately (i) on any breach by you of this License; and (ii) if you commence any form of patent litigation, including a cross-claim or counterclaim, against anyone wherein you allege that the Software constitutes direct or secondary/indirect patent infringement.
9. Severability. If any provision of this License is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the other provisions will remain in full force and effect.
10. Governing Law and Venue. This License is governed by and construed in accordance with the laws of Denmark, except for its conflict of laws rules; the United Nations Convention on Contracts for the International Sale of Goods will not apply. If you reside (or your principal place of business is) within the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the state and federal courts located in San Francisco County, California concerning any dispute arising out of this License (“Dispute”). If you reside (or your principal place of business is) outside the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the courts located in Copenhagen, Denmark concerning any Dispute.
(03.2018)
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 0154f7d01f9921947abe1375ff8eb033
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: