新增unity的牛逼shader和熊猫超级shader

This commit is contained in:
Abin committed 2026-03-10 18:34:45 +08:00
1 parent 6001f6d87a
commit 1a4cd29e7c
216 files changed
+41947

No files matched your search

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fd758a702a9040fcb8614b232817cff9
timeCreated: 1721290722
@@ -0,0 +1,103 @@
using UnityEditor;
using UnityEngine;
using System;
namespace NBShaderEditor
{
public class BinaryIntAttribute : PropertyAttribute
{
public int binaryBits;
public bool showInputFiled;
public int tabNums;
public BinaryIntAttribute(int Bits = 32, bool showInput = false, int tab = 0)
{
binaryBits = Bits;
showInputFiled = showInput;
tabNums = tab;
}
}
[CustomPropertyDrawer(typeof(BinaryIntAttribute))]
public class BinaryIntDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
GUIStyle richTextStyle = EditorStyles.label;
richTextStyle.richText = true;
BinaryIntAttribute binaryIntAttribute = (BinaryIntAttribute)attribute;
// int value = property.intValue;
// int largestBit = 0;
// for (int i = 0; i < 32; i++)
// {
// if ((~value & (1 << i)) == 0)
// {
// largestBit = i;
// }
// }
//
// int addZeroCount = 0;
// if (largestBit < binaryIntAttribute.binaryBits)
// {
// addZeroCount = binaryIntAttribute.binaryBits - largestBit - 1;
// }
//
// string addZeroString = "";
// for (int i = 0; i < addZeroCount; i++)
// {
// addZeroString += "0";
// }
// string binary = addZeroString+Convert.ToString(property.intValue, 2);
string binary = DrawBinaryInt(property.intValue, binaryIntAttribute.binaryBits);
string tabs = "";
for (int i = 0; i < binaryIntAttribute.tabNums; i++)
{
tabs += "\t";
}
if (binaryIntAttribute.showInputFiled)
{
string labelText = property.displayName + tabs + "<mspace=1em>" + binary + "</mspace>";
Rect intRect = EditorGUI.PrefixLabel(position, new GUIContent(labelText), richTextStyle);
property.intValue = EditorGUI.IntField(intRect, property.intValue);
}
else
{
EditorGUILayout.LabelField(property.displayName + tabs);
EditorGUILayout.LabelField(binary);
}
}
public static string DrawBinaryInt(int value, int binaryBits)
{
int largestBit = 0;
for (int i = 0; i < 32; i++)
{
if ((~value & (1 << i)) == 0)
{
largestBit = i;
}
}
int addZeroCount = 0;
if (largestBit < binaryBits)
{
addZeroCount = binaryBits - largestBit - 1;
}
string addZeroString = "";
for (int i = 0; i < addZeroCount; i++)
{
addZeroString += "0";
}
string binary = addZeroString + Convert.ToString(value, 2);
return binary;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4517deaf5f31a5848b6a58304d1f516f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,253 @@
using System;
using System.Reflection;
using UnityEngine;
namespace NBShaderEditor
{
//因为GradientPicker窗口,在窗口打开时使用的是Gradient对象的Cache。
//如果有Undo操作,导致MaterialProperty更新了,但Gradient却更新不到ColorPicer里。所以在这里进行强制更新。
//后续需要强制更新Picker的时候,也可以用这里。
//DeepSeek写的。谨慎用。
public static class GradientReflectionHelper
{
#region GradientPicker 相关
private static Type _gradientPickerType;
// SetCurrentGradient 方法
private static MethodInfo _setGradientMethod;
private static Action<Gradient> _setGradientDelegate;
// RefreshGradientData 方法
private static MethodInfo _refreshMethod;
private static Action _refreshDelegate;
#endregion
#region GradientPreviewCache 相关
private static Type _gradientCacheType;
private static MethodInfo _clearCacheMethod;
private static Action _clearCacheDelegate;
#endregion
// 初始化状态
private static bool _initialized;
private static bool _isValid;
private static readonly object _initLock = new object();
#region 公共API
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void SetCurrentGradient(Gradient gradient)
{
ExecuteAction(() =>
{
if (_setGradientDelegate != null)
_setGradientDelegate(gradient);
else if (_setGradientMethod != null)
_setGradientMethod.Invoke(null, new object[] { gradient });
}, "SetCurrentGradient");
}
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void RefreshGradientData()
{
ExecuteAction(() =>
{
if (_refreshDelegate != null)
_refreshDelegate();
else if (_refreshMethod != null)
_refreshMethod.Invoke(null, null);
}, "RefreshGradientData");
}
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void ClearGradientCache()
{
ExecuteAction(() =>
{
if (_clearCacheDelegate != null)
_clearCacheDelegate();
else if (_clearCacheMethod != null)
_clearCacheMethod.Invoke(null, null);
}, "ClearGradientCache");
}
#endregion
#region 核心实现
private static void ExecuteAction(Action action, string methodName)
{
if (!Application.isEditor) return;
EnsureInitialized();
if (!_isValid) return;
try
{
action?.Invoke();
}
catch (Exception ex)
{
Debug.LogError($"[GradientReflection] {methodName} failed: {ex.Message}");
// 可选择性地禁用后续调用
// _isValid = false;
}
}
private static void EnsureInitialized()
{
if (_initialized) return;
lock (_initLock)
{
if (_initialized) return;
try
{
// 1. 初始化 GradientPicker 类型
_gradientPickerType = Type.GetType("UnityEditor.GradientPicker, UnityEditor");
if (_gradientPickerType != null)
{
// 初始化 SetCurrentGradient
_setGradientMethod = GetStaticMethod(
_gradientPickerType,
"SetCurrentGradient",
new[] { typeof(Gradient) }
);
if (_setGradientMethod != null)
{
_setGradientDelegate = CreateActionDelegate<Gradient>(_setGradientMethod);
}
// 初始化 RefreshGradientData
_refreshMethod = GetStaticMethod(
_gradientPickerType,
"RefreshGradientData",
Type.EmptyTypes
);
if (_refreshMethod != null)
{
_refreshDelegate = CreateActionDelegate(_refreshMethod);
}
}
else
{
Debug.LogWarning("[GradientReflection] GradientPicker type not found");
}
// 2. 初始化 GradientPreviewCache
_gradientCacheType = Type.GetType("UnityEditorInternal.GradientPreviewCache, UnityEditor");
if (_gradientCacheType != null)
{
_clearCacheMethod = GetStaticMethod(
_gradientCacheType,
"ClearCache",
Type.EmptyTypes
);
if (_clearCacheMethod != null)
{
_clearCacheDelegate = CreateActionDelegate(_clearCacheMethod);
}
}
else
{
Debug.LogWarning("[GradientReflection] GradientPreviewCache type not found");
}
// 3. 验证初始化状态
_isValid = (_setGradientMethod != null || _refreshMethod != null) &&
_clearCacheMethod != null;
if (!_isValid)
{
Debug.LogWarning($"[GradientReflection] Initialization incomplete. " +
$"SetCurrentGradient: {(_setGradientMethod != null ? "OK" : "Missing")}, " +
$"RefreshGradientData: {(_refreshMethod != null ? "OK" : "Missing")}, " +
$"ClearCache: {(_clearCacheMethod != null ? "OK" : "Missing")}");
}
else
{
// Debug.Log("[GradientReflection] Initialized successfully");
}
}
catch (Exception e)
{
Debug.LogError($"[GradientReflection] Initialization failed: {e}");
_isValid = false;
}
finally
{
_initialized = true;
}
}
}
private static MethodInfo GetStaticMethod(Type type, string methodName, Type[] parameterTypes)
{
if (type == null) return null;
return type.GetMethod(
methodName,
BindingFlags.Public | BindingFlags.Static,
null,
parameterTypes,
null
);
}
private static Action CreateActionDelegate(MethodInfo method)
{
try
{
return (Action)Delegate.CreateDelegate(typeof(Action), method);
}
catch (Exception ex)
{
Debug.LogWarning($"[GradientReflection] Failed to create delegate for {method.Name}: {ex.Message}");
return null;
}
}
private static Action<T> CreateActionDelegate<T>(MethodInfo method)
{
try
{
return (Action<T>)Delegate.CreateDelegate(typeof(Action<T>), method);
}
catch (Exception ex)
{
Debug.LogWarning($"[GradientReflection] Failed to create delegate for {method.Name}: {ex.Message}");
return null;
}
}
#endregion
#region 辅助功能
/// <summary>
/// 检查是否所有反射方法都可用
/// </summary>
public static bool IsFullySupported => _isValid;
/// <summary>
/// 获取反射初始化状态
/// </summary>
public static string GetReflectionStatus()
{
if (!_initialized) return "Not Initialized";
return $"GradientPicker: {(_gradientPickerType != null ? "Found" : "Missing")}\n" +
$"- SetCurrentGradient: {(_setGradientMethod != null ? "OK" : "Missing")}\n" +
$"- RefreshGradientData: {(_refreshMethod != null ? "OK" : "Missing")}\n" +
$"GradientPreviewCache: {(_gradientCacheType != null ? "Found" : "Missing")}\n" +
$"- ClearCache: {(_clearCacheMethod != null ? "OK" : "Missing")}";
}
#endregion
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ebe6cf7ae30f4357bae940f8ce409628
timeCreated: 1753589587
@@ -0,0 +1,261 @@
using UnityEditor;
using UnityEngine;
using UnityEditor.Experimental.GraphView;
using System;
using NBShader;
namespace NBShaderEditor
{
// #if UNITY_EDITOR
[CustomEditor(typeof(MaterialPropertyAgent))]
public class MaterialPropertyAgentInspector : UnityEditor.Editor
{
private MaterialPropertyAgent agent;
private void OnEnable()
{
agent = (MaterialPropertyAgent)target;
}
private GUIContent materialIndexContent = new GUIContent("材质序号:", "只有模型模式下需要使用,谨慎修改");
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUI.BeginChangeCheck();
if (!agent.isGetByComponet)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("customRenderer"),
new GUIContent("指定Renderer"));
}
if (agent.isRendererMode)
{
EditorGUILayout.BeginHorizontal();
int lastIndex = agent.materialIndex;
agent.materialIndex = EditorGUILayout.IntField(materialIndexContent, agent.materialIndex);
if (lastIndex != agent.materialIndex)
{
agent.initMatAndShaderByMaterialIndexChange();
}
EditorGUILayout.LabelField("材质名:" + agent.mat.name + "\t" + "Shader名:" + agent.shader.name);
EditorGUILayout.EndHorizontal();
}
DrawPropertyData(ref agent.data0, "Data0", serializedObject.FindProperty("data0"));
DrawPropertyData(ref agent.data1, "Data1", serializedObject.FindProperty("data1"));
DrawPropertyData(ref agent.data2, "Data2", serializedObject.FindProperty("data2"));
DrawPropertyData(ref agent.data3, "Data3", serializedObject.FindProperty("data3"));
DrawPropertyData(ref agent.data4, "Data4", serializedObject.FindProperty("data4"));
DrawPropertyData(ref agent.data5, "Data5", serializedObject.FindProperty("data5"));
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("添加"))
{
agent.addProperteData();
}
if (GUILayout.Button("全部删除"))
{
agent.removeAllProperty();
}
EditorGUILayout.EndHorizontal();
serializedObject.ApplyModifiedProperties();
if (EditorGUI.EndChangeCheck())
{
PrefabUtility.RecordPrefabInstancePropertyModifications(agent);
if (!agent.isGetByComponet && agent.mat)
{
if (matEditor) DestroyImmediate(matEditor);
matEditor = (MaterialEditor)CreateEditor(agent.mat);
}
}
if (!agent.isGetByComponet && agent.mat)
{
DrawMaterialInspector(matEditor, agent.mat);
}
}
void DrawPropertyData(ref MaterialPropertyAgent.PropertyData data, string dataLabel,
SerializedProperty property)
{
EditorGUI.BeginProperty(EditorGUILayout.GetControlRect(false, 0f), GUIContent.none, property);
if (data.isActive)
{
EditorGUILayout.LabelField(dataLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
float originLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 80;
// data.index = EditorGUILayout.Popup("属性名:", data.index, agent.shaderPropNameArr);
// data.index = EditorGUILayout.Popup("属性名:", data.index, agent.shaderPropDescripArr);
// string dataDesript = data.descripName;
if (GUILayout.Button(data.descripName, EditorStyles.popup))
{
int dataIndexInAgent = data.dataIndexInAgent;
StringListSerchProvider provider = ScriptableObject.CreateInstance<StringListSerchProvider>();
provider.Initialize(agent.shaderPropDescripsForSerch, (x) =>
{
if (x != null)
{
AfterShaderPropSerch(dataIndexInAgent, x);
}
});
SearchWindow.Open(new SearchWindowContext(GUIUtility.GUIToScreenPoint(Event.current.mousePosition)),
provider);
// SearchWindow.Open(new SearchWindowContext(GUIUtility.GUIToScreenPoint(Event.current.mousePosition)),
// new StringListSerchProvider(agent.shaderPropDescripsForSerch, (x) =>
// {
// if (x != null)
// {
// AfterShaderPropSerch(dataIndexInAgent,x);
// }
// }));
}
EditorGUILayout.LabelField("属性类型:", data.type.ToString());
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = originLabelWidth;
switch (data.type)
{
case MaterialPropertyAgent.shaderPropertyType.Color:
SerializedProperty colorProp = property.FindPropertyRelative("colorValue");
if (data.descripName.ToLower().Contains("hdr"))
{
colorProp.colorValue = EditorGUILayout.ColorField(new GUIContent(data.propName + " :"),
colorProp.colorValue, true, true, true);
}
else
{
colorProp.colorValue =
EditorGUILayout.ColorField(data.propName + " :", colorProp.colorValue);
}
break;
case MaterialPropertyAgent.shaderPropertyType.Vector:
case MaterialPropertyAgent.shaderPropertyType.TexEnv:
SerializedProperty vecProp = property.FindPropertyRelative("vecValue");
if (data.type == MaterialPropertyAgent.shaderPropertyType.Vector)
{
vecProp.vector4Value =
EditorGUILayout.Vector4Field(data.propName + " :", vecProp.vector4Value);
}
else if (data.type == MaterialPropertyAgent.shaderPropertyType.TexEnv)
{
vecProp.vector4Value =
EditorGUILayout.Vector4Field(data.propName + ":", vecProp.vector4Value);
}
break;
case MaterialPropertyAgent.shaderPropertyType.Float:
case MaterialPropertyAgent.shaderPropertyType.Range:
SerializedProperty floatProp = property.FindPropertyRelative("floatValue");
if (data.type == MaterialPropertyAgent.shaderPropertyType.Float)
{
floatProp.floatValue =
EditorGUILayout.FloatField(data.propName + ":", floatProp.floatValue);
}
else if (data.type == MaterialPropertyAgent.shaderPropertyType.Range)
{
floatProp.floatValue = EditorGUILayout.Slider(data.propName + ":", floatProp.floatValue,
data.rangMin, data.rangMax);
}
break;
}
if (GUILayout.Button("删除", new[] { GUILayout.Width(200) }))
{
data.isActive = false;
}
EditorGUI.indentLevel--;
// EditorGUILayout.Space();
}
EditorGUI.EndProperty();
}
//因为Action不能有Ref。所以有了这个丑陋的HardCode
public void AfterShaderPropSerch(int dataIndexInAgent, string propertyDesrpt)
{
switch (dataIndexInAgent)
{
case 0:
AfterShaderPropSerch(ref agent.data0, propertyDesrpt);
break;
case 1:
AfterShaderPropSerch(ref agent.data1, propertyDesrpt);
break;
case 2:
AfterShaderPropSerch(ref agent.data2, propertyDesrpt);
break;
case 3:
AfterShaderPropSerch(ref agent.data3, propertyDesrpt);
break;
case 4:
AfterShaderPropSerch(ref agent.data4, propertyDesrpt);
break;
case 5:
AfterShaderPropSerch(ref agent.data5, propertyDesrpt);
break;
}
}
public void AfterShaderPropSerch(ref MaterialPropertyAgent.PropertyData data, string propertyDesrpt)
{
int preservedIndex = data.index;
// string propname = data.propName;
data.index = Array.FindIndex(agent.shaderPropDescripArr, x => x.Equals(propertyDesrpt));
// Debug.Log();
if (preservedIndex != data.index) //证明用户进行了更改
{
if (!agent.isCanUsedIndex(data.index))
{
//TODO给一个报错提示
Debug.LogError("材质属性已经存在:" + ShaderUtil.GetPropertyDescription(agent.shader, data.index));
data.index = agent.getCanUsedIndex();
}
//此处进行内容刷新
data.setValueByPropChange();
}
}
private MaterialEditor matEditor;
void DrawMaterialInspector(MaterialEditor editor, Material mat)
{
if (editor != null && mat != null)
{
// Draw the material's foldout and the material shader field
// Required to call _materialEditor.OnInspectorGUI ();
editor.DrawHeader();
// We need to prevent the user to edit Unity default materials
bool isDefaultMaterial = !AssetDatabase.GetAssetPath(mat).StartsWith("Assets");
using (new EditorGUI.DisabledGroupScope(isDefaultMaterial))
{
// Draw the material properties
// Works only if the foldout of _materialEditor.DrawHeader () is open
editor.OnInspectorGUI();
}
}
}
}
}
// #endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b9544bec10c84ecca289bece4a630d65
timeCreated: 1702126025
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9279ba81938dc1548b9e9d8297bdcd57
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 947243301cab4804d8df47a42b220c4e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,286 @@
using UnityEditor;
using UnityEngine;
namespace NBShaderEditor
{
public class ShaderGUIFloatItem:ShaderGUIItem
{
public ShaderGUIFloatItem(ShaderGUIRootItem rootItem, ShaderGUIItem parentItem) :
base(rootItem, parentItem: parentItem)
{
base.InitTriggerByChild();
}
public override void DrawController()
{
PropertyInfo.Property.floatValue = DraggableLabelFloat.Handle(LabelRect, PropertyInfo.Property.floatValue, sensitivity: -1f);//拖动Label控件可以操作Float参数
PropertyInfo.Property.floatValue = EditorGUI.FloatField(ControlRect, PropertyInfo.Property.floatValue);
}
}
public class ShaderGUISliderItem:ShaderGUIItem
{
public float Min = 0;
public float Max = 1;
public string RangePropertyName;
ShaderPropertyInfo _rangePropertyInfo;
private const float RangeWidth = 50f;
public override void InitTriggerByChild()
{
if (RangePropertyName != null)
{
_rangePropertyInfo = RootItem.PropertyInfoDic[RangePropertyName];
Min = _rangePropertyInfo.Property.vectorValue.x;
Max = _rangePropertyInfo.Property.vectorValue.y;
}
base.InitTriggerByChild();
}
public ShaderGUISliderItem(ShaderGUIRootItem rootItem, ShaderGUIItem parentItem) :
base(rootItem, parentItem: parentItem) { }
public override void DrawController()
{
if (_rangePropertyInfo != null)
{
Rect minRect = ControlRect;
minRect.width = RangeWidth;
Rect maxRect = ControlRect;
maxRect.x += maxRect.width;
maxRect.x -= RangeWidth;
maxRect.width = RangeWidth;
ControlRect.x += RangeWidth;
ControlRect.width -= 2 * RangeWidth;
RangeVecHasMixedValue(out bool minValueHasMixed,out bool maxValueHasMixed);
Vector4 rangeVector = _rangePropertyInfo.Property.vectorValue;
float min = rangeVector.x;
float max = rangeVector.y;
EditorGUI.showMixedValue = minValueHasMixed;
GUI.backgroundColor = RootItem.DefaultBackgroundColor;
min = EditorGUI.FloatField(minRect, min);
EditorGUI.showMixedValue = maxValueHasMixed;
max = EditorGUI.FloatField(maxRect, max);
rangeVector.x = min;
rangeVector.y = max;
_rangePropertyInfo.Property.vectorValue = rangeVector;
EditorGUI.showMixedValue = PropertyInfo.Property.hasMixedValue;
if (IsPropertyAnimated(PropertyName)) GUI.backgroundColor = RootItem.AnimatedBackgroundColor;
PropertyInfo.Property.floatValue = EditorGUI.Slider(ControlRect, PropertyInfo.Property.floatValue, min, max);
GUI.backgroundColor = RootItem.DefaultBackgroundColor;
EditorGUI.showMixedValue = false;
}
else
{
PropertyInfo.Property.floatValue = EditorGUI.Slider(ControlRect, PropertyInfo.Property.floatValue,Min,Max);
}
}
void RangeVecHasMixedValue( out bool minValueHasMixed, out bool maxValueHasMixed)
{
minValueHasMixed = false;
maxValueHasMixed = false;
if (RootItem.Mats.Count > 1)
{
MaterialProperty rangeProperty = _rangePropertyInfo.Property;
float minValue = 0;
float maxValue = 0;
for (int i = 0; i < RootItem.Mats.Count; i++)
{
Vector4 rangeVec = RootItem.Mats[i].GetVector(RangePropertyName);
if (i == 0)
{
minValue = rangeVec.x;
maxValue = rangeVec.y;
}
else
{
if (!Mathf.Approximately(minValue, rangeVec.x))
{
minValueHasMixed = true;
}
if (!Mathf.Approximately(maxValue, rangeVec.y))
{
maxValueHasMixed = true;
}
}
}
}
}
bool RangePropIsDefaultValue()
{
MaterialProperty rangeProperty = _rangePropertyInfo.Property;
return rangeProperty.vectorValue == RootItem.Shader.GetPropertyDefaultVectorValue(_rangePropertyInfo.Index) && !rangeProperty.hasMixedValue;
}
public override void CheckIsPropertyModified(bool isCallByChild = false)
{
if (RangePropertyName != null)
{
if (!isCallByChild) //只有自身Reset了,才需要查询自己的状态是否正确
{
bool isDefaultValue = true;
float defaultValue = RootItem.Shader.GetPropertyDefaultFloatValue(PropertyInfo.Index);
isDefaultValue = Mathf.Approximately(PropertyInfo.Property.floatValue, defaultValue);
Vector4 defaultRangeVec = RootItem.Shader.GetPropertyDefaultVectorValue(_rangePropertyInfo.Index);
isDefaultValue &= _rangePropertyInfo.Property.vectorValue == defaultRangeVec;
base.CheckIsPropertyModified(isCallByChild);
if (isDefaultValue == PropertyIsDefaultValue)
{
return; //如果状态没有改变,就不需要做任何操作
}
else
{
PropertyIsDefaultValue = isDefaultValue;
}
}
HasModified = !PropertyIsDefaultValue;
foreach (var childItem in ChildrenItemList)
{
HasModified |= childItem.HasModified;
}
ParentItem?.CheckIsPropertyModified(true);
}
else
{
base.CheckIsPropertyModified(isCallByChild);
}
}
public override void ExecuteReset(bool isCallByParent = false)
{
if (RangePropertyName != null)
{
PropertyInfo.Property.floatValue = RootItem.Shader.GetPropertyDefaultFloatValue(PropertyInfo.Index);
_rangePropertyInfo.Property.vectorValue =
RootItem.Shader.GetPropertyDefaultVectorValue(_rangePropertyInfo.Index);
PropertyIsDefaultValue = true;
foreach (var childItem in ChildrenItemList)
{
childItem.ExecuteReset(true);
}
HasModified = false;
if (!isCallByParent) //直接由用户触发重置
{
ParentItem?.CheckIsPropertyModified(true);
}
}
else
{
base.ExecuteReset(isCallByParent);
}
}
}
//用于滑动控制Label的方案。
// DraggableLabelFloat.cs
public static class DraggableLabelFloat
{
// 为每个控件实例缓存一次拖拽状态
private static readonly System.Collections.Generic.Dictionary<int, DragState> s_Drag =
new System.Collections.Generic.Dictionary<int, DragState>();
private class DragState
{
public float startValue;
public float dragX; // 累计水平位移(单位:像素)
}
public static float Handle(Rect labelRect, float value, float sensitivity = -1f, float? min = null, float? max = null)
{
EditorGUIUtility.AddCursorRect(labelRect, MouseCursor.SlideArrow);
int id = GUIUtility.GetControlID(FocusType.Passive, labelRect);
Event e = Event.current;
switch (e.GetTypeForControl(id))
{
case EventType.MouseDown:
if (labelRect.Contains(e.mousePosition) && e.button == 0)
{
GUIUtility.hotControl = id;
e.Use();
EditorGUIUtility.SetWantsMouseJumping(1);
s_Drag[id] = new DragState
{
startValue = value,
dragX = 0f
};
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl == id && s_Drag.TryGetValue(id, out var st))
{
// 关键:使用 Event.delta 累加位移,兼容越界/跳回
st.dragX += e.delta.x;
float baseSens = sensitivity > 0f
? sensitivity
: 0.003f * Mathf.Max(1f, Mathf.Abs(st.startValue));
float modifier = 1f;
if (e.shift) modifier *= 0.1f;
if (e.control || e.command) modifier *= 10f;
float accel = 1f + 0.15f * Mathf.Clamp01(Mathf.Abs(st.dragX) / 50f);
float newValue = st.startValue + st.dragX * baseSens * modifier * accel;
if (min.HasValue) newValue = Mathf.Max(min.Value, newValue);
if (max.HasValue) newValue = Mathf.Min(max.Value, newValue);
if (!float.IsNaN(newValue) && !float.IsInfinity(newValue) && !Mathf.Approximately(newValue, value))
{
GUI.changed = true;
value = newValue;
}
e.Use();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == id)
{
GUIUtility.hotControl = 0;
EditorGUIUtility.SetWantsMouseJumping(0);
s_Drag.Remove(id);
e.Use();
}
break;
case EventType.KeyDown:
// 可选:ESC 取消拖拽并还原
if (GUIUtility.hotControl == id && e.keyCode == KeyCode.Escape && s_Drag.TryGetValue(id, out var st2))
{
value = st2.startValue;
GUI.changed = true;
GUIUtility.hotControl = 0;
EditorGUIUtility.SetWantsMouseJumping(0);
s_Drag.Remove(id);
e.Use();
}
break;
}
return value;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b82b6bb5065f449f98cdba68daa4c16f
timeCreated: 1758462240
@@ -0,0 +1,80 @@
using UnityEditor;
using UnityEngine;
using UnityEditor.AnimatedValues;
namespace NBShaderEditor
{
public class ShaderGUIFoldOutHelper
{
public ShaderGUIFoldOutHelper(ShaderGUIRootItem rootItem, string foldOutPropertyName)
{
_rootItem = rootItem;
_propertyName = foldOutPropertyName;
_propertyInfo = _rootItem.PropertyInfoDic[_propertyName];
animBool.valueChanged.AddListener(rootItem.MatEditor.Repaint);
animBool.speed = 6f;
}
private ShaderGUIRootItem _rootItem;
private string _propertyName;
private AnimBool animBool = new AnimBool();
private const float foldOutWidth = 15f;
private ShaderPropertyInfo _propertyInfo;
public bool BeginFadedGroup(Rect baseRect)
{
Rect foldOutRect = baseRect;
foldOutRect.x = baseRect.x - foldOutWidth;
foldOutRect.width = foldOutWidth + ShaderGUIItem.LabelWidth;//覆盖整个Label
animBool.target = _propertyInfo.Property.floatValue>0.5f?true:false;
animBool.target = EditorGUI.Foldout(foldOutRect,animBool.target,string.Empty,true);
_propertyInfo.Property.floatValue = animBool.target?1f:0f;
return EditorGUILayout.BeginFadeGroup(animBool.faded);
}
public void EndFadedGroup()
{
EditorGUILayout.EndFadeGroup();
}
}
public class ShaderGUIBigBlockItem:ShaderGUIItem
{
ShaderGUIFoldOutHelper _foldOutHelper;
GUIStyle _boldStyle = new GUIStyle(EditorStyles.boldLabel);
public string FoldOutPropertyName { get; set; }
public override void InitTriggerByChild()
{
_foldOutHelper = new ShaderGUIFoldOutHelper(RootItem, FoldOutPropertyName);
base.InitTriggerByChild();
}
public ShaderGUIBigBlockItem(ShaderGUIRootItem rootItem, ShaderGUIItem parentItem) :
base(rootItem, parentItem: parentItem)
{
}
public override void OnGUI()//完全覆写
{
EditorGUILayout.Space();
GetRect();
EditorGUI.LabelField(LabelRect, GuiContent,_boldStyle);
DrawResetButton();
EditorGUI.indentLevel++;
bool isOpen = _foldOutHelper.BeginFadedGroup(BaseRect);
if (isOpen)
{
DrawBlock();
}
EditorGUILayout.EndFadeGroup();
EditorGUI.indentLevel--;
Rect rect = EditorGUILayout.GetControlRect(false, 1);
EditorGUI.DrawRect(rect, new Color(0.5f, 0.5f, 0.5f, 0.5f));
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6228baa804b041658eaebea96655b431
timeCreated: 1758373869
@@ -0,0 +1,208 @@
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
namespace NBShaderEditor
{
public enum MixedBool
{
False = 0,
True = 1,
Mixed = -1
}
public class ShaderGUIItem
{
public const float LabelWidth = 100f;
public ShaderPropertyInfo PropertyInfo;
public ShaderGUIItem ParentItem;
public List<ShaderGUIItem> ChildrenItemList = new List<ShaderGUIItem>();
public ShaderGUIRootItem RootItem;
public string PropertyName;
public GUIContent GuiContent;
public virtual void InitTriggerByChild()//根Child一定要做这个事情
{
if ( PropertyInfo == null && PropertyName != null)
{
PropertyInfo = RootItem.PropertyInfoDic[PropertyName];
}
CheckIsPropertyModified();
}
public ShaderGUIItem(ShaderGUIRootItem rtItem,ShaderGUIItem parentItem=null)
{
RootItem = rtItem;
if (parentItem != null)
{
ParentItem = parentItem;
if (!parentItem.ChildrenItemList.Contains(this))
{
ParentItem.ChildrenItemList.Add(this);
}
}
}
public Rect BaseRect;
public Rect LabelRect;
public Rect ControlRect;
public Rect ResetRect;
private static float ResetButtonSize => EditorGUIUtility.singleLineHeight;
public virtual void GetRect()
{
BaseRect = EditorGUILayout.GetControlRect();
LabelRect = BaseRect;
LabelRect.width = LabelWidth;
ControlRect = BaseRect;
ControlRect.x += LabelWidth;
ControlRect.width -= LabelWidth;
ControlRect.width -= ResetButtonSize;
ResetRect = BaseRect;
ResetRect.x = BaseRect.x + BaseRect.width -ResetButtonSize;
ResetRect.width = ResetButtonSize;
}
public virtual void OnGUI()
{
GetRect();
EditorGUI.LabelField(LabelRect, GuiContent);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = PropertyInfo.Property.hasMixedValue;
if (IsPropertyAnimated(PropertyName)) GUI.backgroundColor = RootItem.AnimatedBackgroundColor;
DrawController();
GUI.backgroundColor = RootItem.DefaultBackgroundColor;
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
OnEndChange();
}
DrawResetButton();
DrawBlock();
}
public void DrawResetButton()//如果重写OnGUI,一定要记得调用DrawResetButton
{
_resetButtonContent.text = HasModified ? "R" : "";
_resetButtonStyle = HasModified ? GUI.skin.button : GUI.skin.label;
if (GUI.Button(ResetRect, _resetButtonContent, _resetButtonStyle))
{
ExecuteReset();
}
}
public virtual void DrawController()
{
}
public virtual void DrawBlock()
{
}
public virtual void OnEndChange()
{
CheckIsPropertyModified();
}
private string _animationPropertyPath;
public bool IsPropertyAnimated(string propertyName)
{
if (propertyName == null) return false;
if (AnimationMode.InAnimationMode())
{
if (_animationPropertyPath == null)
{
_animationPropertyPath = "material." + propertyName;
}
foreach (var r in RootItem.RenderersUsingThisMaterial)
{
if (AnimationMode.IsPropertyAnimated(r, _animationPropertyPath))
{
// Debug.Log(propertyName);
return true;
}
}
}
return false;
}
#region ResetLogic
private GUIContent _resetButtonContent = new GUIContent("R","重置当前属性及子集属性(如有)");
private GUIStyle _resetButtonStyle;
public bool HasModified = false;
public bool PropertyIsDefaultValue = true;
public virtual void CheckIsPropertyModified(bool isCallByChild = false)
{
if (!isCallByChild)//只有自身Reset了,才需要查询自己的状态是否正确
{
bool isDefaultValue = true;
if (PropertyInfo != null)
{
switch (PropertyInfo.Property.type)
{
case MaterialProperty.PropType.Float:
case MaterialProperty.PropType.Range:
float defaultValue = RootItem.Shader.GetPropertyDefaultFloatValue(PropertyInfo.Index);
isDefaultValue = Mathf.Approximately(PropertyInfo.Property.floatValue, defaultValue);
break;
}
}
else
{
isDefaultValue = true;//如果没有Property,则是看子集的情况
}
if (isDefaultValue == PropertyIsDefaultValue)
{
return;//如果状态没有改变,就不需要做任何操作
}
else
{
PropertyIsDefaultValue = isDefaultValue;
}
}
HasModified = !PropertyIsDefaultValue;
foreach (var childItem in ChildrenItemList)
{
HasModified |= childItem.HasModified;
}
ParentItem?.CheckIsPropertyModified(true);
}
public virtual void ExecuteReset(bool isCallByParent = false)
{
if (PropertyInfo != null)
{
switch (PropertyInfo.Property.type)
{
case MaterialProperty.PropType.Float:
case MaterialProperty.PropType.Range:
float defaultValue = RootItem.Shader.GetPropertyDefaultFloatValue(PropertyInfo.Index);
PropertyInfo.Property.floatValue = defaultValue;
break;
}
PropertyIsDefaultValue = true;
}
foreach (var childItem in ChildrenItemList)
{
childItem.ExecuteReset(true);
}
HasModified = false;
if (!isCallByParent)//直接由用户触发重置
{
ParentItem?.CheckIsPropertyModified(true);
}
}
#endregion
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4f948e090bae4a558a52cb56d0b6c9fc
timeCreated: 1758127003
@@ -0,0 +1,20 @@
using UnityEditor;
namespace NBShaderEditor
{
public class ShaderGUIPopUpItem:ShaderGUIItem
{
public ShaderGUIPopUpItem(ShaderGUIRootItem rootItem, ShaderGUIItem parentItem) :
base(rootItem, parentItem: parentItem)
{
// base.InitTriggerByChild();
}
public string[] PopUpNames;
public override void DrawController()
{
PropertyInfo.Property.floatValue = EditorGUI.Popup(ControlRect,(int)PropertyInfo.Property.floatValue,PopUpNames);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a4147e85b43d4bcaab43dedf111c41fb
timeCreated: 1758444036
@@ -0,0 +1,90 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using NBShader;
namespace NBShaderEditor
{
public class ShaderPropertyInfo
{
public MaterialProperty Property;
public string Name;
public int Index;
}
public class ShaderGUIRootItem
{
public Shader Shader;
public MaterialEditor MatEditor;
public List<Material> Mats;
public Dictionary<string,ShaderPropertyInfo> PropertyInfoDic = new Dictionary<string,ShaderPropertyInfo>();
public List<ShaderFlagsBase> ShaderFlags;//各个继承类各自初始化
public bool IsInit = true;
public Color DefaultBackgroundColor;
public readonly Color AnimatedBackgroundColor = Color.red;
public List<Renderer> RenderersUsingThisMaterial = new List<Renderer>();
public virtual void OnGUI(MaterialEditor editor,MaterialProperty[] props)
{
MatEditor = editor;
if (IsInit)
{
DefaultBackgroundColor = GUI.backgroundColor;
Mats = new List<Material>();
foreach (var obj in editor.targets)
{
Mats.Add(obj as Material);
}
InitFlags(Mats);
Shader = Mats[0].shader;
CacheRenderersUsingThisMaterial(Mats[0]);
}
if (PropertyInfoDic.Count != props.Length)
{
PropertyInfoDic.Clear();
for (int i = 0; i < props.Length; i++)
{
ShaderPropertyInfo propInfo = new ShaderPropertyInfo();
propInfo.Property = props[i];
propInfo.Name = props[i].name;
propInfo.Index = i;
PropertyInfoDic.Add(propInfo.Name, propInfo);
}
}
else
{
for (int i = 0; i < props.Length; i++)
{
PropertyInfoDic[props[i].name].Property = props[i];
}
}
OnChildOnGUI();
IsInit = false;
}
void CacheRenderersUsingThisMaterial(Material material)
{
Renderer[] renderers = UnityEngine.Object.FindObjectsOfType(typeof(Renderer)) as Renderer[];//为了兼容性使用较慢版本
RenderersUsingThisMaterial.Clear();
foreach (Renderer renderer in renderers)
{
foreach (var mat in renderer.sharedMaterials)
{
if (mat == material)
{
RenderersUsingThisMaterial.Add(renderer);
break;
}
}
}
}
public virtual void InitFlags(List<Material> mats) { } //各个子类各自实现
public virtual void OnChildOnGUI()
{
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e57b381204754ae780ab305e5feff475
timeCreated: 1758206205
@@ -0,0 +1,425 @@
using System.Collections.Generic;
using System;
using UnityEngine;
using ShaderPropertyPack = NBShaderEditor.ShaderGUIHelper.ShaderPropertyPack;
using UnityEditor;
namespace NBShaderEditor
{
public class ShaderGUIResetTool
{
private ShaderGUIHelper _helper;
private Shader _shader;
public bool IsInitResetData = false;
private Stack<(string,string)> _scopeContextStack = new Stack<(string,string)>();
public void CheckAllModifyOnValueChange()
{
foreach (var item in ResetItemDict.Values)
{
item.HasModified = item.CheckHasModifyOnValueChange();
}
}
public void Init(ShaderGUIHelper helper)
{
_helper = helper;
_shader = helper.shader;
IsInitResetData = true;
ResetItemDict.Clear();
_scopeContextStack.Clear();
}
public void EndInit()
{
IsInitResetData = false;
}
public void Update()
{
if (_needUpdate)
{
_needUpdate = false;
CheckAllModifyOnValueChange();
}
}
private bool _needUpdate = false;
public void NeedUpdate()
{
_needUpdate = true;
}
public ShaderGUIResetTool(ShaderGUIHelper helper)
{
Init(helper);
}
public Dictionary<(string, string), ResetItem> ResetItemDict = new Dictionary<(string, string), ResetItem>();
public class ResetItem
{
public ResetItem Parent;
public List<ResetItem> ChildResetItems = new List<ResetItem>();
public Action ResetCallBack;
public Action OnValueChangedCallBack;
public Func<bool> CheckHasModifyOnValueChange;
public Func<bool> CheckHasMixedValueOnValueChange;
public (string, string) NameTuple;
public bool HasModified = false;
public bool HasMixedValue =false;
public bool ChildHasModified = false;
public bool ChildHasMixedValue = false;
public void Init((string, string) nameTuple,Action resetCallBack,Action onValueChangedCallBack,Func<bool> checkHasModifyOnValueChange,Func<bool> checkHasMixedValueOnValueChange)
{
NameTuple = nameTuple;
ResetCallBack = resetCallBack;
OnValueChangedCallBack = onValueChangedCallBack;
CheckHasModifyOnValueChange = checkHasModifyOnValueChange;
CheckHasMixedValueOnValueChange = checkHasMixedValueOnValueChange;
}
public void Execute(bool isParentCall = false)
{
ResetCallBack?.Invoke();
OnValueChangedCallBack?.Invoke();
HasModified = CheckHasModifyOnValueChange();
HasMixedValue = CheckHasMixedValueOnValueChange();
CheckOnValueChange(isParentCall);
foreach (var item in ChildResetItems)
{
item.Execute(true);
}
}
public void CheckOnValueChange(bool isParentCall = false)
{
HasModified = CheckHasModifyOnValueChange();
HasMixedValue = CheckHasMixedValueOnValueChange();
foreach (var childItem in ChildResetItems)
{
HasMixedValue |= childItem.HasMixedValue;
HasModified |= childItem.HasModified;
}
if (!isParentCall && Parent != null)
{
Parent.CheckOnValueChange();
}
}
}
public void CheckOnValueChange((string,string) nameTuple)
{
if (ResetItemDict.ContainsKey(nameTuple))
{
ResetItemDict[nameTuple].CheckOnValueChange();
}
else
{
Debug.LogError("不包含ResetItemDict:"+nameTuple);
}
}
public void DrawResetModifyButton(Rect rect,(string, string) nameTuple, Action resetCallBack,
Action onValueChangedCallBack,Func<bool> checkHasModifyOnValueChange,Func<bool> checkHasMixedValueOnValueChange,bool isSharedGlobalParent = false)
{
ConstructResetItem(nameTuple,resetCallBack,onValueChangedCallBack,checkHasModifyOnValueChange,checkHasMixedValueOnValueChange,isSharedGlobalParent);
DrawResetModifyButtonFinal(rect,nameTuple);
}
public void DrawResetModifyButton(Rect rect,(string,string)nameTuple,ShaderPropertyPack pack, Action resetAction,Action onValueChangedCallBack,VectorValeType vectorValeType = VectorValeType.Undefine,bool isSharedGlobalParent = false)
{
// (string, string) nameTuple = (label, pack.property.name);
ConstructResetItem(nameTuple,
resetAction: ()=>{
SetPropertyToDefaultValue(pack,vectorValeType);
resetAction?.Invoke();
},onValueChangedCallBack:onValueChangedCallBack,
checkHasModifyOnValueChange: () => IsPropertyModified(pack,vectorValeType),
checkHasMixedValueOnValueChange: () => pack.property.hasMixedValue,
isSharedGlobalParent: isSharedGlobalParent
);
if (ResetItemDict.ContainsKey(nameTuple))
{
DrawResetModifyButtonFinal(rect,nameTuple);
}
}
public void DrawResetModifyButton(Rect rect, string label)
{
//大部分功能都是触发子类
ConstructResetItem((label, ""), resetAction: () => { },onValueChangedCallBack: () => { }, () => false, () => false);
DrawResetModifyButtonFinal(rect,(label,""));
}
//isSharedGlobalParent==>有些组件是公用的,比如极坐标一类。这些是不会设置父Item的。
public void ConstructResetItem((string,string) nameTuple, Action resetAction,
Action onValueChangedCallBack,Func<bool> checkHasModifyOnValueChange,Func<bool> checkHasMixedValueOnValueChange,bool isSharedGlobalParent = false)
{
if(!IsInitResetData) return;
if (!ResetItemDict.ContainsKey(nameTuple))
{
ResetItem item = new ResetItem();
item.Init(nameTuple,resetAction,onValueChangedCallBack,checkHasModifyOnValueChange,checkHasMixedValueOnValueChange);
ResetItemDict.Add(nameTuple,item);
if (_scopeContextStack.Count > 0 && !isSharedGlobalParent)
{
var contextNameTuple = _scopeContextStack.Peek();
ResetItem parentItem = ResetItemDict[contextNameTuple];
parentItem.ChildResetItems.Add(item);
item.Parent = parentItem;
}
if (_helper.matEditor.targets.Length == 1)
{
onValueChangedCallBack?.Invoke();//属性值初始化
}
item.CheckOnValueChange();//Init
}
else
{
// Debug.LogError("ResetItem已经存在:"+nameTuple.ToString());
}
//就算是已经ContainsKey了,也Push和Pop一下。没有作用,但让写法更简单。
_scopeContextStack.Push(nameTuple);
}
public void EndResetModifyButtonScope()
{
if(!IsInitResetData) return;
if(_scopeContextStack.Count == 0) return;
_scopeContextStack.Pop();
}
public float ResetButtonSize => EditorGUIUtility.singleLineHeight;
private GUIContent resetIconContent = new GUIContent();
//仅仅只是Drawer
private void DrawResetModifyButtonFinal(Rect position, (string, string) nameTuple)
{
ResetItem item;
// GUILayout.FlexibleSpace();
if (ResetItemDict.ContainsKey(nameTuple))
{
item = ResetItemDict[nameTuple];
}
else
{
return;
}
float btnSize = ResetButtonSize;
string iconText;
bool isDisabled = true;
GUIStyle iconStyle;
if (item.HasModified || item.HasMixedValue)
{
isDisabled = false;
iconText = "R";
iconStyle = GUI.skin.button;
}
else
{
isDisabled = true;
iconText = "";
iconStyle = GUI.skin.label;
}
resetIconContent.text = iconText;
EditorGUI.BeginDisabledGroup(isDisabled);
// if (GUILayout.Button(iconTexture, GUILayout.Width(btnSize), GUILayout.Height(btnSize)))
if (position.width <= 0)
{
position = GUILayoutUtility.GetRect(resetIconContent, GUI.skin.button, GUILayout.Width(btnSize),
GUILayout.Height(btnSize));
}
if(GUI.Button(position,resetIconContent,iconStyle))
{
item.Execute();
}
EditorGUI.EndDisabledGroup();
}
public void SetPropertyToDefaultValue(ShaderPropertyPack pack,VectorValeType vectorValeType = VectorValeType.Undefine)
{
MaterialProperty property = pack.property;
MaterialProperty.PropType propertyType = property.type;
if (pack.property.type == MaterialProperty.PropType.Texture && vectorValeType != VectorValeType.Undefine)
{
propertyType = MaterialProperty.PropType.Vector;//Tilling or Offset
}
switch (propertyType)
{
case MaterialProperty.PropType.Color:
Vector4 colorValue = _shader.GetPropertyDefaultVectorValue(pack.index);
property.colorValue = new Color(colorValue.x, colorValue.y, colorValue.z, colorValue.x);
break;
case MaterialProperty.PropType.Vector:
Vector4 defaultVecValue;
Vector4 vecValue;
if (vectorValeType == VectorValeType.Tilling || vectorValeType == VectorValeType.Offset)
{
defaultVecValue = new Vector4(1f, 1f, 0f, 0f);
vecValue = property.textureScaleAndOffset;
}
else
{
defaultVecValue = _shader.GetPropertyDefaultVectorValue(pack.index);
vecValue = property.vectorValue;
}
switch (vectorValeType)
{
case VectorValeType.Undefine: Debug.LogError("VectorValeType is undefined"); break;
case VectorValeType.X: vecValue.x = defaultVecValue.x;property.vectorValue = vecValue;break;
case VectorValeType.Y: vecValue.y = defaultVecValue.y;property.vectorValue = vecValue;break;
case VectorValeType.Z: vecValue.z = defaultVecValue.z;property.vectorValue = vecValue;break;
case VectorValeType.W: vecValue.w = defaultVecValue.w;property.vectorValue = vecValue;break;
case VectorValeType.XY:vecValue.x = defaultVecValue.x; vecValue.y = defaultVecValue.y;
property.vectorValue = vecValue;break;
case VectorValeType.Tilling:vecValue.x = defaultVecValue.x; vecValue.y = defaultVecValue.y;
if (property.type == MaterialProperty.PropType.Texture)
{
property.textureScaleAndOffset = vecValue;
}
else
{
property.vectorValue = vecValue;
}
break;
case VectorValeType.ZW:vecValue.z = defaultVecValue.z; vecValue.w = defaultVecValue.w;
property.vectorValue = vecValue;break;
case VectorValeType.Offset:vecValue.z = defaultVecValue.z; vecValue.w = defaultVecValue.w;
if (property.type == MaterialProperty.PropType.Texture)
{
property.textureScaleAndOffset = vecValue;
}
else
{
property.vectorValue = vecValue;
}
break;
case VectorValeType.XYZ:vecValue.x = defaultVecValue.x; vecValue.y = defaultVecValue.y;
vecValue.z = defaultVecValue.z; property.vectorValue = vecValue;break;
case VectorValeType.XYZW: property.vectorValue = defaultVecValue;break;
}
break;
case MaterialProperty.PropType.Float or MaterialProperty.PropType.Range:
float value = _shader.GetPropertyDefaultFloatValue(pack.index);
property.floatValue = value;
break;
case MaterialProperty.PropType.Texture:
if (property.textureValue == null)
{
break;
}
else
{
property.textureValue = null;
break;
}
// return property.textureValue.name == shader.GetPropertyTextureDefaultName(pack.index) ? false : true;
default:
// 如果不属于上述类型,输出提示信息
Debug.Log($"{property.displayName} has no default value or unsupported type");
break;
}
}
public bool IsPropertyModified(ShaderPropertyPack pack,VectorValeType vectorValeType = VectorValeType.Undefine)
{
MaterialProperty property = pack.property;
MaterialProperty.PropType propertyType = property.type;
if (pack.property.type == MaterialProperty.PropType.Texture && vectorValeType != VectorValeType.Undefine)
{
propertyType = MaterialProperty.PropType.Vector;//Tilling or Offset
}
switch (propertyType)
{
case MaterialProperty.PropType.Color:
Vector4 colorValue = _shader.GetPropertyDefaultVectorValue(pack.index);
Color color = new Color(colorValue.x, colorValue.y, colorValue.z, colorValue.w);
return property.colorValue == color ? false : true;
case MaterialProperty.PropType.Vector:
Vector4 defaultVecValue;
Vector4 vecValue;
if (vectorValeType == VectorValeType.Tilling || vectorValeType == VectorValeType.Offset)
{
defaultVecValue = new Vector4(1f, 1f, 0f, 0f);
if (property.type == MaterialProperty.PropType.Texture)
{
vecValue = property.textureScaleAndOffset;
}
else
{
vecValue = property.vectorValue;
}
}
else
{
defaultVecValue = _shader.GetPropertyDefaultVectorValue(pack.index);
vecValue = property.vectorValue;
}
Vector2 defaultVecXYValue = new Vector2(defaultVecValue.x, defaultVecValue.y);
Vector2 defaultVecZWValue = new Vector2(defaultVecValue.z, defaultVecValue.w);
Vector2 vecXYValue = new Vector2(vecValue.x, vecValue.y);
Vector2 vecZWValue = new Vector2(vecValue.z, vecValue.w);
Vector2 defaultVecXYZValue = new Vector3(defaultVecValue.x, defaultVecValue.y,defaultVecValue.z);
Vector2 vecXYZValue = new Vector3(vecValue.x, vecValue.y,vecValue.z);
bool isVecModified = false;
switch (vectorValeType)
{
case VectorValeType.Undefine: Debug.LogError("VectorValeType is undefined"); break;
case VectorValeType.X: isVecModified = Mathf.Approximately(vecValue.x,defaultVecValue.x) ? false : true;break;
case VectorValeType.Y: isVecModified = Mathf.Approximately(vecValue.y,defaultVecValue.y) ? false : true;break;
case VectorValeType.Z: isVecModified = Mathf.Approximately(vecValue.z,defaultVecValue.z) ? false : true;break;
case VectorValeType.W: isVecModified = Mathf.Approximately(vecValue.w,defaultVecValue.w) ? false : true;break;
case VectorValeType.XY:case VectorValeType.Tilling:
isVecModified = vecXYValue == defaultVecXYValue ? false : true;break;
case VectorValeType.ZW:case VectorValeType.Offset:
isVecModified = vecZWValue == defaultVecZWValue ? false : true;break;
case VectorValeType.XYZ:isVecModified = vecXYZValue == defaultVecXYZValue ? false : true ; break;
case VectorValeType.XYZW:isVecModified= vecValue == defaultVecValue? false : true ; break;
}
return isVecModified;
case MaterialProperty.PropType.Float or MaterialProperty.PropType.Range:
return Mathf.Approximately(property.floatValue, _shader.GetPropertyDefaultFloatValue(pack.index)) ? false : true;
case MaterialProperty.PropType.Texture:
if (property.textureValue == null)
{
return false;
}
else
{
return property.textureValue.name == "textureExternal" ? false : true;
}
// return property.textureValue.name == shader.GetPropertyTextureDefaultName(pack.index) ? false : true;
default:
// 如果不属于上述类型,输出提示信息
return false;
// Debug.Log($"{property.displayName} has no default value or unsupported type");
// break;
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 73135babda09451c9e5798b36897637b
timeCreated: 1754727843
@@ -0,0 +1,249 @@
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using NBShader;
namespace NBShaderEditor
{
public class ShaderGUIToolBar
{
public ShaderGUIHelper Helper;
private int viewModeIndex;
private readonly string[] viewModes = { "List", "Grid" };
// private string searchText = "";
private MaterialEditor _editor => Helper.matEditor;
public ShaderGUIToolBar(ShaderGUIHelper helper)
{
Helper = helper;
}
private static Material copiedMaterial;
private static Shader copiedShader;
// 帮助链接URL
private const string HELP_URL = "https://owejt9diz2c.feishu.cn/wiki/BHz8wHHSjiYJagk7WrmcAcconlb?from=from_copylink";
// private Vector2 imagePos;
// private Texture2D icon;
// private Texture2D image;
public void DrawToolbar()
{
float BtnWidth = 30f;
// 开始工具栏区域 (背景)
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
// 1. 选择当前材质
if (GUILayout.Button(EditorGUIUtility.IconContent("Material On Icon","跳到当前材质|跳到当前材质"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
{
EditorGUIUtility.PingObject(Helper.mats[0]);
}
if (GUILayout.Button(EditorGUIUtility.IconContent("TreeEditor.Trash","清除没有使用的贴图|清除没有使用的贴图"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
{
foreach (var mat in Helper.mats)
{
CleanUnusedTextureProperties(Helper.mats[0]);//先清理不属于当前Shader的贴图
}
Helper.isClearUnUsedTexture = true;
}
if (GUILayout.Button(new GUIContent("C","复制材质属性"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
{
copiedMaterial = Helper.mats[0];
copiedShader = copiedMaterial.shader;
}
if (GUILayout.Button(new GUIContent("V","粘贴材质属性"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
{
if (copiedShader)
{
Helper.mats[0].shader = copiedShader;
}
if (copiedMaterial)
{
Helper.mats[0].CopyPropertiesFromMaterial(copiedMaterial);
}
}
if (GUILayout.Button(new GUIContent("R","特殊重置功能"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
{
ShowResetPopupMenu();
}
if (GUILayout.Button(EditorGUIUtility.IconContent("d_UnityEditor.HierarchyWindow","折叠所有控件|折叠所有控件"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
{
for (int i = 0;i<Helper.shaderFlags.Length;i++)
{
W9ParticleShaderFlags shaderFlags = (W9ParticleShaderFlags)Helper.shaderFlags[i];
for (int j = 3; j <= 5; j++)
{
Helper.mats[i].SetInteger(shaderFlags.GetShaderFlagsId(j),0);
}
}
}
// 2. 添加下拉菜单
// viewModeIndex = EditorGUILayout.Popup(viewModeIndex, viewModes, EditorStyles.toolbarPopup, GUILayout.Width(BtnWidth));
// 3. 添加搜索框
GUILayout.FlexibleSpace(); // 将搜索框推到中间
// // 搜索框样式
// GUIStyle searchField = new GUIStyle("SearchTextField");
// GUIStyle cancelButton = new GUIStyle("SearchCancelButton");
//
// EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(300));
// {
// EditorGUI.BeginChangeCheck();
// searchText = EditorGUILayout.TextField(searchText, searchField);
// if (EditorGUI.EndChangeCheck())
// {
// Helper.isSearchText = searchText.Length > 0;
// Helper.searchText = searchText;
// }
//
// // 清除搜索按钮
// if (GUILayout.Button("", cancelButton))
// {
// searchText = "";
// GUI.FocusControl(null); // 移除焦点
// }
// }
// EditorGUILayout.EndHorizontal();
// // 4. 右侧按钮组
// if (GUILayout.Button(EditorGUIUtility.IconContent("TreeEditor.Refresh"), EditorStyles.toolbarButton))
// {
// Debug.Log("Refresh clicked");
// }
//
// // 选项菜单
// if (GUILayout.Button(EditorGUIUtility.IconContent("_Popup"), EditorStyles.toolbarButton))
// {
// // 创建下拉菜单
// GenericMenu menu = new GenericMenu();
// menu.AddItem(new GUIContent("Option 1"), false, () => Debug.Log("Option 1"));
// menu.AddItem(new GUIContent("Option 2"), false, () => Debug.Log("Option 2"));
// menu.ShowAsContext();
// }
// 贴图加载
// if (icon == null)
// icon = AssetDatabase.LoadAssetAtPath<Texture2D>(AssetDatabase.GUIDToAssetPath("eaa39f504c2ce7646aece103ba9c4766"));
// if (image == null)
// image = AssetDatabase.LoadAssetAtPath<Texture2D>(AssetDatabase.GUIDToAssetPath("cc6c30349a33a1d4c8242a9ef1a68830"));
// if (GUILayout.Button(new GUIContent(icon,"爸爸!"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
// {
// // 弹出 PopupWindow
// // 弹出浮动窗口
// FloatingImageWindow.ShowWindow(image);
// }
if (GUILayout.Button(EditorGUIUtility.IconContent("d__Help@2x","说明文档|说明文档"), EditorStyles.toolbarButton,GUILayout.Width(BtnWidth)))
{
// 打开浏览器跳转到帮助链接
Application.OpenURL(HELP_URL);
}
EditorGUILayout.EndHorizontal(); // 结束工具栏
}
private void ShowResetPopupMenu()
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("重置特殊UV通道"), false, () =>
{
Helper.ResetTool.ResetItemDict[("特殊UV通道选择","_SpecialUVChannelMode")].Execute();
});
menu.AddItem(new GUIContent("重置旋转扭曲"), false, () =>
{
Helper.ResetTool.ResetItemDict[("","_UTwirlEnabled")].Execute();
});
menu.AddItem(new GUIContent("重置极坐标"), false, () =>
{
Helper.ResetTool.ResetItemDict[("","_PolarCoordinatesEnabled")].Execute();
});
// 弹出位置可以用 Event.current.mousePosition
menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
}
private void CleanUnusedTextureProperties(Material mat)
{
if (mat == null || mat.shader == null) return;
Shader shader = mat.shader;
// 收集 Shader 里声明过的贴图属性
var shaderTexProps = new HashSet<string>();
int count = ShaderUtil.GetPropertyCount(shader);
for (int i = 0; i < count; i++)
{
if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
{
shaderTexProps.Add(ShaderUtil.GetPropertyName(shader, i));
}
}
// 遍历材质所有贴图属性,找到 shader 不再声明的
var allProps = mat.GetTexturePropertyNames();
foreach (var propName in allProps)
{
if (!shaderTexProps.Contains(propName))
{
if (mat.GetTexture(propName) != null)
{
mat.SetTexture(propName, null);
Debug.Log($"清理 {mat.name} 的无效贴图属性: {propName}");
}
}
}
}
// EditorWindow 显示图片
public class FloatingImageWindow : EditorWindow
{
private Texture2D popupImage;
public static void ShowWindow(Texture2D image)
{
// 创建窗口
FloatingImageWindow window = CreateInstance<FloatingImageWindow>();
window.titleContent = new GUIContent("谢谢爸爸");
window.popupImage = image;
// 设置初始尺寸
if (image != null)
window.position = new Rect(Screen.width / 2f - image.width / 2f,
Screen.height / 2f - image.height / 2f,
image.width,
image.height);
else
window.position = new Rect(Screen.width / 2f - 100, Screen.height / 2f - 100, 200, 200);
window.ShowUtility(); // 浮动窗口
}
private void OnGUI()
{
if (popupImage != null)
{
// 绘制图片
Rect rect = new Rect(0, 0, position.width, position.height);
GUI.DrawTexture(rect, popupImage, ScaleMode.ScaleToFit);
}
// 可选:增加关闭按钮
if (GUI.Button(new Rect(position.width - 25, 5, 20, 20), "X"))
{
Close();
}
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: deccdbc6963a48b2ace3358cbba67689
timeCreated: 1754406958
@@ -0,0 +1,165 @@
using System;
using UnityEngine;
using UnityEngine.Rendering;
namespace NBShaderEditor
{
[Serializable]
public class StencilValues
{
public int DefaultQueue = 2000;
[BinaryInt(8, true, 2)] public int Ref = 0;
public CompareFunction Comp = CompareFunction.Always;
public StencilOp Pass = StencilOp.Keep;
public StencilOp Fail = StencilOp.Keep;
public StencilOp ZFail = StencilOp.Keep;
[BinaryInt(8, true, 1)] public int ReadMask = 255;
[BinaryInt(8, true, 1)] public int WriteMask = 255;
}
public static class StencilTestHelper
{
// private static StencilValuesConfig stencilValuesConfig;
public class StencilPropertyNames
{
public string stencil = "_Stencil";
public string stencilComp = "_StencilComp";
public string stencilOp = "_StencilOp";
public string stencilWriteMask = "_StencilWriteMask";
public string stencilReadMask = "_StencilReadMask";
public string stencilZFail = "_StencilZFail";
public string stencilFail = "_StencilFail";
public string stencilKexIndex = "_StencilKeyIndex";
public StencilPropertyNames()
{
}
public StencilPropertyNames(string stencilName, string stencilCompName, string stencilOpName,
string stencilWriteMaskName, string stencilReadMaskName, string stencilZFailName,
string stencilFailName, string stencilKexIndexName)
{
if (!string.IsNullOrEmpty(stencilName))
{
stencil = stencilName;
}
if (!string.IsNullOrEmpty(stencilCompName))
{
stencilComp = stencilCompName;
}
if (!string.IsNullOrEmpty(stencilOpName))
{
stencilOp = stencilOpName;
}
if (!string.IsNullOrEmpty(stencilWriteMaskName))
{
stencilWriteMask = stencilWriteMaskName;
}
if (!string.IsNullOrEmpty(stencilReadMaskName))
{
stencilReadMask = stencilReadMaskName;
}
if (!string.IsNullOrEmpty(stencilZFailName))
{
stencilZFail = stencilZFailName;
}
if (!string.IsNullOrEmpty(stencilFailName))
{
stencilFail = stencilFailName;
}
if (!string.IsNullOrEmpty(stencilKexIndexName))
{
stencilKexIndex = stencilKexIndexName;
}
}
}
private static StencilPropertyNames defaultStencilPropertyNames = new StencilPropertyNames();
// public static void SetMaterialStencil(Material mat,StencilValues stencilValues,out int defaultQueue)
public static void SetMaterialStencil(Material mat, string stencilConfigKey,
StencilValuesConfig stencilValuesConfig, out int defaultQueue,
StencilPropertyNames stencilPropertyNames = null)
{
if (stencilValuesConfig == null)
{
Debug.LogError(mat.name + ": 缺少模板预设,设置Stencil失败");
// stencilValuesConfig =
// AssetDatabase.LoadAssetAtPath<StencilValuesConfig>(
// "Assets/AddressableAssets/Shader/StencilConfig.asset");
}
if (stencilPropertyNames == null)
{
stencilPropertyNames = defaultStencilPropertyNames;
}
StencilValues stencilValues;
if (stencilValuesConfig.ContainsKey(stencilConfigKey))
{
stencilValues = stencilValuesConfig[stencilConfigKey];
if (!string.IsNullOrEmpty(stencilPropertyNames.stencil))
{
mat.SetFloat(stencilPropertyNames.stencil, stencilValues.Ref);
}
if (!string.IsNullOrEmpty(stencilPropertyNames.stencilComp))
{
mat.SetFloat(stencilPropertyNames.stencilComp, (float)stencilValues.Comp);
}
if (!string.IsNullOrEmpty(stencilPropertyNames.stencilOp))
{
mat.SetFloat(stencilPropertyNames.stencilOp, (float)stencilValues.Pass);
}
if (!string.IsNullOrEmpty(stencilPropertyNames.stencilWriteMask))
{
mat.SetFloat(stencilPropertyNames.stencilWriteMask, stencilValues.WriteMask);
}
if (!string.IsNullOrEmpty(stencilPropertyNames.stencilReadMask))
{
mat.SetFloat(stencilPropertyNames.stencilReadMask, stencilValues.ReadMask);
}
if (!string.IsNullOrEmpty(stencilPropertyNames.stencilZFail))
{
mat.SetFloat(stencilPropertyNames.stencilZFail, (float)stencilValues.ZFail);
}
if (!string.IsNullOrEmpty(stencilPropertyNames.stencilFail))
{
mat.SetFloat(stencilPropertyNames.stencilFail, (float)stencilValues.Fail);
}
if (!string.IsNullOrEmpty(stencilPropertyNames.stencilKexIndex))
{
mat.SetFloat(stencilPropertyNames.stencilKexIndex,
stencilValuesConfig.GetKeyIndex(stencilConfigKey));
}
defaultQueue = stencilValues.DefaultQueue;
}
else
{
Debug.LogError("无法设置材质模板参数,因为没有配置模板值", mat);
defaultQueue = mat.renderQueue;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a7d6268a1ca7d824d8da2adf4cb8f74a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using NBShader;
namespace NBShaderEditor
{
public class StencilValuesConfig : ScriptableObject
{
// public Dictionary<string, StencilValues> Config = new Dictionary<string, StencilValues>();
// public StencilValuesConfigDictionary Config = new StencilValuesConfigDictionary();
[Serializable]
public class KeyStencilValues
{
public string key;
public StencilValues Values;
}
[SerializeField]
public List<KeyStencilValues> Config = new List<KeyStencilValues>();
public bool ContainsKey(string key)
{
if (GetStencilValues(key) != null)
{
return true;
}
else
{
return false;
}
}
public StencilValues GetStencilValues(string key)
{
foreach (var item in Config)
{
if (item.key == key)
{
return item.Values;
}
}
Debug.LogError("StencilValuesConfig: 不存在Key"+key);
return null;
}
public int GetKeyIndex(string key)
{
for (int i = 0; i < Config.Count; i++)
{
if (Config[i].key == key)
{
return i;
}
}
Debug.LogError("StencilValuesConfig: 不存在Key"+key);
return -1;
}
public string GetKeyByIndex(int index)
{
return Config[index].key;
}
public StencilValues this[string key]
{
get
{
return GetStencilValues(key);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9177edf81a5b2354490ec4d66c4c069d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,101 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEditor;
public class StringListSerchProvider : ScriptableObject , ISearchWindowProvider
// public class StringListSerchProvider
{
public List<SearchTreeEntry> CreateSearchTree(SearchWindowContext context)
{
List<SearchTreeEntry> serchList = new List<SearchTreeEntry>();
serchList.Add(new SearchTreeGroupEntry(new GUIContent("List"),0));
List<string> listItemAfterSort = listItems.ToList();
sortListItems(ref listItemAfterSort);
List<string> groups = new List<string>();
foreach (var item in listItemAfterSort)
{
string[] entryTitle = item.Split("/");
string groupName = "";
for (int i = 0; i < entryTitle.Length - 1; i++)
{
groupName += entryTitle[i];
if (!groups.Contains(groupName))
{
serchList.Add(new SearchTreeGroupEntry(new GUIContent(entryTitle[i]),i+1));
}
groupName += "/";
}
SearchTreeEntry entry = new SearchTreeEntry(new GUIContent(entryTitle.Last()));
entry.level = entryTitle.Length;
entry.userData = item;//这里是serch操作点击最后的返回值,是什么都可以的。
// Debug.Log(entry.userData);
serchList.Add(entry);
}
return serchList;
}
public bool OnSelectEntry(SearchTreeEntry searchTreeEntry, SearchWindowContext context)
{
string data = (string)searchTreeEntry.userData;
onSetIndexCallback?.Invoke(data);
return true;
}
private string[] listItems;
private Action<string> onSetIndexCallback;
public StringListSerchProvider(string[] items, Action<string> callBack)
{
listItems = items;
onSetIndexCallback = callBack;
}
public void Initialize(string[] items, Action<string> callBack)
{
listItems = items;
onSetIndexCallback = callBack;
}
// private List<string> sortListItems;
void sortListItems(ref List<string> list)
{
// sortListItems = listItems.ToList();
list.Sort((a, b) =>
{
string[] splits1 = a.Split('/');
string[] splits2 = b.Split('/');
for (int i = 0; i < splits1.Length; i++)
{
if (i >= splits2.Length)
{
return 1;
}
int value = splits1[i].CompareTo(splits2[i]);
if (value != 0)
{
if (splits1.Length != splits2.Length && (i == splits1.Length - 1 || i == splits2.Length - 1))
{
return splits1.Length < splits2.Length ? 1 : -1;
}
return value;
}
}
return 0;
});
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aec459410f5254c4bb4d42e7ec8b4b5e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
{
"name": "com.xuanxuan.render.utility.Editor",
"rootNamespace": "",
"references": [
"GUID:8f9e4d586616f13449cfeb86c5f704c2",
"GUID:df380645f10b7bc4b97d4f5eb6303d95",
"GUID:0e3b0e6ce60c7a34094f8f9822c0b7f2"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8495541fcd41b0c40b5b6e6e7a7639d1
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,188 @@
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
namespace NBShaderEditor
{
public class RefreshMaterialInspectorWindow : EditorWindow
{
[MenuItem("ArtTools/刷新选中材质球面板")]
static void refershSelectMaterialInspector()
{
EditorWindow.GetWindow<RefreshMaterialInspectorWindow>("材质球刷新");
}
public static bool isRefreshing = false;
List<Material> materials = new List<Material>();
int i = 0;
private void OnGUI()
{
if (GUILayout.Button("开始刷新材质面板"))
{
materials.Clear();
foreach (UnityEngine.Object o in Selection.GetFiltered(typeof(Material), SelectionMode.DeepAssets))
{
string path = AssetDatabase.GetAssetPath(o);
string fileExtension = Path.GetExtension(path);
if (fileExtension == ".mat")
{
materials.Add((Material)o);
}
}
i = 0;
}
}
private void OnEnable()
{
Debug.Log("刷新材质打开");
isRefreshing = true;
}
private void Update()
{
if(materials.Count <= 0) return;
if (i < materials.Count)
{
// isRefreshing = true;
// SetNormalToUV1(materials[i]);
Selection.activeObject = materials[i];
Debug.Log(materials[i].name,materials[i]);
EditorUtility.DisplayProgressBar("材质球刷新", $"{i + 1}/{materials.Count}", (i + 1) / (float)materials.Count);
i++;
// isRefreshing = false;
}
if (i >= materials.Count)
{
EditorUtility.ClearProgressBar();
materials.Clear();
Debug.Log("材质刷新结束,isRefreshing布尔值 = "+isRefreshing);
}
}
void OnDisable()
{
Debug.Log("刷新材质关闭");
isRefreshing = false;
}
// void SetNormalToUV1(Material mat)
// {
// if (mat.HasProperty("_NormalFrom"))
// {
// mat.SetInteger("_NormalFrom",1);
// }
// }
//
// // [MenuItem("Assets/测试刷新材质", priority = 1)]
// public static void TestRefeshMaterial()
// {
// W9ParticleShaderFlags flags = new W9ParticleShaderFlags();
// int id = Shader.PropertyToID("_Mask2_Toggle");
// foreach (UnityEngine.Object o in Selection.GetFiltered(typeof(Material), SelectionMode.DeepAssets))
// {
// Material mat = o as Material;
// if (mat.shader.name == "XuanXuan/Effects/Particle_NiuBi")
// {
// bool isToggle = mat.GetFloat(id) > 0.5f;
// if (isToggle)
// {
// mat.DisableKeyword("_MASKMAP2");
// flags.SetMaterial(mat);
// flags.SetFlagBits(W9ParticleShaderFlags.FLAG_BIT_PARTICLE_1_MASK_MAP2,index:1);
// }
// // flags.SetMaterial(mat);
// }
// }
// AssetDatabase.SaveAssets();
// }
//
// [MenuItem("Assets/Effect Tool/刷新选中文件夹内材质Wrap模式", priority = 1)]
// public static void SetSelectParticleMaterialWrapMode()
// {
// foreach (UnityEngine.Object o in Selection.GetFiltered(typeof(Material), SelectionMode.DeepAssets))
// {
// Material mat = (Material)o;
// // Debug.Log(mat.shader.name);
// SetParticleMaterialWrapMode((Material)o);
// }
// AssetDatabase.SaveAssets();
// }
//
// public static void SetParticleMaterialWrapMode(Material mat)
// {
//
// if (mat.shader.name == "XuanXuan/Effects/Particle_NiuBi")
// {
// W9ParticleShaderFlags flags = new W9ParticleShaderFlags(mat);
// SetWrapModeFlag(flags,mat,"_BaseMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_BASEMAP);
// SetWrapModeFlag(flags,mat,"_MaskMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_MASKMAP);
// SetWrapModeFlag(flags,mat,"_MaskMap2",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_MASKMAP2);
// SetWrapModeFlag(flags,mat,"_NoiseMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_NOISEMAP);
// SetWrapModeFlag(flags,mat,"_EmissionMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_EMISSIONMAP);
// SetWrapModeFlag(flags,mat,"_DissolveMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_DISSOLVE_MAP);
// SetWrapModeFlag(flags,mat,"_DissolveMaskMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_DISSOLVE_MASKMAP);
// SetWrapModeFlag(flags,mat,"_DissolveRampMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_DISSOLVE_RAMPMAP);
// SetWrapModeFlag(flags,mat,"_ColorBlendMap",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_COLORBLENDMAP);
// SetWrapModeFlag(flags,mat,"_VertexOffset_Map",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_VERTEXOFFSETMAP);
// SetWrapModeFlag(flags,mat,"_ParallaxMapping_Map",W9ParticleShaderFlags.FLAG_BIT_WRAPMODE_PARALLAXMAPPINGMAP);
// }
// }
//
// public static void SetParticleMaterialMaskStrenth(Material mat)
// {
// if (mat.shader.name == "XuanXuan/Effects/Particle_NiuBi")
// {
// Vector4 vec = mat.GetVector("_MaskMap3OffsetAnition");
// if (vec.z < 1)
// {
// Vector4 newVec = new Vector4(vec.x, vec.y, 1, vec.w);
// mat.SetVector("_MaskMap3OffsetAnition",newVec);
// }
// }
// }
//
// static void SetWrapModeFlag(W9ParticleShaderFlags flags, Material mat, string matTexPropertyName, int flagBit)
// {
// if (mat.GetTexture(matTexPropertyName) != null)
// {
// Texture tex = mat.GetTexture(matTexPropertyName);
// Debug.Log(tex.name);
// if (tex.wrapMode == TextureWrapMode.Clamp)
// {
// Debug.Log("This is Clamp");
// flags.SetFlagBits(flagBit,index:2);
// }
// else if (tex.wrapMode == TextureWrapMode.Repeat)
// {
// Debug.Log("This is Repeat");
// flags.ClearFlagBits(flagBit,index:2);
// }
// }
// }
// static IEnumerator refreshMaterialInspector(Material[] materials)
// {
// for (int i = 0; i < materials.Length; i++)
// {
// EditorUtility.DisplayProgressBar("材质球刷新", $"{i + 1}/{materials.Length}", (i + 1) / (float)materials.Length);
// Debug.Log(i);
// // Selection.activeObject = materials[i];
// yield return null;
// }
// EditorUtility.ClearProgressBar();
// // yield break;
// }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 317bb692129be184ebd7249bba265210
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 72e9a7523c1a5994c8fb317e7a9514e0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,61 @@
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace NBShader
{
public class InspectorButtonAttribute : PropertyAttribute
{
public string Label;
public string MethodName;
public InspectorButtonAttribute(string label, string methodName)
{
this.Label = label;
this.MethodName = methodName;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(InspectorButtonAttribute))]
public class InspectorButtonPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
InspectorButtonAttribute buttonAttribute = (InspectorButtonAttribute)attribute;
// 绘制按钮
if (GUI.Button(position, buttonAttribute.Label))
{
// 获取包含该方法的对象
var targetObject = property.serializedObject.targetObject;
// 获取方法信息
var methodInfo = targetObject.GetType().GetMethod(buttonAttribute.MethodName,
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (methodInfo != null)
{
// 调用方法
methodInfo.Invoke(targetObject, null);
}
else
{
Debug.LogError($"Method '{buttonAttribute.MethodName}' not found in {targetObject.name}.");
}
}
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUIUtility.singleLineHeight; // 返回按钮的高度
}
}
#endif
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 45f557806bb54c4dbeaec7a2ded5be83
timeCreated: 1737792133
@@ -0,0 +1,597 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace NBShader
{
//TODO增加一键去重功能。测试排查BUG
[ExecuteInEditMode]
public class MaterialPropertyAgent : MonoBehaviour, IMaterialModifier
{
[System.Serializable]
public struct PropertyData
{
[HideInInspector] public int dataIndexInAgent;
[HideInInspector] public MaterialPropertyAgent agent;
[HideInInspector] public int id;
public int index;
[HideInInspector] public string propName;
public shaderPropertyType type;
public string descripName;
public Color colorValue;
public Vector4 vecValue;
public float floatValue;
[SerializeField] public IEnumerable propNameList;
[HideInInspector] public bool isActive;
[HideInInspector] public Shader shader;
[HideInInspector] public Material mat;
#if UNITY_EDITOR
public float rangMin { get; set; }
public float rangMax { get; set; }
public void setValueByPropChange()
{
agent.refreshShderPropNameList();
if (!agent.isCanUsedIndex(index))
{
index = agent.getCanUsedIndex();
}
string propertyName = UnityEditor.ShaderUtil.GetPropertyName(shader, index);
id = Shader.PropertyToID(propertyName);
descripName = UnityEditor.ShaderUtil.GetPropertyDescription(shader, index);
type = (shaderPropertyType)UnityEditor.ShaderUtil.GetPropertyType(shader, index);
if (type == shaderPropertyType.TexEnv)
{
propName = UnityEditor.ShaderUtil.GetPropertyName(shader, index) + "_ST";
}
else
{
propName = UnityEditor.ShaderUtil.GetPropertyName(shader, index);
}
switch (type)
{
case shaderPropertyType.Color:
colorValue = mat.GetColor(id);
break;
case shaderPropertyType.Float:
floatValue = mat.GetFloat(id);
break;
case shaderPropertyType.Range:
rangMin = UnityEditor.ShaderUtil.GetRangeLimits(shader, index, 1);
rangMax = UnityEditor.ShaderUtil.GetRangeLimits(shader, index, 2);
floatValue = mat.GetFloat(id);
break;
case shaderPropertyType.Vector:
vecValue = mat.GetVector(id);
break;
case shaderPropertyType.TexEnv:
string stName = UnityEditor.ShaderUtil.GetPropertyName(shader, index) + "_ST";
vecValue = mat.GetVector(stName);
break;
}
}
public void inActivateThis()
{
isActive = false;
}
#endif
}
//因为ShaderUtil只是用于Editor,所以复制一个枚举对属性类型进行识别。
public enum shaderPropertyType
{
//
// 摘要:
// Color Property.
Color = 0,
//
// 摘要:
// Vector Property.
Vector = 1,
//
// 摘要:
// Float Property.
Float = 2,
//
// 摘要:
// Range Property.
Range = 3,
//
// 摘要:
// Texture Property.
TexEnv = 4
}
public PropertyData data0 = new PropertyData();
public PropertyData data1 = new PropertyData();
public PropertyData data2 = new PropertyData();
public PropertyData data3 = new PropertyData();
public PropertyData data4 = new PropertyData();
public PropertyData data5 = new PropertyData();
public Shader shader;
public Material mat;
public int materialIndex = 0;
public Renderer customRenderer;
void initMatAndShader(bool initMat = false)
{
if (!initMat)
{
if (mat != null) return;
}
if (customRenderer || GetComponent<Renderer>())
{
Material[] materials;
Renderer r;
if (customRenderer)
{
r = customRenderer;
}
else
{
r = GetComponent<Renderer>();
}
if (Application.isPlaying)
{
materials = r.materials;
}
else
{
materials = r.sharedMaterials;
}
mat = materials[materialIndex];
shader = mat.shader;
}
else if (this.GetComponent<Graphic>())
{
Graphic graphic = this.GetComponent<Graphic>();
//测试,要不要用IMaterialModifier来处理
// if (Application.isPlaying)
// {
// graphic.material = Material.Instantiate(graphic.material);
// }
mat = graphic.material;
shader = mat.shader;
}
else
{
Debug.LogError("MaterialPropertyAgent未找到材质", this.gameObject);
}
}
private void Start()
{
if (Application.isPlaying)
{
initMatAndShader(true);
}
else
{
initMatAndShader(false);
}
}
private void Update()
{
if (mat == null)
{
// initMatAndShader();
return;
}
updateData(data0);
updateData(data1);
updateData(data2);
updateData(data3);
updateData(data4);
updateData(data5);
}
void updateData(PropertyData data)
{
if (!data.isActive) return;
if (mat == null) return;
switch (data.type)
{
case shaderPropertyType.Color:
mat.SetColor(data.propName, data.colorValue);
break;
case shaderPropertyType.Vector:
case shaderPropertyType.TexEnv:
mat.SetVector(data.propName, data.vecValue);
break;
case shaderPropertyType.Float:
case shaderPropertyType.Range:
mat.SetFloat(data.propName, data.floatValue);
break;
}
}
//实际上是修改了graphic.materialForRendering
public Material GetModifiedMaterial(Material baseMaterial)
{
if (mat)
{
return mat;
}
else
{
return baseMaterial;
}
}
#if UNITY_EDITOR
private void OnRenderObject()
{
if (!UnityEditor.EditorApplication.isPlaying)
{
Update();
}
}
public void addProperteData()
{
refreshShderPropNameList();
if (!data0.isActive)
{
initData(ref data0, 0);
}
else if (!data1.isActive)
{
initData(ref data1, 1);
}
else if (!data2.isActive)
{
initData(ref data2, 2);
}
else if (!data3.isActive)
{
initData(ref data3, 3);
}
else if (!data4.isActive)
{
initData(ref data4, 4);
}
else if (!data5.isActive)
{
initData(ref data5, 5);
}
else
{
Debug.Log("已用掉可用的6个属性");
}
}
public void removeAllProperty()
{
data0.isActive = false;
data1.isActive = false;
data2.isActive = false;
data3.isActive = false;
data4.isActive = false;
data5.isActive = false;
}
public void initData(ref PropertyData data, int dataIndexInAgent)
{
data.dataIndexInAgent = dataIndexInAgent;
data.agent = this;
data.shader = shader;
data.mat = mat;
data.isActive = true;
data.index = getCanUsedIndex();
data.setValueByPropChange();
}
#region TODO自动排除已用Property
List<string> usedPropertyName = new List<string>();
void collectUsedPropName()
{
usedPropertyName.Clear();
if (data0.isActive)
{
usedPropertyName.Add(data0.propName);
}
if (data1.isActive)
{
usedPropertyName.Add(data1.propName);
}
if (data2.isActive)
{
usedPropertyName.Add(data2.propName);
}
if (data3.isActive)
{
usedPropertyName.Add(data3.propName);
}
if (data4.isActive)
{
usedPropertyName.Add(data4.propName);
}
if (data5.isActive)
{
usedPropertyName.Add(data5.propName);
}
}
public int getCanUsedIndex()
{
int index = -1;
collectUsedPropName();
for (int i = 0; i < shaderPropNameArr.Length; i++)
{
string propertyName;
if (UnityEditor.ShaderUtil.GetPropertyType(shader, i) ==
UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv)
{
propertyName = shaderPropNameArr[i] + "_ST";
}
else
{
propertyName = shaderPropNameArr[i];
}
if (usedPropertyName.Contains(propertyName)) continue;
index = i;
break;
}
return index;
}
public bool isCanUsedIndex(int i)
{
string propertyName;
if (UnityEditor.ShaderUtil.GetPropertyType(shader, i) == UnityEditor.ShaderUtil.ShaderPropertyType.TexEnv)
{
propertyName = shaderPropNameArr[i] + "_ST";
}
else
{
propertyName = shaderPropNameArr[i];
}
collectUsedPropName();
if (usedPropertyName.Contains(propertyName))
{
return false;
}
else
{
return true;
}
}
#endregion
public string[] shaderPropNameArr;
public string[] shaderPropDescripArr;
public string[] shaderPropDescripsForSerch;
private void OnValidate()
{
// if (XLuaManager.Instance != null)
// {
// if (XLuaManager.Instance.HasGameStart)//判断是游戏运行状态才进行实例化
// {
// return;//游戏进行中不允许编辑
// }
// }
// Debug.Log("MaterialPropertyAgent : " + "OnValidate");
refreshShderPropNameList();
if (TryGetComponent<Renderer>(out Renderer r) || customRenderer)
{
isRendererMode = true;
}
else
{
isRendererMode = false;
}
if (TryGetComponent<Renderer>(out Renderer r2) || TryGetComponent<Graphic>(out Graphic g))
{
isGetByComponet = true;
}
else
{
isGetByComponet = false;
}
}
public bool isRendererMode = false;
public bool isGetByComponet = false;
public void initMatAndShaderByMaterialIndexChange()
{
initMatAndShader(true);
refreshShderPropNameList();
if (data0.isActive && data0.shader != mat.shader)
{
data0.shader = mat.shader;
data0.mat = mat;
}
if (data1.isActive && data1.shader != mat.shader)
{
data1.shader = mat.shader;
data1.mat = mat;
}
if (data2.isActive && data2.shader != mat.shader)
{
data2.shader = mat.shader;
data2.mat = mat;
}
if (data3.isActive && data3.shader != mat.shader)
{
data3.shader = mat.shader;
data3.mat = mat;
}
if (data4.isActive && data4.shader != mat.shader)
{
data4.shader = mat.shader;
data4.mat = mat;
}
if (data5.isActive && data5.shader != mat.shader)
{
data5.shader = mat.shader;
data5.mat = mat;
}
}
List<string> shaderPropNameList = new List<string>();
private List<string> shaderPropDescripList = new List<string>();
private List<string> shaderPropDescripListForSerch = new List<string>();
public void refreshShderPropNameList()
{
initMatAndShader();
if (shader == null) return;
shaderPropNameList.Clear();
shaderPropDescripList.Clear();
shaderPropDescripListForSerch.Clear();
for (int i = 0; i < UnityEditor.ShaderUtil.GetPropertyCount(shader); i++)
{
shaderPropNameList.Add(UnityEditor.ShaderUtil.GetPropertyName(shader, i));
string descript = UnityEditor.ShaderUtil.GetPropertyDescription(shader, i);
shaderPropDescripList.Add(descript);
string lowerDesc = descript.ToLower();
if (!(lowerDesc.Contains("ignore") || lowerDesc.Contains("mode") || lowerDesc.Contains("toggle") ||
lowerDesc.Contains("enable") || lowerDesc.Contains("flag")))
{
shaderPropDescripListForSerch.Add(descript);
}
}
shaderPropNameArr = shaderPropNameList.ToArray();
shaderPropDescripArr = shaderPropDescripList.ToArray();
shaderPropDescripsForSerch = shaderPropDescripListForSerch.ToArray();
}
#endif
}
/*
[CustomPropertyDrawer(typeof(MaterialPropertyAgent.PropertyData))]
public class PropertyAgentPropertyDataDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
var isActive = property.FindPropertyRelative("isActive");
if (isActive.boolValue)
{
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
var index = property.FindPropertyRelative("index");
MaterialPropertyAgent agent = property.FindPropertyRelative("agent").objectReferenceValue as MaterialPropertyAgent;
int preservedIndex = index.intValue;
float originLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 80;
index.intValue = EditorGUILayout.Popup("属性名:", index.intValue, agent.shaderPropNameArr);
if (preservedIndex != index.intValue)//证明用户进行了更改
{
if (!agent.isCanUsedIndex(index.intValue))
{
//TODO给一个报错提示
Debug.Log(ShaderUtil.GetPropertyDescription(agent.shader, index.intValue));
index.intValue = agent.getCanUsedIndex();
}
//此处进行内容刷新
data.setValueByPropChange();
}
EditorGUILayout.LabelField("属性类型:", data.type.ToString());
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = originLabelWidth;
switch (data.type)
{
case MaterialPropertyAgent.shaderPropertyType.Color:
data.colorValue = EditorGUILayout.ColorField(data.descripName + " :", data.colorValue);
break;
case MaterialPropertyAgent.shaderPropertyType.Vector:
data.vecValue = EditorGUILayout.Vector4Field(data.descripName + " :", data.vecValue);
break;
case MaterialPropertyAgent.shaderPropertyType.Float:
data.floatValue = EditorGUILayout.FloatField(data.descripName + ":", data.floatValue);
break;
case MaterialPropertyAgent.shaderPropertyType.Range:
data.floatValue = EditorGUILayout.Slider(data.descripName + ":", data.floatValue, data.rangMin, data.rangMax);
break;
case MaterialPropertyAgent.shaderPropertyType.TexEnv:
data.vecValue = EditorGUILayout.Vector4Field(data.propName + "_ST:", data.vecValue);
break;
}
if (GUILayout.Button("删除", new[] { GUILayout.Width(200) }))
{
data.isActive = false;
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
}
EditorGUI.EndProperty();
}
}
*/
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 781e80efab11a1d438f7c4d37603bdff
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,89 @@
using System;
using UnityEngine;
namespace NBShader
{
public abstract class ShaderFlagsBase
{
private Material _material;
public Material material
{
get { return _material; }
}
protected ShaderFlagsBase(Material material)
{
_material = material;
}
public void SetMaterial(Material material)
{
_material = material;
}
public Material GetMaterial()
{
return _material;
}
public abstract int GetShaderFlagsId(int index = 0);
protected abstract string GetShaderFlagsName(int index = 0);
private void SetIntValue(Material material, int flagBits, int index = 0)
{
#if UNITY_EDITOR
material.SetInteger(GetShaderFlagsId(index), flagBits);
#else
material.SetInteger(GetShaderFlagsId(index), flagBits);
#endif
}
public void SetFlagBits(int flagBits, MaterialPropertyBlock propertyBlock = null, int index = 0)
{
if (propertyBlock is null)
{
if (_material is null) return;
int flags = _material.GetInteger(GetShaderFlagsId(index));
SetIntValue(_material, flags | flagBits, index);
}
else
{
int flags = propertyBlock.GetInt(GetShaderFlagsId(index));
propertyBlock.SetInt(GetShaderFlagsId(index), flags | flagBits);
}
}
public void ClearFlagBits(int flagBits, MaterialPropertyBlock propertyBlock = null, int index = 0)
{
if (propertyBlock is null)
{
if (_material is null) return;
int flags = _material.GetInteger(GetShaderFlagsId(index));
SetIntValue(_material, flags & ~flagBits, index);
}
else
{
int flags = propertyBlock.GetInteger(GetShaderFlagsId(index));
propertyBlock.SetInteger(GetShaderFlagsId(index), flags & ~flagBits);
}
}
public bool CheckFlagBits(int flagBits, MaterialPropertyBlock propertyBlock = null, int index = 0)
{
int flags = 0;
if (propertyBlock is null)
{
if (_material is null) throw new NullReferenceException("material");
flags = _material.GetInteger(GetShaderFlagsId(index));
}
else
{
flags = propertyBlock.GetInteger(GetShaderFlagsId(index));
}
return (flags & flagBits) != 0;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3bcf591e67bd470e9375d72c63838643
timeCreated: 1655437380
@@ -0,0 +1,16 @@
{
"name": "com.xuanxuan.render.utility",
"rootNamespace": "",
"references": [
"GUID:15fc0a57446b3144c949da3e2b9737a9"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8f9e4d586616f13449cfeb86c5f704c2
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 97647516635f92f43a6cd4807c3899d8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fa89a0fdb680e154f89c18f1a7fea2c6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,391 @@
#ifndef XUANXUAN_UTILITY
#define XUANXUAN_UTILITY
//引入自UnityCG.cginc
#define UNITY_PI 3.14159265359f
#define UNITY_TWO_PI 6.28318530718f
#define UNITY_FOUR_PI 12.56637061436f
#define UNITY_INV_PI 0.31830988618f
#define UNITY_INV_TWO_PI 0.15915494309f
#define UNITY_INV_FOUR_PI 0.07957747155f
#define UNITY_HALF_PI 1.57079632679f
#define UNITY_INV_HALF_PI 0.636619772367f
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
inline half NB_Remap(half x, half inMin, half inMax, half outMin, half outMax)
{
// x= clamp(x,inMin,inMax);
return saturate((x - inMin) / (inMax - inMin)) * (outMax - outMin) + outMin;
}
inline half NB_Remap01(half x, half inMin, half inMax)
{
// x= clamp(x,inMin,inMax);
return saturate((x - inMin) / (inMax - inMin));
}
inline half NB_RemapNoClamp(half x, half inMin, half inMax, half outMin, half outMax)
{
// x= clamp(x,inMin,inMax);
return ((x - inMin) / (inMax - inMin)) * (outMax - outMin) + outMin;
}
//原生SmoothStep开销很大:https://zhuanlan.zhihu.com/p/34629262
//在很多时候可以用简单线性映射代替。
half SimpleSmoothstep(half min,half max,half interp)
{
return saturate((interp - min)/(max-min));
}
half4 TryLinearize(half4 color)
{
#if defined(UNITY_COLORSPACE_GAMMA)
return pow(color, 2.2f);
#else
return color;
#endif
}
half4 TryLinearizeWithoutAlpha(half4 color)
{
#if defined(UNITY_COLORSPACE_GAMMA)
return half4(pow(color.rgb, 2.2f), color.a);
#else
return color;
#endif
}
half3 TryLinearize(half3 color)
{
#if defined(UNITY_COLORSPACE_GAMMA)
return pow(color, 2.2f);
#else
return color;
#endif
}
half2 TryLinearize(half2 color)
{
#if defined(UNITY_COLORSPACE_GAMMA)
return pow(color, 2.2f);
#else
return color;
#endif
}
half TryLinearize(half color)
{
#if defined(UNITY_COLORSPACE_GAMMA)
return pow(color, 2.2f);
#else
return color;
#endif
}
half4 tex2D_TryLinearizeWithoutAlpha(sampler2D tex, float2 uv)
{
#if defined(UNITY_COLORSPACE_GAMMA)
return TryLinearizeWithoutAlpha(tex2D(tex, uv));
#else
return tex2D(tex, uv);
#endif
}
inline float LinearToGammaSpaceExact (float value)
{
if (value <= 0.0F)
return 0.0F;
else if (value <= 0.0031308F)
return 12.92F * value;
else if (value < 1.0F)
return 1.055F * pow(value, 0.4166667F) - 0.055F;
else
return pow(value, 0.45454545F);
}
// real FastSRGBToLinear(real c)
// {
// return c * (c * (c * 0.305306011 + 0.682171111) + 0.012522878);
// }
// float2 Rotate_Radians_float(float2 UV, float2 Center, float Rotation)
// {
// if(Rotation == 0)
// {
// return UV;
// }
//
// // Rotation = Rotation / 180 * 3.14; //从角度转为弧度。
// Rotation *= 0.01745329222; //从角度转为弧度。
// UV -= Center;
// float s = sin(Rotation);
// float c = cos(Rotation);
// float2x2 rMatrix = float2x2(c, -s, s, c);
// rMatrix *= 0.5;
// rMatrix += 0.5;
// rMatrix = rMatrix * 2 - 1;
// UV.xy = mul(UV.xy, rMatrix);
// UV += Center;
// return UV;
// }
float2 Rotate_Radians_float(float2 UV, float2 Center, float Rotation)
{
if(Rotation == 0)
{
return UV;
}
// Rotation = Rotation / 180 * 3.14; //从角度转为弧度。
Rotation *= 0.01745329222; //从角度转为弧度。
float s, c; // 如果 angle 是 uniform,每帧或每物件算一次更省
sincos(Rotation, s, c); // HLSL 内置,一次算出 sin/cos
float2 d = UV - Center;
// 旋转 (x', y') = ( c*x - s*y, s*x + c*y )
float2 r = float2(dot(d, float2( c, -s)),
dot(d, float2( s, c)));
return r + Center;
}
inline half luminance(half3 color)
{
return dot(color, float3(0.2126f, 0.7152f, 0.0722f));
}
inline half DepthFactor(float Z, float near, float far)
{
Z = saturate((Z-near)/(far - near));
return Z;
}
//抽自Unity.cginc
inline half3 LinearToGammaSpace (half3 linRGB)
{
linRGB = max(linRGB, half3(0.h, 0.h, 0.h));
// An almost-perfect approximation from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1
return max(1.055h * pow(linRGB, 0.416666667h) - 0.055h, 0.h);
// Exact version, useful for debugging.
//return half3(LinearToGammaSpaceExact(linRGB.r), LinearToGammaSpaceExact(linRGB.g), LinearToGammaSpaceExact(linRGB.b));
}
//ASE
float2 voronoihash1( float2 p )
{
p = float2( dot( p, float2( 127.1, 311.7 ) ), dot( p, float2( 269.5, 183.3 ) ) );
return frac( sin( p ) *43758.5453);
}
//ASE
float voronoi1( float2 v, float time, inout float2 id, inout float2 mr, float smoothness )
{
float2 n = floor( v );
float2 f = frac( v );
float F1 = 8.0;
float F2 = 8.0; float2 mg = 0;
for ( int j = -1; j <= 1; j++ )
{
for ( int i = -1; i <= 1; i++ )
{
float2 g = float2( i, j );
float2 o = voronoihash1( n + g );
o = ( sin( time + o * 6.2831 ) * 0.5 + 0.5 ); float2 r = f - g - o;
float d = 0.5 * dot( r, r );
if( d<F1 ) {
F2 = F1;
F1 = d; mg = g; mr = r; id = o;
} else if( d<F2 ) {
F2 = d;
}
}
}
return F2 - F1;
}
void voroniForgraphfunc_half(half2 uv,half angle,half scale,out float outVoroni1 )
{
uv = uv*scale;
float2 id1 = 0;
float2 uv1 = 0;
outVoroni1 = voronoi1( uv, angle, id1, uv1, 0 );
}
inline float2 unity_voronoi_noise_randomVector (float2 UV, float offset)
{
float2x2 m = float2x2(15.27, 47.63, 99.41, 89.98);
UV = frac(sin(mul(UV, m)) * 46839.32);
return float2(sin(UV.y*+offset)*0.5+0.5, cos(UV.x*offset)*0.5+0.5);
}
void Unity_Voronoi_float(float2 UV, float AngleOffset, float CellDensity, out float Out, out float Cells)
{
float2 g = floor(UV * CellDensity);
float2 f = frac(UV * CellDensity);
float t = 8.0;
float3 res = float3(8.0, 0.0, 0.0);
for(int y=-1; y<=1; y++)
{
for(int x=-1; x<=1; x++)
{
float2 lattice = float2(x,y);
float2 offset = unity_voronoi_noise_randomVector(lattice + g, AngleOffset);
float d = distance(lattice + offset, f);
if(d < res.x)
{
res = float3(d, offset.x, offset.y);
Out = res.x;
Cells = res.y;
}
}
}
}
void Unity_Blend_Overlay_float4(float4 Base, float4 Blend, float Opacity, out float4 Out)
{
float4 result1 = 1.0 - 2.0 * (1.0 - Base) * (1.0 - Blend);
float4 result2 = 2.0 * Base * Blend;
float4 zeroOrOne = step(Base, 0.5);
Out = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
Out = lerp(Base, Out, Opacity);
}
void Unity_Blend_HardLight_half(half Base, half Blend, half Opacity, out half Out)
{
half result1 = 1.0 - 2.0 * (1.0 - Base) * (1.0 - Blend);
half result2 = 2.0 * Base * Blend;
half zeroOrOne = step(Blend, 0.5);
Out = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
Out = lerp(Base, Out, Opacity);
}
void Blend_HardLight_half(half Base, half Blend, out half Out)
{
half result1 = 1.0 - 2.0 * (1.0 - Base) * (1.0 - Blend);
half result2 = 2.0 * Base * Blend;
half zeroOrOne = step(Blend, 0.5);
Out = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
}
float2 randomGradient(float2 p) {
p = p + 0.02;
float x = dot(p, float2(123.4, 234.5));
float y = dot(p, float2(234.5, 345.6));
float2 gradient = float2(x, y);
gradient = sin(gradient);
gradient = gradient * 43758.5453;
// part 4.5 - update noise function with time
// gradient = sin(gradient + u_time);
return gradient;
// gradient = sin(gradient);
// return gradient;
}
#include "./jp.keijiro.noiseshader/Shader/SimplexNoise3D.hlsl"
half SimplexNoise(float2 uv,float time)
{
return SimplexNoise(float3(uv,time))*0.5+0.5;
}
#include "./jp.keijiro.noiseshader/Shader/ClassicNoise3D.hlsl"
half PerlinNoise(float2 uv,float time)
{
return ClassicNoise(float3(uv,time))*0.5+0.5;
}
float2 PolarCoordinates(float2 UV, float2 _PCCenter)
{
// float2 uvsource = float2(0, 0);
float2 delta = UV - _PCCenter.xy;//校准UV到中心
float radius = length(delta) * 2;
float angle = atan2(delta.x, delta.y) * UNITY_INV_TWO_PI ;
return float2(angle, radius);//翻转可以调整横向和纵向。
}
float2 PolarCoordinatesStrengthAndST(float2 UVBeforPollarCoord,float2 UVAfterPolarCoord,float polarStrenth ,float4 tex_ST)
{
UVAfterPolarCoord = UVAfterPolarCoord*tex_ST.xy + tex_ST.zw;//利用相应功能贴图的坐标对ST进行修改。
UVAfterPolarCoord = lerp(UVBeforPollarCoord, UVAfterPolarCoord, polarStrenth);
return UVAfterPolarCoord;
}
//极坐标//transformation为极坐标强度
float2 PolarCoordinates(float2 UV, float3 _PCCenter, float4 tex_ST)
{
// float2 uvsource = float2(0, 0);
//
// float2 delta = UV - _PCCenter.xy;//校准UV到中心
// float radius = length(delta) * 2;
// float angle = atan2(delta.x, delta.y) * UNITY_INV_TWO_PI ;
// uvsource = float2(angle, radius);//翻转可以调整横向和纵向。
// uvsource = uvsource*tex_ST.xy + tex_ST.zw;//利用相应功能贴图的坐标对ST进行修改。
// uvsource = lerp(UV, uvsource, _PCCenter.z);
// return uvsource;
//拆分成两步,第一步求极坐标太耗(atan),一般源UV都是一样的,只是ST不同。
float2 uvsource = PolarCoordinates(UV,_PCCenter.xy);
uvsource = PolarCoordinatesStrengthAndST(UV,uvsource,_PCCenter.z,tex_ST);
return uvsource;
}
float2 CylinderCoordinate(float3 positionOS)
{
float angle = atan2(positionOS.x,positionOS.z)* UNITY_INV_TWO_PI ;
return float2(angle,positionOS.y);
}
float2 UVOffsetAnimaiton(float2 UV,half2 OffsetSpeed,float time)
{
float2 newUV = float2(OffsetSpeed.x*time+UV.x,OffsetSpeed.y*time+UV.y);
return newUV;
}
half3 rgb2hsv(half3 c)
{
half4 K = half4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
half4 p = lerp(half4(c.bg, K.wz), half4(c.gb, K.xy), step(c.b, c.g));
half4 q = lerp(half4(p.xyw, c.r), half4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
half3 hsv2rgb(half3 c)
{
half4 K = half4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
half3 p = abs(frac(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * lerp(K.xxx, saturate(p - K.xxx), c.y);
}
half3 ColorSaturate(half3 color, half colorSaturation)
{
half3 lum = luminance(color);
return max(0, lerp(lum, color, colorSaturation));
}
half2 Rotate(half2 v, half cos0, half sin0)
{
return half2(v.x * cos0 - v.y * sin0,
v.x * sin0 + v.y * cos0);
}
half SmoothStep01(half interval)//让01线性过渡变成SmoothStep过渡,但是控制计算量。
{
interval = saturate(interval);
return interval * interval * ( 3 - 2 * interval );
}
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9f34986983f558c40a7e30a353dc3c34
timeCreated: 1684725413
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e95a8f1b5d23f4141b5121f98f90f10a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,56 @@
Noise Shader Library for Unity
==============================
**NoiseShader** is a Unity package that provides 2D/3D gradient noise
functions written in the shader language. These functions are ported from the
[webgl-noise] library that is originally written by Stefan Gustavson and Ahima
Arts.
[webgl-noise]: https://github.com/ashima/webgl-noise
At the moment, it contains the following functions:
- Classic Perlin noise (2D/3D)
- Periodic Perlin noise (2D/3D)
- Simplex noise (2D/3D)
- Analytical derivatives of simplex noise (2D/3D)
How To Install
--------------
This package uses the [scoped registry] feature to resolve package dependencies.
Please add the following sections to the manifest file (Packages/manifest.json).
[scoped registry]: https://docs.unity3d.com/Manual/upm-scoped.html
To the `scopedRegistries` section:
```
{
"name": "Keijiro",
"url": "https://registry.npmjs.com",
"scopes": [ "jp.keijiro" ]
}
```
To the `dependencies` section:
```
"jp.keijiro.noiseshader": "2.0.0"
```
After changes, the manifest file should look like below:
```
{
"scopedRegistries": [
{
"name": "Keijiro",
"url": "https://registry.npmjs.com",
"scopes": [ "jp.keijiro" ]
}
],
"dependencies": {
"jp.keijiro.noiseshader": "2.0.0",
...
```
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b92baefe22663afa5ad0ab303b3dcc20
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 77b21af505211947eb730e678820eb8b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,66 @@
//
// GLSL textureless classic 2D noise "cnoise",
// with an RSL-style periodic variant "pnoise".
// Author: Stefan Gustavson (stefan.gustavson@liu.se)
// Version: 2011-08-22
//
// Many thanks to Ian McEwan of Ashima Arts for the
// ideas for permutation and gradient selection.
//
// Copyright (c) 2011 Stefan Gustavson. All rights reserved.
// Distributed under the MIT license. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
#ifndef _INCLUDE_JP_KEIJIRO_NOISESHADER_CLASSIC_NOISE_2D_HLSL_
#define _INCLUDE_JP_KEIJIRO_NOISESHADER_CLASSIC_NOISE_2D_HLSL_
#include "Common.hlsl"
float ClassicNoise_impl(float2 pi0, float2 pf0, float2 pi1, float2 pf1)
{
pi0 = wglnoise_mod289(pi0); // To avoid truncation effects in permutation
pi1 = wglnoise_mod289(pi1);
float4 ix = float2(pi0.x, pi1.x).xyxy;
float4 iy = float2(pi0.y, pi1.y).xxyy;
float4 fx = float2(pf0.x, pf1.x).xyxy;
float4 fy = float2(pf0.y, pf1.y).xxyy;
float4 i = wglnoise_permute(wglnoise_permute(ix) + iy);
float4 phi = i / 41 * 3.14159265359 * 2;
float2 g00 = float2(cos(phi.x), sin(phi.x));
float2 g10 = float2(cos(phi.y), sin(phi.y));
float2 g01 = float2(cos(phi.z), sin(phi.z));
float2 g11 = float2(cos(phi.w), sin(phi.w));
float n00 = dot(g00, float2(fx.x, fy.x));
float n10 = dot(g10, float2(fx.y, fy.y));
float n01 = dot(g01, float2(fx.z, fy.z));
float n11 = dot(g11, float2(fx.w, fy.w));
float2 fade_xy = wglnoise_fade(pf0);
float2 n_x = lerp(float2(n00, n01), float2(n10, n11), fade_xy.x);
float n_xy = lerp(n_x.x, n_x.y, fade_xy.y);
return 1.44 * n_xy;
}
// Classic Perlin noise
float ClassicNoise(float2 p)
{
float2 i = floor(p);
float2 f = frac(p);
return ClassicNoise_impl(i, f, i + 1, f - 1);
}
// Classic Perlin noise, periodic variant
float PeriodicNoise(float2 p, float2 rep)
{
float2 i0 = wglnoise_mod(floor(p), rep);
float2 i1 = wglnoise_mod(i0 + 1, rep);
float2 f = frac(p);
return ClassicNoise_impl(i0, f, i1, f - 1);
}
#endif
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 8ec48974b9689234f9a4a7c1927e2a7b
timeCreated: 1498976326
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,93 @@
//
// GLSL textureless classic 3D noise "cnoise",
// with an RSL-style periodic variant "pnoise".
// Author: Stefan Gustavson (stefan.gustavson@liu.se)
// Version: 2011-10-11
//
// Many thanks to Ian McEwan of Ashima Arts for the
// ideas for permutation and gradient selection.
//
// Copyright (c) 2011 Stefan Gustavson. All rights reserved.
// Distributed under the MIT license. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
#ifndef _INCLUDE_JP_KEIJIRO_NOISESHADER_CLASSIC_NOISE_3D_HLSL_
#define _INCLUDE_JP_KEIJIRO_NOISESHADER_CLASSIC_NOISE_3D_HLSL_
#include "Common.hlsl"
float ClassicNoise_impl(float3 pi0, float3 pf0, float3 pi1, float3 pf1)
{
pi0 = wglnoise_mod289(pi0);
pi1 = wglnoise_mod289(pi1);
float4 ix = float4(pi0.x, pi1.x, pi0.x, pi1.x);
float4 iy = float4(pi0.y, pi0.y, pi1.y, pi1.y);
float4 iz0 = pi0.z;
float4 iz1 = pi1.z;
float4 ixy = wglnoise_permute(wglnoise_permute(ix) + iy);
float4 ixy0 = wglnoise_permute(ixy + iz0);
float4 ixy1 = wglnoise_permute(ixy + iz1);
float4 gx0 = lerp(-1, 1, frac(floor(ixy0 / 7) / 7));
float4 gy0 = lerp(-1, 1, frac(floor(ixy0 % 7) / 7));
float4 gz0 = 1 - abs(gx0) - abs(gy0);
bool4 zn0 = gz0 < -0.01;
gx0 += zn0 * (gx0 < -0.01 ? 1 : -1);
gy0 += zn0 * (gy0 < -0.01 ? 1 : -1);
float4 gx1 = lerp(-1, 1, frac(floor(ixy1 / 7) / 7));
float4 gy1 = lerp(-1, 1, frac(floor(ixy1 % 7) / 7));
float4 gz1 = 1 - abs(gx1) - abs(gy1);
bool4 zn1 = gz1 < -0.01;
gx1 += zn1 * (gx1 < -0.01 ? 1 : -1);
gy1 += zn1 * (gy1 < -0.01 ? 1 : -1);
float3 g000 = normalize(float3(gx0.x, gy0.x, gz0.x));
float3 g100 = normalize(float3(gx0.y, gy0.y, gz0.y));
float3 g010 = normalize(float3(gx0.z, gy0.z, gz0.z));
float3 g110 = normalize(float3(gx0.w, gy0.w, gz0.w));
float3 g001 = normalize(float3(gx1.x, gy1.x, gz1.x));
float3 g101 = normalize(float3(gx1.y, gy1.y, gz1.y));
float3 g011 = normalize(float3(gx1.z, gy1.z, gz1.z));
float3 g111 = normalize(float3(gx1.w, gy1.w, gz1.w));
float n000 = dot(g000, pf0);
float n100 = dot(g100, float3(pf1.x, pf0.y, pf0.z));
float n010 = dot(g010, float3(pf0.x, pf1.y, pf0.z));
float n110 = dot(g110, float3(pf1.x, pf1.y, pf0.z));
float n001 = dot(g001, float3(pf0.x, pf0.y, pf1.z));
float n101 = dot(g101, float3(pf1.x, pf0.y, pf1.z));
float n011 = dot(g011, float3(pf0.x, pf1.y, pf1.z));
float n111 = dot(g111, pf1);
float3 fade_xyz = wglnoise_fade(pf0);
float4 n_z = lerp(float4(n000, n100, n010, n110),
float4(n001, n101, n011, n111), fade_xyz.z);
float2 n_yz = lerp(n_z.xy, n_z.zw, fade_xyz.y);
float n_xyz = lerp(n_yz.x, n_yz.y, fade_xyz.x);
return 1.46 * n_xyz;
}
// Classic Perlin noise
float ClassicNoise(float3 p)
{
float3 i = floor(p);
float3 f = frac(p);
return ClassicNoise_impl(i, f, i + 1, f - 1);
}
// Classic Perlin noise, periodic variant
float PeriodicNoise(float3 p, float3 rep)
{
float3 i0 = wglnoise_mod(floor(p), rep);
float3 i1 = wglnoise_mod(i0 + 1, rep);
float3 f = frac(p);
return ClassicNoise_impl(i0, f, i1, f - 1);
}
#endif
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 2688615dc3cd4ed4cbca4cd0135d8e8a
timeCreated: 1498976326
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,64 @@
#ifndef _INCLUDE_JP_KEIJIRO_NOISESHADER_COMMON_HLSL_
#define _INCLUDE_JP_KEIJIRO_NOISESHADER_COMMON_HLSL_
float wglnoise_mod(float x, float y)
{
return x - y * floor(x / y);
}
float2 wglnoise_mod(float2 x, float2 y)
{
return x - y * floor(x / y);
}
float3 wglnoise_mod(float3 x, float3 y)
{
return x - y * floor(x / y);
}
float4 wglnoise_mod(float4 x, float4 y)
{
return x - y * floor(x / y);
}
float2 wglnoise_fade(float2 t)
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
float3 wglnoise_fade(float3 t)
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
float wglnoise_mod289(float x)
{
return x - floor(x / 289) * 289;
}
float2 wglnoise_mod289(float2 x)
{
return x - floor(x / 289) * 289;
}
float3 wglnoise_mod289(float3 x)
{
return x - floor(x / 289) * 289;
}
float4 wglnoise_mod289(float4 x)
{
return x - floor(x / 289) * 289;
}
float3 wglnoise_permute(float3 x)
{
return wglnoise_mod289((x * 34 + 1) * x);
}
float4 wglnoise_permute(float4 x)
{
return wglnoise_mod289((x * 34 + 1) * x);
}
#endif
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 443fb5ca2e0ec42bc8a96eb43c8470fe
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,63 @@
//
// Description : Array and textureless GLSL 2D simplex noise function.
// Author : Ian McEwan, Ashima Arts.
// Maintainer : ijm
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 Ashima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
#ifndef _INCLUDE_JP_KEIJIRO_NOISESHADER_SIMPLEX_NOISE_2D_HLSL_
#define _INCLUDE_JP_KEIJIRO_NOISESHADER_SIMPLEX_NOISE_2D_HLSL_
#include "Common.hlsl"
float3 SimplexNoiseGrad(float2 v)
{
const float C1 = (3 - sqrt(3)) / 6;
const float C2 = (sqrt(3) - 1) / 2;
// First corner
float2 i = floor(v + dot(v, C2));
float2 x0 = v - i + dot(i, C1);
// Other corners
float2 i1 = x0.x > x0.y ? float2(1, 0) : float2(0, 1);
float2 x1 = x0 + C1 - i1;
float2 x2 = x0 + C1 * 2 - 1;
// Permutations
i = wglnoise_mod289(i); // Avoid truncation effects in permutation
float3 p = wglnoise_permute( i.y + float3(0, i1.y, 1));
p = wglnoise_permute(p + i.x + float3(0, i1.x, 1));
// Gradients: 41 points uniformly over a unit circle.
// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
float3 phi = p / 41 * 3.14159265359 * 2;
float2 g0 = float2(cos(phi.x), sin(phi.x));
float2 g1 = float2(cos(phi.y), sin(phi.y));
float2 g2 = float2(cos(phi.z), sin(phi.z));
// Compute noise and gradient at P
float3 m = float3(dot(x0, x0), dot(x1, x1), dot(x2, x2));
float3 px = float3(dot(g0, x0), dot(g1, x1), dot(g2, x2));
m = max(0.5 - m, 0);
float3 m3 = m * m * m;
float3 m4 = m * m3;
float3 temp = -8 * m3 * px;
float2 grad = m4.x * g0 + temp.x * x0 +
m4.y * g1 + temp.y * x1 +
m4.z * g2 + temp.z * x2;
return 99.2 * float3(grad, dot(m4, px));
}
float SimplexNoise(float2 v)
{
return SimplexNoiseGrad(v).z;
}
#endif
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 66b8605d5d2f14d408b0f4aee5f9d25a
timeCreated: 1498976326
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,76 @@
//
// Description : Array and textureless GLSL 2D/3D/4D simplex
// noise functions.
// Author : Ian McEwan, Ashima Arts.
// Maintainer : ijm
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 Ashima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
#ifndef _INCLUDE_JP_KEIJIRO_NOISESHADER_SIMPLEX_NOISE_3D_HLSL_
#define _INCLUDE_JP_KEIJIRO_NOISESHADER_SIMPLEX_NOISE_3D_HLSL_
#include "Common.hlsl"
float4 SimplexNoiseGrad(float3 v)
{
// First corner
float3 i = floor(v + dot(v, 1.0 / 3));
float3 x0 = v - i + dot(i, 1.0 / 6);
// Other corners
float3 g = x0.yzx <= x0.xyz;
float3 l = 1 - g;
float3 i1 = min(g.xyz, l.zxy);
float3 i2 = max(g.xyz, l.zxy);
float3 x1 = x0 - i1 + 1.0 / 6;
float3 x2 = x0 - i2 + 1.0 / 3;
float3 x3 = x0 - 0.5;
// Permutations
i = wglnoise_mod289(i); // Avoid truncation effects in permutation
float4 p = wglnoise_permute( i.z + float4(0, i1.z, i2.z, 1));
p = wglnoise_permute(p + i.y + float4(0, i1.y, i2.y, 1));
p = wglnoise_permute(p + i.x + float4(0, i1.x, i2.x, 1));
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
float4 gx = lerp(-1, 1, frac(floor(p / 7) / 7));
float4 gy = lerp(-1, 1, frac(floor(p % 7) / 7));
float4 gz = 1 - abs(gx) - abs(gy);
bool4 zn = gz < -0.01;
gx += zn * (gx < -0.01 ? 1 : -1);
gy += zn * (gy < -0.01 ? 1 : -1);
float3 g0 = normalize(float3(gx.x, gy.x, gz.x));
float3 g1 = normalize(float3(gx.y, gy.y, gz.y));
float3 g2 = normalize(float3(gx.z, gy.z, gz.z));
float3 g3 = normalize(float3(gx.w, gy.w, gz.w));
// Compute noise and gradient at P
float4 m = float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3));
float4 px = float4(dot(g0, x0), dot(g1, x1), dot(g2, x2), dot(g3, x3));
m = max(0.5 - m, 0);
float4 m3 = m * m * m;
float4 m4 = m * m3;
float4 temp = -8 * m3 * px;
float3 grad = m4.x * g0 + temp.x * x0 +
m4.y * g1 + temp.y * x1 +
m4.z * g2 + temp.z * x2 +
m4.w * g3 + temp.w * x3;
return 107 * float4(grad, dot(m4, px));
}
float SimplexNoise(float3 v)
{
return SimplexNoiseGrad(v).w;
}
#endif
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 2b1bb9b67aabb824998a7d2e026d2606
timeCreated: 1498976326
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
{
"author": "Keijiro Takahashi",
"description": "Noise Shader provides lightweight 2D/3D gradient noise functions for shader use.",
"displayName": "Noise Shader",
"keywords": [ "unity" ],
"license": "MIT",
"name": "jp.keijiro.noiseshader",
"repository": "github:keijiro/NoiseShader",
"unity": "2019.3",
"unityRelease": "0f1",
"version": "2.0.0"
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 39ccfaa9af9f4dc84a876b1b1c3ae8bb
PackageManifestImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: