浏览代码

Merge branch 'hackweek2017' of https://github.com/stramit/MaterialGraph into hackweek2017

/main
bfogerty 8 年前
当前提交
1f0971d6
共有 49 个文件被更改,包括 1850 次插入198 次删除
  1. 3
      .gitignore
  2. 2
      .gitmodules
  3. 2
      MaterialGraphProject/Assets/Eduardo/EduardoTestGraph.ShaderGraph
  4. 2
      MaterialGraphProject/Assets/Eduardo/FunctionNInNOut.cs
  5. 2
      MaterialGraphProject/Assets/Eduardo/HeightToNormalNode.cs
  6. 2
      MaterialGraphProject/Assets/GraphFramework/SerializableGraph/Editor/Drawing/Presenters/GraphNodePresenter.cs
  7. 98
      MaterialGraphProject/Assets/Matt/AbstractAdvancedMasterNode.cs
  8. 2
      MaterialGraphProject/Assets/Matt/AnisotropicMaster.ShaderGraph
  9. 12
      MaterialGraphProject/Assets/Matt/AnisotropicMetallicMasterNode.cs
  10. 2
      MaterialGraphProject/Assets/Matt/New Material.mat
  11. 14
      MaterialGraphProject/Assets/Rinaldo/BlendModeNode.cs
  12. 2
      MaterialGraphProject/Assets/Rinaldo/BlendModesEnum.cs
  13. 2
      MaterialGraphProject/Assets/Rinaldo/Editor/BlendModeNodePresenter.cs
  14. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/NodePreviewPresenter.cs
  15. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/TextureAssetPresenter.cs
  16. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/TextureLODNodePresenter.cs
  17. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/TextureNodePresenter.cs
  18. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/HelperShader.shader.meta
  19. 32
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/ExportTexture.template
  20. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/advancedSubshader.template
  21. 1
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/shader.template
  22. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/IntegrationTests/PropertyNodeTests.cs
  23. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/AbstractMaterialNode.cs
  24. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/SceneData/DepthTextureNode.cs
  25. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/SceneData/MotionVectorTextureNode.cs
  26. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/TextureLODNode.cs
  27. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/TextureNode.cs
  28. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/PreviewProperty.cs
  29. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/PropertyType.cs
  30. 61
      MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/ExportTextureMasterNode.cs
  31. 22
      MaterialGraphProject/Assets/Vlad/TextureAssetNode.cs
  32. 75
      MaterialGraphProject/Assets/Vlad/UVTriPlanar.cs
  33. 180
      MaterialGraphProject/ProjectSettings/ProjectSettings.asset
  34. 46
      MaterialGraphProject/Assets/Eduardo/ChannelBlendNode.cs
  35. 12
      MaterialGraphProject/Assets/Eduardo/ChannelBlendNode.cs.meta
  36. 20
      MaterialGraphProject/Assets/Eduardo/ReciprocalSqrtNode.cs
  37. 12
      MaterialGraphProject/Assets/Eduardo/ReciprocalSqrtNode.cs.meta
  38. 906
      MaterialGraphProject/Assets/GeneratedShader.shader
  39. 10
      MaterialGraphProject/Assets/GeneratedShader.shader.meta
  40. 1
      MaterialGraphProject/Assets/Matt/ClothMaster.ShaderGraph
  41. 9
      MaterialGraphProject/Assets/Matt/ClothMaster.ShaderGraph.meta
  42. 96
      MaterialGraphProject/Assets/Matt/ClothMasterNode.cs
  43. 12
      MaterialGraphProject/Assets/Matt/ClothMasterNode.cs.meta
  44. 1
      MaterialGraphProject/Assets/Matt/SubsurfaceMaster.ShaderGraph
  45. 9
      MaterialGraphProject/Assets/Matt/SubsurfaceMaster.ShaderGraph.meta
  46. 86
      MaterialGraphProject/Assets/Matt/SubsurfaceMetallicMasterNode.cs
  47. 12
      MaterialGraphProject/Assets/Matt/SubsurfaceMetallicMasterNode.cs.meta
  48. 202
      MaterialGraphProject/Assets/NewNodes/WIP/MultiLayerParallaxNode.cs
  49. 12
      MaterialGraphProject/Assets/NewNodes/WIP/MultiLayerParallaxNode.cs.meta

3
.gitignore


MaterialGraphProject/Temp
MaterialGraphProject/MaterialGraphProject.userprefs
MaterialGraphProject/.idea
MaterialGraphProject/Assets/Plugins/Editor/Rider
MaterialGraphProject/Assets/Plugins/Editor/Rider
.DS_Store

2
.gitmodules


[submodule "MaterialGraphProject/Assets/GraphView/Editor"]
path = MaterialGraphProject/Assets/GraphView/Editor
url = https://github.com/Unity-Technologies/GraphView.git
url = https://github.com/chikuba/GraphView.git

2
MaterialGraphProject/Assets/Eduardo/EduardoTestGraph.ShaderGraph
文件差异内容过多而无法显示
查看文件

2
MaterialGraphProject/Assets/Eduardo/FunctionNInNOut.cs


private string GetOutputDeclaration()
{
string outDeclaration = "";
foreach (ISlot outSlot in GetOutputSlots<ISlot>())
foreach (MaterialSlot outSlot in GetOutputSlots<MaterialSlot>())
{
outDeclaration += "\n " + precision + GetSlotTypeName(outSlot.id) + " " + GetVariableNameForSlot(outSlot.id) + ";\n";
}

2
MaterialGraphProject/Assets/Eduardo/HeightToNormalNode.cs


namespace UnityEngine.MaterialGraph
{
[Title("HeightToNormal")]
[Title("Utility/Heightmap To Normalmap")]
public class HeightToNormalNode : FunctionNInNOut, IGeneratesFunction
{

2
MaterialGraphProject/Assets/GraphFramework/SerializableGraph/Editor/Drawing/Presenters/GraphNodePresenter.cs


foreach (var slot in slots)
{
var data = CreateInstance<GraphAnchorPresenter>();
data.capabilities &= ~Capabilities.Movable;
if (slot.isOutputSlot)
{
outputAnchors.Add(data);

98
MaterialGraphProject/Assets/Matt/AbstractAdvancedMasterNode.cs


public abstract string GetSurfaceOutputName();
public abstract string GetLightFunction();
public abstract string GetMaterialID();
public abstract int[] GetCustomDataSlots();
public abstract string[] GetCustomData();
public override string GetSubShader(GenerationMode mode, PropertyGenerator shaderPropertiesVisitor)
{

(node as IGeneratesBodyCode).GenerateNodeCode(shaderBody, generationMode);
}
ListPool<INode>.Release(nodes);
foreach (var slot in GetInputSlots<MaterialSlot>())
{
if (!CheckForCustomData(slot.id)) // Check to ignore writing surface data for items getting packed into custom data
{
foreach (var edge in owner.GetEdges(slot.slotReference))
{
var outputRef = edge.outputSlot;
var fromNode = owner.GetNodeFromGuid<AbstractMaterialNode>(outputRef.nodeGuid);
if (fromNode == null)
continue;
var remapper = fromNode as INodeGroupRemapper;
if (remapper != null && !remapper.IsValidSlotConnection(outputRef.slotId))
continue;
shaderBody.AddShaderChunk("o." + slot.shaderOutputName + " = " + fromNode.GetVariableNameForSlot(outputRef.slotId) + ";", true);
if (slot.id == NormalSlotId)
shaderBody.AddShaderChunk("o." + slot.shaderOutputName + " += 1e-6;", true);
}
// Write tangent data to WorldVectors input on SurfaceOutput
if (slot.id == TangentSlotId)
{
var edges = owner.GetEdges(slot.slotReference);
if (edges.Any())
{
shaderBody.AddShaderChunk("float3x3 worldToTangent;", false);
shaderBody.AddShaderChunk("worldToTangent[0] = float3(1, 0, 0);", false);
shaderBody.AddShaderChunk("worldToTangent[1] = float3(0, 1, 0);", false);
shaderBody.AddShaderChunk("worldToTangent[2] = float3(0, 0, 1);", false);
shaderBody.AddShaderChunk("float3 tangentTWS = mul(o." + slot.shaderOutputName + ", worldToTangent);", false);
shaderBody.AddShaderChunk("o.WorldVectors = float3x3(tangentTWS, " + ShaderGeneratorNames.WorldSpaceBitangent + ", " + ShaderGeneratorNames.WorldSpaceNormal + ");", false);
}
else
{
shaderBody.AddShaderChunk("o.WorldVectors = float3x3(" + ShaderGeneratorNames.WorldSpaceTangent + ", " + ShaderGeneratorNames.WorldSpaceBitangent + ", " + ShaderGeneratorNames.WorldSpaceNormal + ");", false);
}
}
}
}
string[] customData = GetCustomData();
foreach(string data in customData)
{
shaderBody.AddShaderChunk(data, false);
}
}
public MaterialSlot GetMaterialSlot(int id)
{
if (slot.id == id)
return slot;
}
return null;
}
public string GetVariableNameForSlotAtId(int id)
{
MaterialSlot slot = GetMaterialSlot(id);
if (slot != null)
{
foreach (var edge in owner.GetEdges(slot.slotReference))
{
var outputRef = edge.outputSlot;

if (remapper != null && !remapper.IsValidSlotConnection(outputRef.slotId))
continue;
shaderBody.AddShaderChunk("o." + slot.shaderOutputName + " = " + fromNode.GetVariableNameForSlot(outputRef.slotId) + ";", true);
if (slot.id == NormalSlotId)
shaderBody.AddShaderChunk("o." + slot.shaderOutputName + " += 1e-6;", true);
return fromNode.GetVariableNameForSlot(outputRef.slotId);
//shaderBody.AddShaderChunk("o." + slot.shaderOutputName + " = " + fromNode.GetVariableNameForSlot(outputRef.slotId) + ";", true);
}
return "";
}
// Write tangent data to WorldVectors input on SurfaceOutput
if (slot.id == TangentSlotId)
{
var edges = owner.GetEdges(slot.slotReference);
if (edges.Any())
{
shaderBody.AddShaderChunk("float3x3 worldToTangent;", false);
shaderBody.AddShaderChunk("worldToTangent[0] = float3(1, 0, 0);", false);
shaderBody.AddShaderChunk("worldToTangent[1] = float3(0, 1, 0);", false);
shaderBody.AddShaderChunk("worldToTangent[2] = float3(0, 0, 1);", false);
shaderBody.AddShaderChunk("float3 tangentTWS = mul(o." + slot.shaderOutputName + ", worldToTangent);", false);
shaderBody.AddShaderChunk("o.WorldVectors = float3x3(tangentTWS, "+ ShaderGeneratorNames.WorldSpaceBitangent + ", "+ ShaderGeneratorNames.WorldSpaceNormal+ ");", false);
}
else
{
shaderBody.AddShaderChunk("o.WorldVectors = float3x3(" + ShaderGeneratorNames.WorldSpaceTangent + ", " + ShaderGeneratorNames.WorldSpaceBitangent + ", " + ShaderGeneratorNames.WorldSpaceNormal + ");", false);
}
}
bool CheckForCustomData(int id)
{
foreach (var custom in GetCustomDataSlots())
{
if (custom == id)
return true;
return false;
}
}
}

2
MaterialGraphProject/Assets/Matt/AnisotropicMaster.ShaderGraph
文件差异内容过多而无法显示
查看文件

12
MaterialGraphProject/Assets/Matt/AnisotropicMetallicMasterNode.cs


public AnisotropicMetallicMasterNode()
{
name = "AnisotropicMetallicMasterNode";
name = "AnisotropicMetallicMaster";
UpdateNodeAfterDeserialization();
}

}
public override int[] GetCustomDataSlots()
{
return new int[] { };
}
public override string[] GetCustomData()
{
return new string[] { };
}
public sealed override void UpdateNodeAfterDeserialization()

2
MaterialGraphProject/Assets/Matt/New Material.mat


m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: New Material
m_Shader: {fileID: 4800000, guid: 9ab5e16c2083a4fe689209a8c1ae425e, type: 3}
m_Shader: {fileID: 4800000, guid: 4afc3341bed83d34cb1aebb7e98d8751, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0

14
MaterialGraphProject/Assets/Rinaldo/BlendModeNode.cs


}
}
}
/*This is to overide input to be vector 3, not really necessary anymore*/
/*This is to overide input to be vector 3, not really necessary */
/*
protected override MaterialSlot GetInputSlot1()
{

var outputString = new ShaderGenerator();
switch (m_BlendMode)
{
/* case BlendModesEnum.AddSub:
outputString.AddShaderChunk(GetFunctionPrototype("arg1", "arg2"), false);
outputString.AddShaderChunk("{", false);
outputString.Indent();
outputString.AddShaderChunk("return 2.0 * arg1 + arg2 - 1.0;", false);
outputString.Deindent();
outputString.AddShaderChunk("}", false);
break;
*/
case BlendModesEnum.Burn:
outputString.AddShaderChunk(GetFunctionPrototype("arg1", "arg2"), false);
outputString.AddShaderChunk("{", false);

outputString.Deindent();
outputString.AddShaderChunk("}", false);
break;
case BlendModesEnum.LinearLight:
case BlendModesEnum.LinearLight_AddSub:
outputString.AddShaderChunk(GetFunctionPrototype("arg1", "arg2"), false);
outputString.AddShaderChunk("{", false);
outputString.Indent();

outputString.AddShaderChunk("}", false);
break;
}
visitor.AddShaderChunk(outputString.GetShaderString(0), true);
}
}

2
MaterialGraphProject/Assets/Rinaldo/BlendModesEnum.cs


Lighten,
LinearBurn,
LinearDodge,
LinearLight,
LinearLight_AddSub,
Multiply,
Negation,
Overlay,

2
MaterialGraphProject/Assets/Rinaldo/Editor/BlendModeNodePresenter.cs


*/
public override float GetHeight()
{
return 3 * (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing) + EditorGUIUtility.standardVerticalSpacing;
return EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing + EditorGUIUtility.standardVerticalSpacing;
}
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/NodePreviewPresenter.cs


var resultShader = GetPreviewShaderString();
Debug.Log("RecreateShaderAndMaterial : " + m_Node.GetVariableNameForNode() + Environment.NewLine + resultShader);
string shaderOuputString = resultShader.Replace("UnityEngine.MaterialGraph", "Generated");
System.IO.File.WriteAllText(Application.dataPath+"/GeneratedShader.shader", shaderOuputString);
if (string.IsNullOrEmpty(resultShader))
return false;

{
switch (previewProperty.m_PropType)
{
case PropertyType.Texture2D:
case PropertyType.Texture:
mat.SetTexture(previewProperty.m_Name, previewProperty.m_Texture);
break;
case PropertyType.Cubemap:

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/TextureAssetPresenter.cs


return;
tNode.exposedState = (PropertyNode.ExposedState)EditorGUILayout.EnumPopup(new GUIContent("Exposed"), tNode.exposedState);
tNode.defaultTexture = EditorGUILayout.MiniThumbnailObjectField(new GUIContent("Texture"), tNode.defaultTexture, typeof(Texture2D), null) as Texture2D;
tNode.defaultTexture = EditorGUILayout.MiniThumbnailObjectField(new GUIContent("Texture"), tNode.defaultTexture, typeof(Texture), null) as Texture;
tNode.textureType = (TextureType)EditorGUILayout.Popup((int)tNode.textureType, textureTypeNames, EditorStyles.popup);
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/TextureLODNodePresenter.cs


return;
tNode.exposedState = (PropertyNode.ExposedState)EditorGUILayout.EnumPopup(new GUIContent("Exposed"), tNode.exposedState);
tNode.defaultTexture = EditorGUILayout.MiniThumbnailObjectField(new GUIContent("Texture"), tNode.defaultTexture, typeof(Texture2D), null) as Texture2D;
tNode.defaultTexture = EditorGUILayout.MiniThumbnailObjectField(new GUIContent("Texture"), tNode.defaultTexture, typeof(Texture), null) as Texture;
tNode.textureType = (TextureType)EditorGUILayout.Popup((int)tNode.textureType, textureTypeNames, EditorStyles.popup);
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Presenters/TextureNodePresenter.cs


return;
tNode.exposedState = (PropertyNode.ExposedState)EditorGUILayout.EnumPopup(new GUIContent("Exposed"), tNode.exposedState);
tNode.defaultTexture = EditorGUILayout.MiniThumbnailObjectField(new GUIContent("Texture"), tNode.defaultTexture, typeof(Texture2D), null) as Texture2D;
tNode.defaultTexture = EditorGUILayout.MiniThumbnailObjectField(new GUIContent("Texture"), tNode.defaultTexture, typeof(Texture), null) as Texture;
tNode.textureType = (TextureType)EditorGUILayout.Popup((int)tNode.textureType, textureTypeNames, EditorStyles.popup);
}

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/HelperShader.shader.meta


fileFormatVersion: 2
guid: 9ab5e16c2083a4fe689209a8c1ae425e
timeCreated: 1495569001
timeCreated: 1495630928
defaultTextures: []
nonModifiableTextures: []
defaultTextures:
- TextureAsset_ebbe75eb_728a_4e6c_b8a1_994df86c74ad_Uniform: {fileID: 2800000, guid: 225a31f233f5b82488f996901413908d,
type: 3}
nonModifiableTextures:
- Texture_94ba0aed_e579_4ba0_b677_86c6deda72a2_Uniform: {fileID: 2800000, guid: 9c50a18d04437449b86568cfcbb668a7,
type: 3}
- Texture_65e72eb9_bdc7_4c17_b514_379aaeefd7ca_Uniform: {fileID: 2800000, guid: 84462bdfeee9d694bbebf34e5f3faa74,
type: 3}
userData:
assetBundleName:
assetBundleVariant:

32
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/ExportTexture.template


Pass
{
CGPROGRAM
#pragma vertex vert
#include "UnityCustomRenderTexture.cginc"
#pragma vertex CustomRenderTextureVertexShader${ShaderIsUsingPreview}
#include "UnityCG.cginc"
#pragma target 4.0
v2f_customrendertexture CustomRenderTextureVertexShader_Preview(appdata_base IN)
{
v2f_customrendertexture OUT;
OUT.vertex = UnityObjectToClipPos(IN.vertex);
OUT.primitiveID = 0;//TODO
OUT.localTexcoord = IN.texcoord;
OUT.globalTexcoord = IN.texcoord;
OUT.direction = CustomRenderTextureComputeCubeDirection(OUT.globalTexcoord.xy);
return OUT;
}
struct v2f
{
float4 pos : SV_POSITION;
${ShaderInputs}
};
v2f vert (appdata_full v)
{
v2f o = (v2f)0;
o.pos = UnityObjectToClipPos(v.vertex);
${VertexShaderBody}
return o;
}
half4 frag (v2f IN) : COLOR
float4 frag(v2f_customrendertexture IN) : COLOR
{
${PixelShaderBody}
}

10
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/advancedSubshader.template


float3 SubsurfaceShadingSimple(float3 diffColor, float3 normal, float3 viewDir, float3 thickness, UnityLight light)
{
half3 vLTLight = light.dir + normal * _TDistortion;
half fLTDot = pow(saturate(dot(viewDir, -vLTLight)), _TPower) * _TScale;
half3 fLT = _TAttenuation * (fLTDot + _TAmbient) * (thickness);
return diffColor * ((light.color * fLT) * _TransmissionOverallStrength);
half3 vLTLight = light.dir + normal * 1;
half fLTDot = pow(saturate(dot(viewDir, -vLTLight)), 3.5) * 1.5;
half3 fLT = 1 * (fLTDot + 1.2) * (thickness);
return diffColor * ((light.color * fLT) * 0.4);
}
// ------------------------------------------------------------------

///END
#pragma target 5.0
//#pragma target 5.0
#pragma surface surf ${LightingFunctionName} ${VertexShaderDecl}
#pragma glsl
#pragma debug

1
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/shader.template


${SubShader}
FallBack "Diffuse"
CustomEditor "LegacyIlluminShaderGUI"
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Testing/IntegrationTests/PropertyNodeTests.cs


"MudDiffuse.tif"
};
private static Texture2D FindTestTexture()
private static Texture FindTestTexture()
return AssetDatabase.LoadAssetAtPath<Texture2D>(texturePath);
return AssetDatabase.LoadAssetAtPath<Texture>(texturePath);
}
[SetUp]

[Test]
public void TestTextureNodeTypeIsCorrect()
{
Assert.AreEqual(PropertyType.Texture2D, m_TextureNode.propertyType);
Assert.AreEqual(PropertyType.Texture, m_TextureNode.propertyType);
}
[Test]

12
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/AbstractMaterialNode.cs


if (inputSlot == null)
return string.Empty;
string sufix = "";
var edges = owner.GetEdges(inputSlot.slotReference).ToArray();
if (edges.Any())

if (slot == null)
return string.Empty;
if (slot.concreteValueType == ConcreteSlotValueType.sampler2D)
sufix += "_Uniform";
return ShaderGenerator.AdaptNodeOutput(fromNode, slot.id, slot.concreteValueType) + sufix;
return ShaderGenerator.AdaptNodeOutput(fromNode, slot.id, slot.concreteValueType);
if (inputSlot.concreteValueType == ConcreteSlotValueType.sampler2D)
sufix += "_Uniform";
return inputSlot.GetDefaultValue(generationMode) + sufix;
return inputSlot.GetDefaultValue(generationMode);
}
private ConcreteSlotValueType FindCommonChannelType(ConcreteSlotValueType from, ConcreteSlotValueType to)

switch (slotValue)
{
case ConcreteSlotValueType.sampler2D:
return PropertyType.Texture2D;
return PropertyType.Texture;
case ConcreteSlotValueType.Vector1:
return PropertyType.Float;
case ConcreteSlotValueType.Vector2:

6
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/SceneData/DepthTextureNode.cs


public override bool hasPreview { get { return true; } }
public Texture2D defaultTexture { get; set; }
public Texture defaultTexture { get; set; }
public DepthTextureNode()
{

return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Texture2D,
m_PropType = PropertyType.Texture,
m_Texture = defaultTexture
};
}

return GetVariableNameForNode();
}
public override PropertyType propertyType { get { return PropertyType.Texture2D; } }
public override PropertyType propertyType { get { return PropertyType.Texture; } }
public bool RequiresMeshUV(UVChannel channel)
{

6
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/SceneData/MotionVectorTextureNode.cs


public override bool hasPreview { get { return true; } }
public Texture2D defaultTexture { get; set; }
public Texture defaultTexture { get; set; }
public MotionVectorTextureNode()
{

return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Texture2D,
m_PropType = PropertyType.Texture,
m_Texture = defaultTexture
};
}

return GetVariableNameForNode();
}
public override PropertyType propertyType { get { return PropertyType.Texture2D; } }
public override PropertyType propertyType { get { return PropertyType.Texture; } }
public bool RequiresMeshUV(UVChannel channel)
{

10
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/TextureLODNode.cs


[Serializable]
private class TextureHelper
{
public Texture2D texture;
public Texture texture;
public Texture2D defaultTexture
public Texture defaultTexture
{
get
{

}
}
#else
public Texture2D defaultTexture { get; set; }
public Texture defaultTexture { get; set; }
#endif
public TextureType textureType

return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Texture2D,
m_PropType = PropertyType.Texture,
public override PropertyType propertyType { get { return PropertyType.Texture2D; } }
public override PropertyType propertyType { get { return PropertyType.Texture; } }
public bool RequiresMeshUV(UVChannel channel)
{

10
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/Input/Texture/TextureNode.cs


[Serializable]
private class TextureHelper
{
public Texture2D texture;
public Texture texture;
public Texture2D defaultTexture
public Texture defaultTexture
{
get
{

}
}
#else
public Texture2D defaultTexture {get; set; }
public Texture defaultTexture {get; set; }
#endif
public TextureType textureType

return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Texture2D,
m_PropType = PropertyType.Texture,
public override PropertyType propertyType { get { return PropertyType.Texture2D; } }
public override PropertyType propertyType { get { return PropertyType.Texture; } }
public bool RequiresMeshUV(UVChannel channel)
{

2
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/PreviewProperty.cs


public PropertyType m_PropType;
public Color m_Color;
public Texture2D m_Texture;
public Texture m_Texture;
public Cubemap m_Cubemap;
public Vector4 m_Vector4;
public float m_Float;

2
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/Nodes/PropertyType.cs


public enum PropertyType
{
Color,
Texture2D,
Texture,
Cubemap,
Float,
Vector2,

61
MaterialGraphProject/Assets/UnityShaderEditor/Runtime/SurfaceModel/ExportTextureMasterNode.cs


namespace UnityEngine.MaterialGraph
{
[Serializable]
[Title("Master/Export Texture")]
[Title("Master/Custom Texture")]
public class ExportTextureMasterNode : AbstractMasterNode
{
public const string ColorSlotName = "Color";

return false;
}
public override string GetFullShader(GenerationMode mode, out List<PropertyGenerator.TextureInfo> configuredTextures)
public override string GetFullShader(GenerationMode generationMode, out List<PropertyGenerator.TextureInfo> configuredTextures)
{
// figure out what kind of preview we want!

var shaderPropertiesVisitor = new PropertyGenerator();
var shaderPropertyUsagesVisitor = new ShaderGenerator();
var shaderInputVisitor = new ShaderGenerator();
var vertexShaderBlock = new ShaderGenerator();
vertexShaderBlock.AddShaderChunk("float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;", true);
vertexShaderBlock.AddShaderChunk("float3 viewDir = UnityWorldSpaceViewDir(worldPos);", true);
vertexShaderBlock.AddShaderChunk("float4 screenPos = ComputeScreenPos(UnityObjectToClipPos(v.vertex));", true);
vertexShaderBlock.AddShaderChunk("float3 worldNormal = UnityObjectToWorldNormal(v.normal);", true);
shaderInputVisitor.AddShaderChunk("float3 worldPos : TEXCOORD0;", true);
vertexShaderBlock.AddShaderChunk("o.worldPos = worldPos;", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpacePosition + " = IN.worldPos;", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpacePosition + " = float3(0.0, 0.0, 0.0);", true);
shaderInputVisitor.AddShaderChunk("float3 worldNormal : TEXCOORD1;", true);
vertexShaderBlock.AddShaderChunk("o.worldNormal = worldNormal;", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceNormal + " = normalize(IN.worldNormal);", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceNormal + " = float3(0.0, 0.0, 1.0);", true);
}
for (int uvIndex = 0; uvIndex < ShaderGeneratorNames.UVCount; ++uvIndex)

{
shaderInputVisitor.AddShaderChunk(string.Format("half4 meshUV{0} : TEXCOORD{1};", uvIndex, (uvIndex + 5)), true);
vertexShaderBlock.AddShaderChunk(string.Format("o.meshUV{0} = v.texcoord{1};", uvIndex, uvIndex == 0 ? "" : uvIndex.ToString()), true);
shaderBodyVisitor.AddShaderChunk(string.Format("half4 {0} = IN.meshUV{1};", channel.GetUVName(), uvIndex), true);
shaderBodyVisitor.AddShaderChunk("half4 " + channel.GetUVName() + " = float4(IN.localTexcoord.xyz,1.0);", true);
shaderBodyVisitor.AddShaderChunk(
"float3 "
+ ShaderGeneratorNames.WorldSpaceViewDirection
+ " = normalize(UnityWorldSpaceViewDir("
+ ShaderGeneratorNames.WorldSpacePosition
+ "));", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceViewDirection + " = float3(0.0, 0.0, -1.0);", true);
shaderInputVisitor.AddShaderChunk("float4 screenPos : TEXCOORD3;", true);
vertexShaderBlock.AddShaderChunk("o.screenPos = screenPos;", true);
shaderBodyVisitor.AddShaderChunk("half4 " + ShaderGeneratorNames.ScreenPosition + " = IN.screenPos;", true);
shaderBodyVisitor.AddShaderChunk("half4 " + ShaderGeneratorNames.ScreenPosition + " = float4(IN.globalTexcoord.xyz, 1.0);", true);
shaderInputVisitor.AddShaderChunk("float4 worldTangent : TEXCOORD4;", true);
vertexShaderBlock.AddShaderChunk("o.worldTangent = float4(UnityObjectToWorldDir(v.tangent.xyz), v.tangent.w);", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceTangent + " = normalize(IN.worldTangent.xyz);", true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceTangent + " = float3(1.0,0.0,0.0);", true);
shaderBodyVisitor.AddShaderChunk(string.Format("float3 {0} = cross({1}, {2}) * IN.worldTangent.w;", ShaderGeneratorNames.WorldSpaceBitangent, ShaderGeneratorNames.WorldSpaceNormal, ShaderGeneratorNames.WorldSpaceTangent), true);
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceBitangent + " = float3(0.0,1.0,0.0);", true);
vertexShaderBlock.AddShaderChunk("o.color = v.color;", true);
shaderBodyVisitor.AddShaderChunk("float4 " + ShaderGeneratorNames.VertexColor + " = IN.color;", true);
shaderBodyVisitor.AddShaderChunk("float4 " + ShaderGeneratorNames.VertexColor + " = float4(1.0,1.0,1.0,1.0);", true);
var generationMode = GenerationMode.Preview;
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
{
if (activeNode is IGeneratesFunction)

template = template.Replace("${ShaderName}", GetType() + guid.ToString());
template = template.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetShaderString(2));
template = template.Replace("${ShaderPropertyUsages}", shaderPropertyUsagesVisitor.GetShaderString(3));
template = template.Replace("${ShaderInputs}", shaderInputVisitor.GetShaderString(4));
template = template.Replace("${VertexShaderBody}", vertexShaderBlock.GetShaderString(4));
string vertexShaderBody = vertexShaderBlock.GetShaderString(4);
if (vertexShaderBody.Length > 0)
{
template = template.Replace("${VertexShaderDecl}", "vertex:vert");
template = template.Replace("${VertexShaderBody}", vertexShaderBody);
}
else
{
template = template.Replace("${VertexShaderDecl}", "");
template = template.Replace("${VertexShaderBody}", vertexShaderBody);
}
//In preview mode we use a different vertex shader, as the custom texture shaders are customized and not preview compatible.
template = template.Replace("${ShaderIsUsingPreview}", generationMode == GenerationMode.Preview?"_Preview":"");
configuredTextures = shaderPropertiesVisitor.GetConfiguredTexutres();
return Regex.Replace(template, @"\r\n|\n\r|\n|\r", Environment.NewLine);

22
MaterialGraphProject/Assets/Vlad/TextureAssetNode.cs


[Serializable]
private class TextureHelper
{
public Texture2D texture;
public Texture texture;
public Texture2D defaultTexture
public Texture defaultTexture
{
get
{

}
}
#else
public Texture2D defaultTexture {get; set; }
public Texture defaultTexture {get; set; }
#endif
public TextureType textureType

get { return new[] { OutputSlotRgbaId }; }
}
public override string GetVariableNameForSlot(int slotId)
{
string slotOutput;
switch (slotId)
{
default:
slotOutput = "";
break;
}
return GetVariableNameForNode() + slotOutput;
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
properties.Add(GetPreviewProperty());

return new PreviewProperty
{
m_Name = propertyName,
m_PropType = PropertyType.Texture2D,
m_PropType = PropertyType.Texture,
m_Texture = defaultTexture
};
}

public override PropertyType propertyType { get { return PropertyType.Texture2D; } }
public override PropertyType propertyType { get { return PropertyType.Texture; } }
}
}

75
MaterialGraphProject/Assets/Vlad/UVTriPlanar.cs


namespace UnityEngine.MaterialGraph
{
[Title("UV/Tri-Planar Mapping")]
public class UVTriPlanar : Function1Input, IGeneratesFunction, IMayRequireNormal, IMayRequireWorldPosition
public class UVTriPlanar : Function3Input, IGeneratesFunction, IMayRequireNormal, IMayRequireWorldPosition
private const string kTileSlotName = "Tile";
private const string kBlendSlotName = "Blend";
protected override string GetFunctionName()
{

protected override MaterialSlot GetInputSlot()
protected override MaterialSlot GetInputSlot1()
{
return new MaterialSlot(InputSlot1Id, kTextureSlotName, kTextureSlotName, SlotType.Input, SlotValueType.sampler2D, Vector4.zero, false);
}
protected override MaterialSlot GetInputSlot2()
return new MaterialSlot(InputSlotId, kTextureSlotName, kTextureSlotName, SlotType.Input, SlotValueType.sampler2D, Vector4.zero, false);
return new MaterialSlot(InputSlot2Id, kTileSlotName, kTileSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.one);
}
protected override MaterialSlot GetInputSlot3()
{
return new MaterialSlot(InputSlot3Id, kBlendSlotName, kBlendSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.one);
}
protected override MaterialSlot GetOutputSlot()

UpdateNodeAfterDeserialization();
}
protected override string GetFunctionPrototype(string argName)
public override bool hasPreview
{
get { return true; }
}
public override PreviewMode previewMode
{
get
{
return PreviewMode.Preview3D;
}
}
protected override string GetFunctionPrototype(string arg1Name, string arg2Name, string arg3Name)
+ "sampler2D " + argName + ", float3 normal, float3 pos)";
+ "sampler2D " + arg1Name + ", "
+ precision + " " + arg2Name + ", "
+ precision + " " + arg3Name +
", float3 normal, float3 pos)";
protected override string GetFunctionCallBody(string inputValue)
protected override string GetFunctionCallBody(string input1Value, string input2Value, string input3Value)
return GetFunctionName() + " (" + inputValue + "_Uniform" + ", IN.worldNormal, IN.worldPos)";
return GetFunctionName() + " (" + input1Value + ", " + input2Value + ", " + input3Value + ", IN.worldNormal, IN.worldPos)";
}
public override void GeneratePropertyUsages(ShaderGenerator visitor, GenerationMode generationMode)

{
var outputString = new ShaderGenerator();
var textureSlot = FindInputSlot<MaterialSlot>(InputSlotId);
var textureSlot = FindInputSlot<MaterialSlot>(InputSlot1Id);
if (textureSlot == null)
return;

}
////////////////////////////////QQQ: Any better way of getting "_Uniform" at the end? //////////////////////////////////
// outputString.AddShaderChunk("sampler2D " + textureName + "_Uniform;", false);
// outputString.AddShaderChunk("", false);
outputString.AddShaderChunk(GetFunctionPrototype("arg"), false);
outputString.AddShaderChunk(GetFunctionPrototype("arg1", "arg2", "arg3"), false);
// create UVs from position
outputString.AddShaderChunk("fixed3 uvs = pos * arg2;", false);
outputString.AddShaderChunk("half3 blend = abs(normal);", false);
outputString.AddShaderChunk("half3 blend = pow(abs(normal), arg3);", false);
outputString.AddShaderChunk("fixed4 cx = tex2D(arg, pos.yz);", false);
outputString.AddShaderChunk("fixed4 cy = tex2D(arg, pos.xz);", false);
outputString.AddShaderChunk("fixed4 cz = tex2D(arg, pos.xy);", false);
outputString.AddShaderChunk("fixed4 cx = tex2D(arg1, uvs.yz);", false);
outputString.AddShaderChunk("fixed4 cy = tex2D(arg1, uvs.xz);", false);
outputString.AddShaderChunk("fixed4 cz = tex2D(arg1, uvs.xy);", false);
// blend the textures based on weights

outputString.AddShaderChunk("}", false);
visitor.AddShaderChunk(outputString.GetShaderString(0), true);
}
//prevent validation errors when a sampler2D input is missing
//use on any input requiring a TextureAssetNode
public override void ValidateNode()
{
base.ValidateNode();
var slot = FindInputSlot<MaterialSlot>(InputSlot1Id);
if (slot == null)
return;
var edges = owner.GetEdges(slot.slotReference).ToList();
hasError |= edges.Count == 0;
}
public bool RequiresNormal()

180
MaterialGraphProject/ProjectSettings/ProjectSettings.asset


--- !u!129 &1
PlayerSettings:
m_ObjectHideFlags: 0
serializedVersion: 10
serializedVersion: 11
productGUID: 4a61ffcca1e65d342aac47392d65ac32
AndroidProfiler: 0
defaultScreenOrientation: 0

captureSingleScreen: 0
muteOtherAudioSources: 0
Prepare IOS For Recording: 0
Force IOS Speakers When Recording: 0
submitAnalytics: 1
usePlayerLog: 1
bakeCollisionMeshes: 0

macAppStoreCategory: public.app-category.games
gpuSkinning: 0
graphicsJobs: 0
xboxPIXTextureCapture: 0

xboxEnableFitness: 0
visibleInBackground: 0
allowFullscreenSwitch: 1
graphicsJobMode: 0
macFullscreenMode: 2
d3d9FullscreenMode: 1
d3d11FullscreenMode: 1

n3dsDisableStereoscopicView: 0
n3dsEnableSharedListOpt: 1
n3dsEnableVSync: 0
uiUse16BitDepthBuffer: 0
xboxOneDisableEsram: 0
xboxOnePresentImmediateThreshold: 0
videoMemoryForVertexBuffers: 0
psp2PowerMode: 0
psp2AcquireBGM: 1

16:10: 1
16:9: 1
Others: 1
bundleIdentifier: com.Company.ProductName
vrSettings: {}
xboxOneEnable7thCore: 0
vrSettings:
cardboard:
depthFormat: 0
enableTransitionView: 0
daydream:
depthFormat: 0
useSustainedPerformanceMode: 0
hololens:
depthFormat: 1
m_ColorGamuts: 00000000
targetPixelDensity: 0
resolutionScalingMode: 0
applicationIdentifier:
Android: com.Company.ProductName
Standalone: unity.DefaultCompany.Graphs
Tizen: com.Company.ProductName
iOS: com.Company.ProductName
tvOS: com.Company.ProductName
buildNumber:
iOS: 0
AndroidMinSdkVersion: 9
AndroidMinSdkVersion: 16
AndroidTargetSdkVersion: 0
iPhoneBuildNumber: 0
ForceInternetPermission: 0
ForceSDCardPermission: 0
CreateWallpaper: 0

iOSURLSchemes: []
iOSBackgroundModes: 0
iOSMetalForceHardShadows: 0
metalEditorSupport: 1
metalAPIValidation: 1
iOSRenderExtraFrameOnPause: 1
iOSManualSigningProvisioningProfileID:
tvOSManualSigningProvisioningProfileID:
appleEnableAutomaticSigning: 0
AndroidTargetDevice: 0
AndroidSplashScreenScale: 0
androidSplashScreen: {fileID: 0}

m_BuildTargetBatching: []
m_BuildTargetGraphicsAPIs:
- m_BuildTarget: WindowsStandaloneSupport
m_APIs: 01000000
m_APIs: 0200000001000000
m_Automatic: 0
- m_BuildTarget: AndroidPlayer
m_APIs: 08000000

wiiUGamePadStartupScreen: {fileID: 0}
wiiUDrcBufferDisabled: 0
wiiUProfilerLibPath:
playModeTestRunnerEnabled: 0
actionOnDotNetUnhandledException: 1
enableInternalProfiler: 0
logObjCUncaughtExceptions: 1

microphoneUsageDescription:
XboxTitleId:
XboxImageXexPath:
XboxSpaPath:
XboxGenerateSpa: 0
XboxDeployKinectResources: 0
XboxSplashScreen: {fileID: 0}
xboxEnableSpeech: 0
xboxAdditionalTitleMemorySize: 0
xboxDeployKinectHeadOrientation: 0
xboxDeployKinectHeadPosition: 0
switchNetLibKey:
switchSocketMemoryPoolSize: 6144
switchSocketAllocatorPoolSize: 128
switchSocketConcurrencyLimit: 14
switchScreenResolutionBehavior: 2
switchUseCPUProfiler: 0
switchApplicationID: 0x01004b9000490000
switchNSODependencies:
switchTitleNames_0:
switchTitleNames_1:
switchTitleNames_2:
switchTitleNames_3:
switchTitleNames_4:
switchTitleNames_5:
switchTitleNames_6:
switchTitleNames_7:
switchTitleNames_8:
switchTitleNames_9:
switchTitleNames_10:
switchTitleNames_11:
switchPublisherNames_0:
switchPublisherNames_1:
switchPublisherNames_2:
switchPublisherNames_3:
switchPublisherNames_4:
switchPublisherNames_5:
switchPublisherNames_6:
switchPublisherNames_7:
switchPublisherNames_8:
switchPublisherNames_9:
switchPublisherNames_10:
switchPublisherNames_11:
switchIcons_0: {fileID: 0}
switchIcons_1: {fileID: 0}
switchIcons_2: {fileID: 0}
switchIcons_3: {fileID: 0}
switchIcons_4: {fileID: 0}
switchIcons_5: {fileID: 0}
switchIcons_6: {fileID: 0}
switchIcons_7: {fileID: 0}
switchIcons_8: {fileID: 0}
switchIcons_9: {fileID: 0}
switchIcons_10: {fileID: 0}
switchIcons_11: {fileID: 0}
switchSmallIcons_0: {fileID: 0}
switchSmallIcons_1: {fileID: 0}
switchSmallIcons_2: {fileID: 0}
switchSmallIcons_3: {fileID: 0}
switchSmallIcons_4: {fileID: 0}
switchSmallIcons_5: {fileID: 0}
switchSmallIcons_6: {fileID: 0}
switchSmallIcons_7: {fileID: 0}
switchSmallIcons_8: {fileID: 0}
switchSmallIcons_9: {fileID: 0}
switchSmallIcons_10: {fileID: 0}
switchSmallIcons_11: {fileID: 0}
switchManualHTML:
switchAccessibleURLs:
switchLegalInformation:
switchMainThreadStackSize: 1048576
switchPresenceGroupId: 0x01004b9000490000
switchLogoHandling: 0
switchReleaseVersion: 0
switchDisplayVersion: 1.0.0
switchStartupUserAccount: 0
switchTouchScreenUsage: 0
switchSupportedLanguagesMask: 0
switchLogoType: 0
switchApplicationErrorCodeCategory:
switchUserAccountSaveDataSize: 0
switchUserAccountSaveDataJournalSize: 0
switchApplicationAttribute: 0
switchCardSpecSize: 4
switchCardSpecClock: 25
switchRatingsMask: 0
switchRatingsInt_0: 0
switchRatingsInt_1: 0
switchRatingsInt_2: 0
switchRatingsInt_3: 0
switchRatingsInt_4: 0
switchRatingsInt_5: 0
switchRatingsInt_6: 0
switchRatingsInt_7: 0
switchRatingsInt_8: 0
switchRatingsInt_9: 0
switchRatingsInt_10: 0
switchRatingsInt_11: 0
switchLocalCommunicationIds_0: 0x01004b9000490000
switchLocalCommunicationIds_1:
switchLocalCommunicationIds_2:
switchLocalCommunicationIds_3:
switchLocalCommunicationIds_4:
switchLocalCommunicationIds_5:
switchLocalCommunicationIds_6:
switchLocalCommunicationIds_7:
switchParentalControl: 0
switchAllowsScreenshot: 1
switchDataLossConfirmation: 0
switchSupportedNpadStyles: 3
switchSocketConfigEnabled: 0
switchTcpInitialSendBufferSize: 32
switchTcpInitialReceiveBufferSize: 64
switchTcpAutoSendBufferSizeMax: 256
switchTcpAutoReceiveBufferSizeMax: 256
switchUdpSendBufferSize: 9
switchUdpReceiveBufferSize: 42
switchSocketBufferEfficiency: 4
ps4NPAgeRating: 12
ps4NPTitleSecret:
ps4NPTrophyPackPath:

ps4ParamSfxPath:
ps4VideoOutPixelFormat: 0
ps4VideoOutInitialWidth: 1920
ps4VideoOutBaseModeInitialWidth: 1920
ps4VideoOutReprojectionRate: 120
ps4PronunciationXMLPath:
ps4PronunciationSIGPath:

ps4ApplicationParam4: 0
ps4DownloadDataSize: 0
ps4GarlicHeapSize: 2048
ps4ProGarlicHeapSize: 2560
ps4UseDebugIl2cppLibs: 0
ps4pnSessions: 1
ps4pnPresence: 1
ps4pnFriends: 1

ps4attribShareSupport: 0
ps4attribExclusiveVR: 0
ps4disableAutoHideSplash: 0
ps4videoRecordingFeaturesUsed: 0
ps4contentSearchFeaturesUsed: 0
ps4attribEyeToEyeDistanceSettingVR: 0
ps4IncludedModules: []
monoEnv:
psp2Splashimage: {fileID: 0}

psp2UseLibLocation: 0
psp2InfoBarOnStartup: 0
psp2InfoBarColor: 0
psp2UseDebugIl2cppLibs: 0
psp2ScriptOptimizationLevel: 0
psmSplashimage: {fileID: 0}
splashScreenBackgroundSourceLandscape: {fileID: 0}
splashScreenBackgroundSourcePortrait: {fileID: 0}

Standalone: 0
incrementalIl2cppBuild: {}
additionalIl2CppArgs:
scriptingRuntimeVersion: 0
apiCompatibilityLevelPerPlatform: {}
m_RenderingPath: 1
m_MobileRenderingPath: 1

tizenMicrophonePermissions: 0
tizenDeploymentTarget:
tizenDeploymentTargetType: 0
tizenMinOSVersion: 0
tizenMinOSVersion: 1
n3dsUseExtSaveData: 0
n3dsCompressStaticMem: 1
n3dsExtSaveDataNumber: 0x12345

XboxOneSplashScreen: {fileID: 0}
XboxOneAllowedProductIds: []
XboxOnePersistentLocalStorageSize: 0
vrEditorSettings: {}
xboxOneScriptCompiler: 0
vrEditorSettings:
daydream:
daydreamIconForeground: {fileID: 0}
daydreamIconBackground: {fileID: 0}
cloudServicesEnabled:
Analytics: 0
Build: 0

projectName:
organizationId:
cloudEnabled: 0
enableNativePlatformBackendsForNewInputSystem: 0
disableOldInputManagerSupport: 0

46
MaterialGraphProject/Assets/Eduardo/ChannelBlendNode.cs


using UnityEngine.Graphing;
using System.Linq;
using System.Collections;
namespace UnityEngine.MaterialGraph
{
[Title("Art/ChannelBlend")]
public class ChannelBlend : FunctionNInNOut, IGeneratesFunction
{
public ChannelBlend()
{
name = "ChannelBlend";
AddSlot("Mask", "mask", Graphing.SlotType.Input, SlotValueType.Vector4, Vector4.zero);
AddSlot("RColor", "rCol", Graphing.SlotType.Input, SlotValueType.Vector4, Vector4.zero);
AddSlot("GColor", "gCol", Graphing.SlotType.Input, SlotValueType.Vector4, Vector4.zero);
AddSlot("BColor", "bCol", Graphing.SlotType.Input, SlotValueType.Vector4, Vector4.zero);
AddSlot("AColor", "aCol", Graphing.SlotType.Input, SlotValueType.Vector4, Vector4.zero);
AddSlot("BGColor", "bgCol", Graphing.SlotType.Input, SlotValueType.Vector4, Vector4.zero);
AddSlot("BlendedColor", "blendCol", Graphing.SlotType.Output, SlotValueType.Vector4, Vector4.zero);
}
protected override string GetFunctionName()
{
return "unity_ChannelBlend";
}
public override bool hasPreview
{
get { return true; }
}
public void GenerateNodeFunction(ShaderGenerator visitor, GenerationMode generationMode)
{
var outputString = new ShaderGenerator();
outputString.AddShaderChunk(GetFunctionPrototype(), false);
outputString.AddShaderChunk("{", false);
outputString.AddShaderChunk("float4 background = step(max(mask.r,max(mask.g,mask.b)), 0.001) * bgCol;", false);
outputString.AddShaderChunk("blendCol = mask.r * rCol + mask.g * gCol + mask.b * bCol + mask.a * aCol + background;", false);
outputString.AddShaderChunk("}", false);
visitor.AddShaderChunk(outputString.GetShaderString(0), true);
}
}
}

12
MaterialGraphProject/Assets/Eduardo/ChannelBlendNode.cs.meta


fileFormatVersion: 2
guid: a3ee559026fa1ca4aab68fafbdcfbc56
timeCreated: 1495618140
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

20
MaterialGraphProject/Assets/Eduardo/ReciprocalSqrtNode.cs


namespace UnityEngine.MaterialGraph
{
[Title("Math/Advanced/Reciprocal Square Root")]
public class ReciprocalSqrtNode : Function1Input
{
public ReciprocalSqrtNode()
{
name = "ReciprocalSquareRoot";
}
public override bool hasPreview
{
get { return false; }
}
protected override string GetFunctionName() { return "rsqrt"; }
}
}

12
MaterialGraphProject/Assets/Eduardo/ReciprocalSqrtNode.cs.meta


fileFormatVersion: 2
guid: d67c532974f20f74ca83c79573c45a61
timeCreated: 1495627989
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

906
MaterialGraphProject/Assets/GeneratedShader.shader


Shader "Graph/Generated.AnisotropicMetallicMasterNoded3249a79-099e-4f35-8185-c418a23965c8"
{
Properties
{
}
SubShader
{
Tags
{
"RenderType"="Opaque"
"Queue"="Geometry"
}
Blend One Zero
Cull Back
ZTest LEqual
ZWrite On
LOD 200
CGPROGRAM
#include "UnityCG.cginc"
//#include "AdvancedBRDF.cginc"
//#include "AdvancedShading.cginc"
//#include "AdvancedLighting.cginc"
#define SHADINGMODELID_STANDARD
// ------------------------------------------------------------------
// Diffuse
// From UE4 - Used for Cloth (Deprecated)
float3 Diffuse_Lambert(float3 DiffuseColor)
{
return DiffuseColor * (1 / UNITY_PI);
}
// ------------------------------------------------------------------
// Fresnel
// From UE4 - Used for Cloth
// [Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering"]
float3 F_Schlick(float3 SpecularColor, float VoH)
{
float Fc = Pow5(1 - VoH); // 1 sub, 3 mul
//return Fc + (1 - Fc) * SpecularColor; // 1 add, 3 mad
// Anything less than 2% is physically impossible and is instead considered to be shadowing
return saturate(50.0 * SpecularColor.g) * Fc + (1 - Fc) * SpecularColor;
}
// ------------------------------------------------------------------
// Distribution
// From UE4 - USed for Cloth
// GGX / Trowbridge-Reitz
// [Walter et al. 2007, "Microfacet models for refraction through rough surfaces"]
float D_GGX(float roughness, float NdotH)
{
float a = roughness * roughness;
float a2 = a * a;
float d = (NdotH * a2 - NdotH) * NdotH + 1; // 2 mad
return a2 / (UNITY_PI*d*d); // 4 mul, 1 rcp
}
// Anisotropic GGX
// Taken from HDRenderPipeline
float D_GGXAnisotropic(float TdotH, float BdotH, float NdotH, float roughnessT, float roughnessB)
{
float f = TdotH * TdotH / (roughnessT * roughnessT) + BdotH * BdotH / (roughnessB * roughnessB) + NdotH * NdotH;
return 1.0 / (roughnessT * roughnessB * f * f);
}
// From UE4 - Used for Cloth
float D_InvGGX(float roughness, float NdotH)
{
float a = roughness * roughness;
float a2 = a * a;
float A = 4;
float d = (NdotH - a2 * NdotH) * NdotH + a2;
return 1/(UNITY_PI * (1 + A*a2)) * (1 + 4 * a2*a2 / (d*d)); //RCP
}
// ------------------------------------------------------------------
// Visibility
// From UE4 - Used for Cloth
// Appoximation of joint Smith term for GGX
// [Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs"]
float Vis_SmithJointApprox(float Roughness, float NoV, float NoL)
{
float a = (Roughness*Roughness);
float Vis_SmithV = NoL * (NoV * (1 - a) + a);
float Vis_SmithL = NoV * (NoL * (1 - a) + a);
// Note: will generate NaNs with Roughness = 0. MinRoughness is used to prevent this
return 0.5 * 1/(Vis_SmithV + Vis_SmithL); //RCP
}
// From UE4 - Used for Cloth
float Vis_Cloth(float NoV, float NoL)
{
return 1/(4 * (NoL + NoV - NoL * NoV)); //RCP
}
// ------------------------------------------------------------------
// SORT THESE
// Smith Joint GGX Anisotropic Visibility
// Taken from https://cedec.cesa.or.jp/2015/session/ENG/14698.html
float SmithJointGGXAnisotropic(float TdotV, float BdotV, float NdotV, float TdotL, float BdotL, float NdotL, float roughnessT, float roughnessB)
{
float aT = roughnessT;
float aT2 = aT * aT;
float aB = roughnessB;
float aB2 = aB * aB;
float lambdaV = NdotL * sqrt(aT2 * TdotV * TdotV + aB2 * BdotV * BdotV + NdotV * NdotV);
float lambdaL = NdotV * sqrt(aT2 * TdotL * TdotL + aB2 * BdotL * BdotL + NdotL * NdotL);
return 0.5 / (lambdaV + lambdaL);
}
// Convert Anistropy to roughness
void ConvertAnisotropyToRoughness(float roughness, float anisotropy, out float roughnessT, out float roughnessB)
{
// (0 <= anisotropy <= 1), therefore (0 <= anisoAspect <= 1)
// The 0.9 factor limits the aspect ratio to 10:1.
float anisoAspect = sqrt(1.0 - 0.9 * anisotropy);
roughnessT = roughness / anisoAspect; // Distort along tangent (rougher)
roughnessB = roughness * anisoAspect; // Straighten along bitangent (smoother)
}
// Schlick Fresnel
float FresnelSchlick(float f0, float f90, float u)
{
float x = 1.0 - u;
float x5 = x * x;
x5 = x5 * x5 * x;
return (f90 - f0) * x5 + f0; // sub mul mul mul sub mad
}
//Clamp roughness
float ClampRoughnessForAnalyticalLights(float roughness)
{
return max(roughness, 0.000001);
}
//Calculate tangent warp for IBL (Reference Version - not used)
float3 SpecularGGXIBLRef(float3 viewDir, float3 normalDir, float3 tangentDir, float3 bitangentDir, float roughnessT, float roughnessB)
{
return float3(1, 1, 1);
//Hidden in UnityAnisotropicLighting.cginc
}
// Sample Anisotropic Direction for IBL (Reference Version - not used)
void SampleAnisoGGXDir(float2 u, float3 viewDir, float3 normalDir, float3 tangent, float3 bitangent, float roughnessT, float roughnessB, out float3 halfDir, out float3 lightDir)
{
// AnisoGGX NDF sampling
halfDir = sqrt(u.x / (1.0 - u.x)) * (roughnessT * cos((UNITY_PI * 2) * u.y) * tangent + roughnessB * sin((UNITY_PI * 2) * u.y) * bitangent) + normalDir;
halfDir = normalize(halfDir);
// Convert sample from half angle to incident angle
lightDir = 2.0 * saturate(dot(viewDir, halfDir)) * halfDir - viewDir;
}
// Ref: Donald Revie - Implementing Fur Using Deferred Shading (GPU Pro 2)
// The grain direction (e.g. hair or brush direction) is assumed to be orthogonal to the normal.
// The returned normal is NOT normalized.
float3 ComputeGrainNormal(float3 grainDir, float3 V)
{
float3 B = cross(-V, grainDir);
return cross(B, grainDir);
}
//Modify Normal for Anisotropic IBL (Realtime version)
// Fake anisotropic by distorting the normal.
// The grain direction (e.g. hair or brush direction) is assumed to be orthogonal to N.
// Anisotropic ratio (0->no isotropic; 1->full anisotropy in tangent direction)
float3 GetAnisotropicModifiedNormal(float3 grainDir, float3 N, float3 V, float anisotropy)
{
float3 grainNormal = ComputeGrainNormal(grainDir, V);
// TODO: test whether normalizing 'grainNormal' is worth it.
return normalize(lerp(N, grainNormal, anisotropy));
}
/// REGION END - ANISOTROPY
/// REGION START - SUBSURFACE SCATTERING
half Fresnel(half3 H, half3 V, half F0)
{
half base = 1.0 - dot(V, H);
half exponential = pow(base, 5.0);
return exponential + F0 * (1.0 - exponential);
}
/*
inline half3 KelemenSzirmayKalosSpecular(half3 normal, half3 lightDir, half3 viewDir, float roughness, float rho_s)
{
half3 result = half3(0, 0, 0);
half NdotL = dot(normal, lightDir);
if (NdotL > 0.0)
{
half3 h = lightDir + viewDir;
half3 H = normalize(h);
half NdotH = dot(normal, H);
half PH = pow(2.0 * tex2D(_BeckmannPrecomputedTex, half2(NdotH, roughness)).r, 10.0);
half F = Fresnel(H, viewDir, 0.028);
half frSpec = max(PH * F / dot(h, h), 0);
half term = NdotL * rho_s * frSpec;
result = half3(term, term, term);
}
return result;
}*/
/*
half3 SkinDiffuse(float curv, float3 NdotL)
{
float3 lookup = NdotL * 0.5 + 0.5;
float3 diffuse;
diffuse.r = tex2D(_DiffusionProfileTexture, float2(lookup.r, curv)).r;
diffuse.g = tex2D(_DiffusionProfileTexture, float2(lookup.g, curv)).g;
diffuse.b = tex2D(_DiffusionProfileTexture, float2(lookup.b, curv)).b;
return diffuse;
}*/
/// REGION END - SUBSURFACE SCATTERING
// Upgrade NOTE: replaced 'defined SHADINGMODELID_CLEARCOAT' with 'defined (SHADINGMODELID_CLEARCOAT)'
// Upgrade NOTE: replaced 'defined SHADINGMODELID_CLOTH' with 'defined (SHADINGMODELID_CLOTH)'
// Upgrade NOTE: replaced 'defined SHADINGMODELID_EYE' with 'defined (SHADINGMODELID_EYE)'
// Upgrade NOTE: replaced 'defined SHADINGMODELID_FOLIAGE' with 'defined (SHADINGMODELID_FOLIAGE)'
// Upgrade NOTE: replaced 'defined SHADINGMODELID_HAIR' with 'defined (SHADINGMODELID_HAIR)'
// Upgrade NOTE: replaced 'defined SHADINGMODELID_SKIN' with 'defined (SHADINGMODELID_SKIN)'
// Upgrade NOTE: replaced 'defined SHADINGMODELID_SUBSURFACE' with 'defined (SHADINGMODELID_SUBSURFACE)'
// ------------------------------------------------------------------
// Shading models
//#pragma multi_compile SHADINGMODELID_UNLIT SHADINGMODELID_STANDARD SHADINGMODELID_SUBSURFACE SHADINGMODELID_SKIN SHADINGMODELID_FOLIAGE SHADINGMODELID_CLEARCOAT SHADINGMODELID_CLOTH SHADINGMODELID_EYE
// ------------------------------------------------------------------
// Input
half _ShadingModel;
sampler2D _AnisotropyMap;
half _Anisotropy;
sampler2D _TangentMap;
half4 _TranslucentColor;
sampler2D _TranslucencyMap;
sampler2D _FuzzTex;
half3 _FuzzColor;
half _Cloth;
sampler2D _IrisNormal;
sampler2D _IrisMask;
half _IrisDistance;
half _TDistortion;
half _TScale;
half _TAmbient;
half _TPower;
half _TAttenuation;
half _TransmissionOverallStrength;
// ------------------------------------------------------------------
// Maths helpers
// Octahedron Normal Vectors
// [Cigolle 2014, "A Survey of Efficient Representations for Independent Unit Vectors"]
// Mean Max
// oct 8:8 0.33709 0.94424
// snorm 8:8:8 0.17015 0.38588
// oct 10:10 0.08380 0.23467
// snorm 10:10:10 0.04228 0.09598
// oct 12:12 0.02091 0.05874
float2 UnitVectorToOctahedron(float3 N)
{
N.xy /= dot(float3(1,1,1), abs(N));
if (N.z <= 0)
{
N.xy = (1 - abs(N.yx)) * (N.xy >= 0 ? float2(1, 1) : float2(-1, -1));
}
return N.xy;
}
float3 OctahedronToUnitVector(float2 Oct)
{
float3 N = float3(Oct, 1 - dot(float2(1,1), abs(Oct)));
if (N.z < 0)
{
N.xy = (1 - abs(N.yx)) * (N.xy >= 0 ? float2(1, 1) : float2(-1, -1));
}
return float3(1, 1, 1);
return normalize(N);
}
// ------------------------------------------------------------------
// Surface helpers
half Anisotropy(float2 uv)
{
return tex2D(_AnisotropyMap, uv) * _Anisotropy;
}
half3 Fuzz(float2 uv)
{
return tex2D(_FuzzTex, uv) * _FuzzColor;
}
half Cloth()
{
return _Cloth;
}
half4 Iris(float2 uv)
{
float2 n = UnitVectorToOctahedron(normalize(UnpackNormal(tex2D(_IrisNormal, uv)).rgb)) * 0.5 + 0.5;
float m = saturate(tex2D(_IrisMask, uv).r); // Iris Mask
float d = saturate(_IrisDistance); // Iris Distance
return float4(n.x, n.y, m, d);
}
half3 Translucency(float2 uv)
{
return tex2D(_TranslucencyMap, uv).rgb * _TranslucentColor.rgb;
}
// ------------------------------------------------------------------
// Unlit Shading Function
float4 UnlitShading(float3 diffColor)
{
return half4(diffColor, 1);
}
// ------------------------------------------------------------------
// Standard Shading Function
float4 StandardShading(float3 diffColor, float3 specColor, float oneMinusReflectivity, float smoothness, float3 normal, float3x3 worldVectors,
float anisotropy, float metallic, float3 viewDir, UnityLight light, UnityIndirect gi)
{
//Unpack world vectors
float3 tangent = worldVectors[0];
float3 bitangent = worldVectors[1];
//Normal shift
float shiftAmount = dot(normal, viewDir);
normal = shiftAmount < 0.0f ? normal + viewDir * (-shiftAmount + 1e-5f) : normal;
//Regular vectors
float NdotL = saturate(dot(normal, light.dir)); //sat?
float NdotV = abs(dot(normal, viewDir)); //abs?
float LdotV = dot(light.dir, viewDir);
float3 H = Unity_SafeNormalize(light.dir + viewDir);
float invLenLV = rsqrt(abs(2 + 2 * normalize(LdotV)));
//float invLenLV = rsqrt(abs(2 + 2 * LdotV));
//float NdotH = (NdotL + normalize(NdotV)) * invLenLV;
float NdotH = saturate(dot(normal, H));
//float NdotH = saturate((NdotL + normalize(NdotV)) * invLenLV);
//float H = (light.dir + viewDir) * invLenLV;
float LdotH = saturate(dot(light.dir, H));
//Tangent vectors
float TdotH = dot(tangent, H);
float TdotL = dot(tangent, light.dir);
float BdotH = dot(bitangent, H);
float BdotL = dot(bitangent, light.dir);
float TdotV = dot(viewDir, tangent);
float BdotV = dot(viewDir, bitangent);
//Fresnels
half grazingTerm = saturate(smoothness + (1 - oneMinusReflectivity));
float3 F = FresnelLerp(specColor, grazingTerm, NdotV); //Original Schlick - Replace from SRP?
//float3 fresnel0 = lerp(specColor, diffColor, metallic);
//float3 F = FresnelSchlick(fresnel0, 1.0, LdotH);
//Calculate roughness
float roughnessT;
float roughnessB;
float perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);
float roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
ConvertAnisotropyToRoughness(roughness, anisotropy, roughnessT, roughnessB);
//Clamp roughness
//roughness = ClampRoughnessForAnalyticalLights(roughness);
roughnessT = ClampRoughnessForAnalyticalLights(roughnessT);
roughnessB = ClampRoughnessForAnalyticalLights(roughnessB);
//Visibility & Distribution terms
float V = SmithJointGGXAnisotropic(TdotV, BdotV, NdotV, TdotL, BdotL, NdotL, roughnessT, roughnessB);
float D = D_GGXAnisotropic(TdotH, BdotH, NdotH, roughnessT, roughnessB);
//Specular term
float3 specularTerm = V * D; //*UNITY_PI;
# ifdef UNITY_COLORSPACE_GAMMA
specularTerm = sqrt(max(1e-4h, specularTerm));
# endif
// specularTerm * nl can be NaN on Metal in some cases, use max() to make sure it's a sane value
specularTerm = max(0, specularTerm * NdotL);
#if defined(_SPECULARHIGHLIGHTS_OFF)
specularTerm = 0.0;
#endif
//Diffuse term
float diffuseTerm = DisneyDiffuse(NdotV, NdotL, LdotH, perceptualRoughness) * NdotL;// - Need this NdotL multiply?
//Reduction
half surfaceReduction;
# ifdef UNITY_COLORSPACE_GAMMA
surfaceReduction = 1.0 - 0.28*roughness*perceptualRoughness; // 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]
# else
surfaceReduction = 1.0 / (roughness*roughness + 1.0); // fade \in [0.5;1]
# endif
//Final
half3 color = (diffColor * (gi.diffuse + light.color * diffuseTerm))
+ specularTerm * light.color * FresnelTerm(specColor, LdotH)
+ surfaceReduction * gi.specular * FresnelLerp(specColor, grazingTerm, NdotV);
return half4(color, 1);
}
// ------------------------------------------------------------------
// Cloth Shading Function
//float3 ClothShading(FGBufferData GBuffer, float3 LobeRoughness, float3 LobeEnergy, float3 L, float3 V, half3 N)
float4 ClothShading(float3 diffColor, float3 specColor, float3 fuzzColor, float cloth, float oneMinusReflectivity, float smoothness, float3 normal, float3 viewDir, UnityLight light, UnityIndirect gi, float3x3 worldVectors, float anisotropy)
{
const float3 FuzzColor = saturate(fuzzColor);
const float Cloth = saturate(cloth);
//Regular vectors
float NdotL = saturate(dot(normal, light.dir)); //sat?
float NdotV = abs(dot(normal, viewDir)); //abs?
float LdotV = dot(light.dir, viewDir);
//float invLenLV = rsqrt(abs(2 + 2 * normalize(LdotV)));
////float invLenLV = rsqrt(abs(2 + 2 * LdotV));
//float NdotH = (NdotL + normalize(NdotV)) * invLenLV;
//float NdotH = saturate((NdotL + normalize(NdotV)) * invLenLV);
float3 H = Unity_SafeNormalize(light.dir + viewDir);
//float H = (light.dir + viewDir) * invLenLV;
float LdotH = saturate(dot(light.dir, H));
//float3 H = normalize(viewDir + light.dir);
//float NdotL = saturate(dot(normal, light.dir));
//float NdotV = saturate(abs(dot(normal, viewDir)) + 1e-5);
float NdotH = saturate(dot(normal, H));
float VdotH = saturate(dot(viewDir, H));
//float LdotH = saturate(dot(light.dir, H));
half grazingTerm = saturate(smoothness + (1 - oneMinusReflectivity));
// Diffuse
float perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);
float roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
float diffuseTerm = DisneyDiffuse(NdotV, NdotL, LdotH, perceptualRoughness) * NdotL;// - Need this NdotL multiply?
// Cloth - Asperity Scattering - Inverse Beckmann Layer
float3 F1 = FresnelTerm(fuzzColor, LdotH);// FresnelLerp(fuzzColor, grazingTerm, NdotV);// FresnelTerm(FuzzColor, LdotH);// F_Schlick(FuzzColor, VdotH);
float D1 = D_InvGGX(roughness, NdotH);
float V1 = Vis_Cloth(NdotV, NdotL);
//Specular term
float3 specularTerm1 = V1 * D1; //*UNITY_PI;
# ifdef UNITY_COLORSPACE_GAMMA
specularTerm1 = sqrt(max(1e-4h, specularTerm1));
# endif
// specularTerm * nl can be NaN on Metal in some cases, use max() to make sure it's a sane value
// specularTerm1 = max(0, specularTerm1 * NdotL);
#if defined(_SPECULARHIGHLIGHTS_OFF)
specularTerm1 = 0.0;
#endif
float3 Spec1 = specularTerm1 * light.color * FresnelTerm(fuzzColor, LdotH);
// Generalized microfacet specular
/*float3 F2 = F_Schlick(specColor, VdotH);
float D2 = D_GGX(roughness, NdotH);
float V2 = Vis_SmithJointApprox(roughness, NdotV, NdotL);
float3 Spec2 = D2 * V2 * F2 * light.color;*/
//Unpack world vectors
float3 tangent = worldVectors[0];
float3 bitangent = worldVectors[1];
//Tangent vectors
float TdotH = dot(tangent, H);
float TdotL = dot(tangent, light.dir);
float BdotH = dot(bitangent, H);
float BdotL = dot(bitangent, light.dir);
float TdotV = dot(viewDir, tangent);
float BdotV = dot(viewDir, bitangent);
//Fresnels
float3 F2 = FresnelLerp(specColor, grazingTerm, NdotV);// FresnelTerm(specColor, LdotH);// FresnelLerp(specColor, grazingTerm, NdotV); //Original Schlick - Replace from SRP?
float roughnessT;
float roughnessB;
//float perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);
//float roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
ConvertAnisotropyToRoughness(roughness, anisotropy, roughnessT, roughnessB);
//Clamp roughness
//roughness = ClampRoughnessForAnalyticalLights(roughness);
roughnessT = ClampRoughnessForAnalyticalLights(roughnessT);
roughnessB = ClampRoughnessForAnalyticalLights(roughnessB);
//Visibility & Distribution terms
float V2 = SmithJointGGXAnisotropic(TdotV, BdotV, NdotV, TdotL, BdotL, NdotL, roughnessT, roughnessB);
float D2 = D_GGXAnisotropic(TdotH, BdotH, NdotH, roughnessT, roughnessB);
//Specular term
float3 specularTerm2 = V2 * D2; //*UNITY_PI;
# ifdef UNITY_COLORSPACE_GAMMA
specularTerm2 = sqrt(max(1e-4h, specularTerm2));
# endif
// specularTerm * nl can be NaN on Metal in some cases, use max() to make sure it's a sane value
specularTerm2 = max(0, specularTerm2 * NdotL);
#if defined(_SPECULARHIGHLIGHTS_OFF)
specularTerm2 = 0.0;
#endif
float3 Spec2 = specularTerm2 * light.color * FresnelTerm(specColor, LdotH);
float3 Spec = lerp(Spec2, Spec1, Cloth);
//Reduction
half surfaceReduction;
# ifdef UNITY_COLORSPACE_GAMMA
surfaceReduction = 1.0 - 0.28*roughness*perceptualRoughness; // 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]
# else
surfaceReduction = 1.0 / (roughness*roughness + 1.0); // fade \in [0.5;1]
# endif
//Final
//half grazingTerm = saturate(smoothness + (1 - oneMinusReflectivity));
half3 color = (diffColor * (gi.diffuse + light.color * diffuseTerm))
+ Spec
+ surfaceReduction * gi.specular * FresnelLerp(specColor, grazingTerm, NdotV);
return half4(color, 1);
}
// ------------------------------------------------------------------
// Eye Shading Function
//float3 EyeShading(FGBufferData GBuffer, float3 LobeRoughness, float3 LobeEnergy, float3 L, float3 V, half3 N)
float4 EyeShading(float3 diffColor, float3 specColor, float3 viewDir, half3 normal, float smoothness, float oneMinusReflectivity, UnityLight light, UnityIndirect gi)
{
float3 H = normalize(viewDir + light.dir);
float NdotL = saturate(dot(normal, light.dir));
float NdotV = saturate(abs(dot(normal, viewDir)) + 1e-5);
float NdotH = saturate(dot(normal, H));
float VdotH = saturate(dot(viewDir, H));
float LdotH = saturate(dot(light.dir, H));
// Generalized microfacet specular
float perceptualRoughness = SmoothnessToPerceptualRoughness(smoothness);
float roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
float D = D_GGX(roughness, NdotH);// *LobeEnergy[1];
float V = Vis_SmithJointApprox(roughness, NdotV, NdotL);
float3 F = F_Schlick(specColor, VdotH);
float3 specularTerm = V * D; //*UNITY_PI;
# ifdef UNITY_COLORSPACE_GAMMA
specularTerm = sqrt(max(1e-4h, specularTerm));
# endif
// specularTerm * nl can be NaN on Metal in some cases, use max() to make sure it's a sane value
specularTerm = max(0, specularTerm * NdotL);
#if defined(_SPECULARHIGHLIGHTS_OFF)
specularTerm = 0.0;
#endif
half grazingTerm = saturate(smoothness + (1 - oneMinusReflectivity));
half surfaceReduction;
# ifdef UNITY_COLORSPACE_GAMMA
surfaceReduction = 1.0 - 0.28*roughness*perceptualRoughness; // 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]
# else
surfaceReduction = 1.0 / (roughness*roughness + 1.0); // fade \in [0.5;1]
# endif
float diffuseTerm = DisneyDiffuse(NdotV, NdotL, LdotH, perceptualRoughness) * NdotL; // TODO - Unreal does not apply diffuse in Shading function
//Final
half3 color = (diffColor * (gi.diffuse + light.color * diffuseTerm))
+ specularTerm * light.color * FresnelTerm(specColor, LdotH)
+ surfaceReduction * gi.specular * FresnelLerp(specColor, grazingTerm, NdotV);
return half4(color, 1);
}
// ------------------------------------------------------------------
// Subsurface Shading Function
float3 SubsurfaceShadingSimple(float3 diffColor, float3 normal, float3 viewDir, float3 thickness, UnityLight light)
{
half3 vLTLight = light.dir + normal * _TDistortion;
half fLTDot = pow(saturate(dot(viewDir, -vLTLight)), _TPower) * _TScale;
half3 fLT = _TAttenuation * (fLTDot + _TAmbient) * (thickness);
return diffColor * ((light.color * fLT) * _TransmissionOverallStrength);
}
// ------------------------------------------------------------------
// Eye Subsurface Shading Function
//float3 EyeSubsurfaceShading(FGBufferData GBuffer, float3 L, float3 V, half3 N)
float3 EyeSubsurfaceShading(float3 diffColor, float3 specColor, float3 viewDir, half3 normal, float smoothness, float4 iris, UnityLight light)
{
float2 irisNormal = iris.rg;
float irisMask = iris.z;
float irisDistance = iris.w;
float3 H = normalize(viewDir + light.dir);
float VdotH = saturate(dot(viewDir, H));
float NdotV = saturate(abs(dot(normal, viewDir)) + 1e-5);
float LdotH = saturate(dot(light.dir, H));
// F_Schlick
//float F0 = GBuffer.Specular * 0.08;
//float Fc = Pow5(1 - VoH);
//float F = Fc + (1 - Fc) * F0;
float3 fresnel0 = lerp(specColor, diffColor, smoothness);
float3 F = FresnelSchlick(fresnel0, 1.0, LdotH);
//float IrisDistance = GBuffer.CustomData.w;
//float IrisMask = GBuffer.CustomData.z;
float3 IrisNormal;
IrisNormal = OctahedronToUnitVector(irisNormal * 2 - 1);
// Blend in the negative intersection normal to create some concavity
// Not great as it ties the concavity to the convexity of the cornea surface
// No good justification for that. On the other hand, if we're just looking to
// introduce some concavity, this does the job.
float3 CausticNormal = normalize(lerp(IrisNormal, -normal, irisMask*irisDistance));
float NdotL = saturate(dot(IrisNormal, light.dir));
float Power = lerp(12, 1, NdotL);
float Caustic = 0.6 + 0.2 * (Power + 1) * pow(saturate(dot(CausticNormal, light.dir)), Power);
float Iris = NdotL * Caustic;
// http://blog.stevemcauley.com/2011/12/03/energy-conserving-wrapped-diffuse/
float Wrap = 0.15;
float Sclera = saturate((dot(normal, light.dir) + Wrap) / (1 + Wrap) * (1 + Wrap));
return (1 - F) * lerp(Sclera, Iris, irisMask) * diffColor / UNITY_PI;
}
// ------------------------------------------------------------------
// Shading function selectors
//float3 SurfaceShading(/*FGBufferData GBuffer,*/ float3 LobeRoughness, float3 LobeEnergy, float3 L, float3 V, half3 N, uint2 Random)
float4 SurfaceShading(float3 diffColor, float3 specColor, float oneMinusReflectivity, float smoothness, float3 normal,
float3x3 worldVectors, float anisotropy, float4 customData, float metallic, float3 viewDir, UnityLight light, UnityIndirect gi)
{
#if defined(SHADINGMODELID_UNLIT)
{
return UnlitShading(diffColor);
}
#elif defined(SHADINGMODELID_STANDARD) || defined(SHADINGMODELID_SUBSURFACE) || defined(SHADINGMODELID_SKIN) || defined(SHADINGMODELID_FOLIAGE)
{
return StandardShading(diffColor, specColor, oneMinusReflectivity, smoothness,
normal, worldVectors, anisotropy, metallic, viewDir, light, gi);
}
#elif defined (SHADINGMODELID_CLEARCOAT)
{
return float4(1, 1, 1, 1); //ClearCoatShading(GBuffer, LobeRoughness, LobeEnergy, L, V, N);
}
#elif defined (SHADINGMODELID_CLOTH)
{
return ClothShading(diffColor, specColor, customData.rgb, customData.a, oneMinusReflectivity, smoothness, normal, viewDir, light, gi, worldVectors, anisotropy);
}
#elif defined (SHADINGMODELID_EYE)
{
return EyeShading(diffColor, specColor, viewDir, normal, smoothness, oneMinusReflectivity, light, gi); //EyeShading(GBuffer, LobeRoughness, LobeEnergy, L, V, N);
}
#endif
return float4(0, 0, 0, 0);
}
//float3 SubsurfaceShading(/*FGBufferData GBuffer,*/ float3 L, float3 V, half3 N, float Shadow, uint2 Random)
float3 SubsurfaceShading(float3 diffColor, float3 specColor, float3 normal, float smoothness, float3 viewDir, float4 customData, UnityLight light)
{
#if defined (SHADINGMODELID_SUBSURFACE)
{
return SubsurfaceShadingSimple(diffColor, normal, viewDir, customData.rgb, light);
}
#elif defined (SHADINGMODELID_SKIN)
{
return float3(0, 0, 0); //SubsurfaceShadingPreintegratedSkin(GBuffer, L, V, N);
}
#elif defined (SHADINGMODELID_FOLIAGE)
{
return float3(0, 0, 0); //SubsurfaceShadingTwoSided(SubsurfaceColor, L, V, N);
}
#elif defined (SHADINGMODELID_HAIR)
{
return float3(0, 0, 0); //HairShading(GBuffer, L, V, N, Shadow, 1, 0, Random);
}
#elif defined (SHADINGMODELID_EYE)
{
return EyeSubsurfaceShading(diffColor, specColor, viewDir, normal, smoothness, customData, light); //EyeSubsurfaceShading(GBuffer, L, V, N);
}
#endif
return float3(0, 0, 0);
}
//#endif UNITY_ADVANCED_SHADINGMODELS_INCLUDED
//-------------------------------------------------------------------------------------
// Lighting Helpers
// Glossy Environment
half3 Unity_AnisotropicGlossyEnvironment(UNITY_ARGS_TEXCUBE(tex), half4 hdr, Unity_GlossyEnvironmentData glossIn, half anisotropy) //Reference IBL from HD Pipe (Add half3 L input and replace R)
{
half perceptualRoughness = glossIn.roughness /* perceptualRoughness */;
// TODO: CAUTION: remap from Morten may work only with offline convolution, see impact with runtime convolution!
// For now disabled
#if 0
float m = PerceptualRoughnessToRoughness(perceptualRoughness); // m is the real roughness parameter
const float fEps = 1.192092896e-07F; // smallest such that 1.0+FLT_EPSILON != 1.0 (+1e-4h is NOT good here. is visibly very wrong)
float n = (2.0 / max(fEps, m*m)) - 2.0; // remap to spec power. See eq. 21 in --> https://dl.dropboxusercontent.com/u/55891920/papers/mm_brdf.pdf
n /= 4; // remap from n_dot_h formulatino to n_dot_r. See section "Pre-convolved Cube Maps vs Path Tracers" --> https://s3.amazonaws.com/docs.knaldtech.com/knald/1.0.0/lys_power_drops.html
perceptualRoughness = pow(2 / (n + 2), 0.25); // remap back to square root of real roughness (0.25 include both the sqrt root of the conversion and sqrt for going from roughness to perceptualRoughness)
#else
// MM: came up with a surprisingly close approximation to what the #if 0'ed out code above does.
perceptualRoughness = perceptualRoughness*(1.7 - 0.7*perceptualRoughness);
#endif
half mip = perceptualRoughnessToMipmapLevel(perceptualRoughness);
half3 R = glossIn.reflUVW;// -half3(anisotropy, 0, 0);
half4 rgbm = UNITY_SAMPLE_TEXCUBE_LOD(tex, R, mip);
return DecodeHDR(rgbm, hdr);
}
// Indirect Specular
inline half3 UnityGI_AnisotropicIndirectSpecular(UnityGIInput data, half occlusion, Unity_GlossyEnvironmentData glossIn, half anisotropy, half3x3 worldVectors)
{
half3 specular;
float3 tangentX = worldVectors[0];
float3 tangentY = worldVectors[1];
float3 N = worldVectors[2];
float3 V = data.worldViewDir;
float3 iblNormalWS = GetAnisotropicModifiedNormal(tangentY, N, V, anisotropy);
float3 iblR = reflect(-V, iblNormalWS);
#ifdef UNITY_SPECCUBE_BOX_PROJECTION
// we will tweak reflUVW in glossIn directly (as we pass it to Unity_GlossyEnvironment twice for probe0 and probe1), so keep original to pass into BoxProjectedCubemapDirection
half3 originalReflUVW = glossIn.reflUVW;
glossIn.reflUVW = BoxProjectedCubemapDirection(iblR, data.worldPos, data.probePosition[0], data.boxMin[0], data.boxMax[0]);
#endif
#ifdef _GLOSSYREFLECTIONS_OFF
specular = unity_IndirectSpecColor.rgb;
#else
half3 env0 = Unity_AnisotropicGlossyEnvironment(UNITY_PASS_TEXCUBE(unity_SpecCube0), data.probeHDR[0], glossIn, anisotropy);
//half3 env0 = Unity_AnisotropicGlossyEnvironment(UNITY_PASS_TEXCUBE(unity_SpecCube0), data.probeHDR[0], glossIn, anisotropy, L); //Reference IBL from HD Pipe
#ifdef UNITY_SPECCUBE_BLENDING
const float kBlendFactor = 0.99999;
float blendLerp = data.boxMin[0].w;
UNITY_BRANCH
if (blendLerp < kBlendFactor)
{
#ifdef UNITY_SPECCUBE_BOX_PROJECTION
glossIn.reflUVW = BoxProjectedCubemapDirection(iblR, data.worldPos, data.probePosition[1], data.boxMin[1], data.boxMax[1]);
#endif
half3 env1 = Unity_AnisotropicGlossyEnvironment(UNITY_PASS_TEXCUBE_SAMPLER(unity_SpecCube1, unity_SpecCube0), data.probeHDR[1], glossIn, anisotropy);
//half3 env1 = Unity_AnisotropicGlossyEnvironment(UNITY_PASS_TEXCUBE_SAMPLER(unity_SpecCube1, unity_SpecCube0), data.probeHDR[1], glossIn, anisotropy, L); //Reference IBL from HD Pipe
specular = lerp(env1, env0, blendLerp);
}
else
{
specular = env0;
}
#else
specular = env0;
#endif
#endif
return specular * occlusion;// *weightOverPdf; //Reference IBL from HD Pipe
//return specular * occlusion * weightOverPdf; //Reference IBL from HD Pipe
}
// Global Illumination
inline UnityGI UnityAnisotropicGlobalIllumination(UnityGIInput data, half occlusion, half3 normalWorld, Unity_GlossyEnvironmentData glossIn, half anisotropy, half3x3 worldVectors)
{
UnityGI o_gi = UnityGI_Base(data, occlusion, normalWorld);
o_gi.indirect.specular = UnityGI_AnisotropicIndirectSpecular(data, occlusion, glossIn, anisotropy, worldVectors);
return o_gi;
}
//-------------------------------------------------------------------------------------
// Lighting Functions
//Surface Description
struct SurfaceOutputAdvanced
{
fixed3 Albedo; // base (diffuse or specular) color
fixed3 Normal; // tangent space normal, if written
half3 Emission;
half Metallic; // 0=non-metal, 1=metal
// Smoothness is the user facing name, it should be perceptual smoothness but user should not have to deal with it.
// Everywhere in the code you meet smoothness it is perceptual smoothness
half Smoothness; // 0=rough, 1=smooth
half Occlusion; // occlusion (default 1)
fixed Alpha; // alpha for transparencies
half3 Tangent;
half Anisotropy;
half4 CustomData;
float3x3 WorldVectors;
//half ShadingModel;
};
inline half4 LightingAdvanced(SurfaceOutputAdvanced s, half3 viewDir, UnityGI gi)
{
s.Normal = normalize(s.Normal);
half oneMinusReflectivity;
half3 specColor;
s.Albedo = DiffuseAndSpecularFromMetallic(s.Albedo, s.Metallic, /*out*/ specColor, /*out*/ oneMinusReflectivity);
// shader relies on pre-multiply alpha-blend (_SrcBlend = One, _DstBlend = OneMinusSrcAlpha)
// this is necessary to handle transparency in physically correct way - only diffuse component gets affected by alpha
half outputAlpha;
s.Albedo = PreMultiplyAlpha(s.Albedo, s.Alpha, oneMinusReflectivity, /*out*/ outputAlpha);
half4 c = SurfaceShading(s.Albedo, specColor, oneMinusReflectivity, s.Smoothness, s.Normal, s.WorldVectors, s.Anisotropy, s.CustomData, s.Metallic, viewDir, gi.light, gi.indirect);
c.rgb += SubsurfaceShading(s.Albedo, specColor, s.Normal, s.Smoothness, viewDir, s.CustomData, gi.light);
//c.rgb += UNITY_BRDF_GI(s.Albedo, specColor, oneMinusReflectivity, s.Smoothness, s.Normal, viewDir, s.Occlusion, gi);
c.a = outputAlpha;
return c;
}
//This is pointless as always forward?
inline half4 LightingAdvanced_Deferred(SurfaceOutputAdvanced s, half3 viewDir, UnityGI gi, out half4 outGBuffer0, out half4 outGBuffer1, out half4 outGBuffer2)
{
half oneMinusReflectivity;
half3 specColor;
s.Albedo = DiffuseAndSpecularFromMetallic(s.Albedo, s.Metallic, /*out*/ specColor, /*out*/ oneMinusReflectivity);
half4 c = SurfaceShading(s.Albedo, specColor, oneMinusReflectivity, s.Smoothness, s.Normal, s.WorldVectors, s.Anisotropy, s.CustomData, s.Metallic, viewDir, gi.light, gi.indirect);
c.rgb += SubsurfaceShading(s.Albedo, specColor, s.Normal, s.Smoothness, viewDir, s.CustomData, gi.light);
UnityStandardData data;
data.diffuseColor = s.Albedo;
data.occlusion = s.Occlusion;
data.specularColor = specColor;
data.smoothness = s.Smoothness;
data.normalWorld = s.Normal;
UnityStandardDataToGbuffer(data, outGBuffer0, outGBuffer1, outGBuffer2);
half4 emission = half4(s.Emission + c.rgb, 1);
return emission;
}
inline void LightingAdvanced_GI(SurfaceOutputAdvanced s, UnityGIInput data, inout UnityGI gi)
{
#if defined(UNITY_PASS_DEFERRED) && UNITY_ENABLE_REFLECTION_BUFFERS
gi = UnityGlobalIllumination(data, s.Occlusion, s.Normal);
#else
Unity_GlossyEnvironmentData g = UnityGlossyEnvironmentSetup(s.Smoothness, data.worldViewDir, s.Normal, lerp(unity_ColorSpaceDielectricSpec.rgb, s.Albedo, s.Metallic));
gi = UnityAnisotropicGlobalIllumination(data, s.Occlusion, s.Normal, g, s.Anisotropy, s.WorldVectors);
#endif
}
///END
#pragma target 5.0
#pragma surface surf Advanced vertex:vert
#pragma glsl
#pragma debug
float4 Color_eb55295a_2a33_4a48_b612_9d279e2cf480_Uniform;
float Vector1_58a74627_6519_4fc6_ac27_ff4e37beadf7_Uniform;
struct Input
{
float4 color : COLOR;
float4 worldTangent;
float3 worldNormal;
};
void vert (inout appdata_full v, out Input o)
{
UNITY_INITIALIZE_OUTPUT(Input,o);
o.worldTangent = float4(UnityObjectToWorldDir(v.tangent.xyz), v.tangent.w);
}
void surf (Input IN, inout SurfaceOutputAdvanced o)
{
float3 worldSpaceTangent = normalize(IN.worldTangent.xyz);
float3 worldSpaceNormal = normalize(IN.worldNormal);
float3 worldSpaceBitangent = cross(worldSpaceNormal, worldSpaceTangent) * IN.worldTangent.w;
o.Albedo = Color_eb55295a_2a33_4a48_b612_9d279e2cf480_Uniform;
o.Metallic = Vector1_58a74627_6519_4fc6_ac27_ff4e37beadf7_Uniform;
o.Smoothness = Vector1_58a74627_6519_4fc6_ac27_ff4e37beadf7_Uniform;
o.Anisotropy = Vector1_58a74627_6519_4fc6_ac27_ff4e37beadf7_Uniform;
o.WorldVectors = float3x3(worldSpaceTangent, worldSpaceBitangent, worldSpaceNormal);
}
ENDCG
}
FallBack "Diffuse"
}

10
MaterialGraphProject/Assets/GeneratedShader.shader.meta


fileFormatVersion: 2
guid: 4afc3341bed83d34cb1aebb7e98d8751
timeCreated: 1495619733
licenseType: Pro
ShaderImporter:
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

1
MaterialGraphProject/Assets/Matt/ClothMaster.ShaderGraph
文件差异内容过多而无法显示
查看文件

9
MaterialGraphProject/Assets/Matt/ClothMaster.ShaderGraph.meta


fileFormatVersion: 2
guid: c6f272d98c8edc642b85922a6d8ffe9c
timeCreated: 1495626442
licenseType: Pro
ScriptedImporter:
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 625f186215c104763be7675aa2d941aa, type: 3}

96
MaterialGraphProject/Assets/Matt/ClothMasterNode.cs


using System;
using UnityEngine.Graphing;
namespace UnityEngine.MaterialGraph
{
[Serializable]
[Title("Master/Cloth")]
public class ClothMasterNode : AbstractAdvancedMasterNode
{
//public const string MetallicSlotName = "Metallic";
//public const int MetallicSlotId = 2;
public const string FuzzSlotName = "Fuzz";
public const int FuzzSlotId = 9;
public const string ClothFactorSlotName = "ClothFactor";
public const int ClothFactorSlotId = 10;
public const string LightFunctionName = "Advanced";
public const string SurfaceOutputStructureName = "SurfaceOutputAdvanced";
public ClothMasterNode()
{
name = "Cloth";
UpdateNodeAfterDeserialization();
}
public override string GetMaterialID()
{
return "SHADINGMODELID_CLOTH";
}
public override int[] GetCustomDataSlots()
{
return new int[] { 9, 10 };
}
public override string[] GetCustomData()
{
string fuzzInput = GetVariableNameForSlotAtId(9);
if (fuzzInput == "")
fuzzInput = "float3(0,0,0)";
else
fuzzInput = fuzzInput + ".rgb";
string clothFactorInput = GetVariableNameForSlotAtId(10);
if (clothFactorInput == "")
clothFactorInput = "0";
else
clothFactorInput = clothFactorInput + ".r";
return new string[] { "o.CustomData = float4(" + fuzzInput + ", "+ clothFactorInput + ");" };
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
//AddSlot(new MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(AnisotropySlotId, AnisotropySlotName, AnisotropySlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(TangentSlotId, TangentSlotName, TangentSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(AnisotropySlotId, AnisotropySlotName, AnisotropySlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(FuzzSlotId, FuzzSlotName, FuzzSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(ClothFactorSlotId, ClothFactorSlotName, ClothFactorSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
//MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
AnisotropySlotId,
TangentSlotId,
FuzzSlotId,
ClothFactorSlotId
});
}
public override string GetSurfaceOutputName()
{
return SurfaceOutputStructureName;
}
public override string GetLightFunction()
{
return LightFunctionName;
}
}
}

12
MaterialGraphProject/Assets/Matt/ClothMasterNode.cs.meta


fileFormatVersion: 2
guid: 4a9c7c58817be884f8b788d9e11dbef0
timeCreated: 1478188276
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

1
MaterialGraphProject/Assets/Matt/SubsurfaceMaster.ShaderGraph
文件差异内容过多而无法显示
查看文件

9
MaterialGraphProject/Assets/Matt/SubsurfaceMaster.ShaderGraph.meta


fileFormatVersion: 2
guid: 25497a67e7ee41d4c8f2039c1df994a1
timeCreated: 1495614205
licenseType: Pro
ScriptedImporter:
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 625f186215c104763be7675aa2d941aa, type: 3}

86
MaterialGraphProject/Assets/Matt/SubsurfaceMetallicMasterNode.cs


using System;
using UnityEngine.Graphing;
namespace UnityEngine.MaterialGraph
{
[Serializable]
[Title("Master/SubsurfaceMetallic")]
public class SubsurfaceMetallicMasterNode : AbstractAdvancedMasterNode
{
public const string MetallicSlotName = "Metallic";
public const int MetallicSlotId = 2;
public const string TranslucencySlotName = "Translucency";
public const int TranslucencySlotId = 9;
public const string LightFunctionName = "Advanced";
public const string SurfaceOutputStructureName = "SurfaceOutputAdvanced";
public SubsurfaceMetallicMasterNode()
{
name = "SubsurfaceMetallic";
UpdateNodeAfterDeserialization();
}
public override string GetMaterialID()
{
return "SHADINGMODELID_SUBSURFACE";
}
public override int[] GetCustomDataSlots()
{
return new int[] { 9 };
}
public override string[] GetCustomData()
{
string translucencyInput = GetVariableNameForSlotAtId(9);
if (translucencyInput == "")
translucencyInput = "float3(0,0,0)";
else
translucencyInput = translucencyInput + ".rgb";
return new string[] { "o.CustomData = float4(" + translucencyInput + ", 0);" };
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(AnisotropySlotId, AnisotropySlotName, AnisotropySlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(TangentSlotId, TangentSlotName, TangentSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
AddSlot(new MaterialSlot(AnisotropySlotId, AnisotropySlotName, AnisotropySlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
AddSlot(new MaterialSlot(TranslucencySlotId, TranslucencySlotName, TranslucencySlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
AnisotropySlotId,
TangentSlotId,
TranslucencySlotId
});
}
public override string GetSurfaceOutputName()
{
return SurfaceOutputStructureName;
}
public override string GetLightFunction()
{
return LightFunctionName;
}
}
}

12
MaterialGraphProject/Assets/Matt/SubsurfaceMetallicMasterNode.cs.meta


fileFormatVersion: 2
guid: 7c541e9dc2ccc50469af225259c7cb17
timeCreated: 1478188276
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

202
MaterialGraphProject/Assets/NewNodes/WIP/MultiLayerParallaxNode.cs


using UnityEngine.Graphing;
namespace UnityEngine.MaterialGraph
{
[Title("UV/MultiLayerParallax")]
public class MultiLayerParallaxNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV, IMayRequireViewDirectionTangentSpace
{
protected const string kInputDepthShaderName = "Depth";
protected const string kInputFadeRateShaderName = "FadeRate";
protected const string kInputLayerCountShaderName = "LayerCount";
protected const string kTextureSlotShaderName = "Texture";
protected const string kOutputSlotShaderName = "Result";
public const int InputDepthSlotId = 0; // 'depth'
public const int InputFadeRateSlotId = 1; // 'fade_rate'
public const int InputLayerCountSlotId = 2; // 'layer_count'
public const int TextureSlotId = 3; // 'tex'
public const int OutputSlotId = 4; // 'result'
public override bool hasPreview
{
get { return true; }
}
public override PreviewMode previewMode
{
get
{
return PreviewMode.Preview3D;
}
}
public MultiLayerParallaxNode()
{
name = "MultiLayerParallax";
UpdateNodeAfterDeserialization();
}
public string GetFunctionName()
{
return "unity_multilayer_parallax_" + precision;
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(GetInputDepthSlot());
AddSlot(GetInputFadeRateSlot());
AddSlot(GetInputLayerCountSlot());
AddSlot(GetTextureSlot());
AddSlot(GetOutputSlot());
RemoveSlotsNameNotMatching(validSlots);
}
protected int[] validSlots
{
get { return new[] { InputDepthSlotId, InputFadeRateSlotId, InputLayerCountSlotId, TextureSlotId, OutputSlotId }; }
}
protected virtual MaterialSlot GetInputDepthSlot()
{
return new MaterialSlot(InputDepthSlotId, GetInputSlot1Name(), kInputDepthShaderName, SlotType.Input, SlotValueType.Vector1, Vector4.zero);
}
protected virtual MaterialSlot GetInputFadeRateSlot()
{
return new MaterialSlot(InputFadeRateSlotId, GetInputSlot2Name(), kInputFadeRateShaderName, SlotType.Input, SlotValueType.Dynamic, Vector4.zero);
}
protected virtual MaterialSlot GetInputLayerCountSlot()
{
return new MaterialSlot(InputLayerCountSlotId, GetInputSlot3Name(), kInputLayerCountShaderName, SlotType.Input, SlotValueType.Dynamic, Vector4.zero);
}
protected virtual MaterialSlot GetTextureSlot()
{
return new MaterialSlot(TextureSlotId, GetTextureSlotName(), kTextureSlotShaderName, SlotType.Input, SlotValueType.sampler2D, Vector4.zero);
}
protected virtual MaterialSlot GetOutputSlot()
{
return new MaterialSlot(OutputSlotId, GetOutputSlotName(), kOutputSlotShaderName, SlotType.Output, SlotValueType.Dynamic, Vector4.zero);
}
protected virtual string GetInputSlot1Name()
{
return kInputDepthShaderName;
}
protected virtual string GetInputSlot2Name()
{
return kInputFadeRateShaderName;
}
protected virtual string GetInputSlot3Name()
{
return kInputLayerCountShaderName;
}
protected virtual string GetTextureSlotName()
{
return kTextureSlotShaderName;
}
protected virtual string GetOutputSlotName()
{
return kOutputSlotShaderName;
}
private string input1Dimension
{
get { return ConvertConcreteSlotValueTypeToString(FindInputSlot<MaterialSlot>(InputDepthSlotId).concreteValueType); }
}
private string input2Dimension
{
get { return ConvertConcreteSlotValueTypeToString(FindInputSlot<MaterialSlot>(InputFadeRateSlotId).concreteValueType); }
}
private string input3Dimension
{
get { return ConvertConcreteSlotValueTypeToString(FindInputSlot<MaterialSlot>(InputLayerCountSlotId).concreteValueType); }
}
public string outputDimension
{
get { return ConvertConcreteSlotValueTypeToString(FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType); }
}
protected virtual string GetFunctionPrototype(string depth, string fadeRate, string layerCount, string tex, string UVs, string viewTangentSpace)
{
return "inline " + precision + outputDimension + " " + GetFunctionName() + " (" +
precision + input1Dimension + " " + depth + ", " +
precision + input2Dimension + " " + fadeRate + ", " +
precision + input3Dimension + " " + layerCount + ", " +
"sampler2D " + tex + ", " +
precision + "2 " + UVs + ", " +
precision + "3 " + viewTangentSpace + ")";
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
NodeUtils.SlotConfigurationExceptionIfBadConfiguration(this, new[] { InputDepthSlotId, InputFadeRateSlotId, InputLayerCountSlotId, TextureSlotId }, new[] { OutputSlotId });
string depthValue = GetSlotValue(InputDepthSlotId, generationMode);
string fadeRateValue = GetSlotValue(InputFadeRateSlotId, generationMode);
string layerCountValue = GetSlotValue(InputLayerCountSlotId, generationMode);
string textureValue = GetSlotValue(TextureSlotId, generationMode);
visitor.AddShaderChunk(
precision + outputDimension + " " + GetVariableNameForSlot(OutputSlotId) +
" = " + GetFunctionCallBody(depthValue, fadeRateValue, layerCountValue, textureValue) + ";", true);
}
public void GenerateNodeFunction(ShaderGenerator visitor, GenerationMode generationMode)
{
var outputString = new ShaderGenerator();
outputString.AddShaderChunk(GetFunctionPrototype("depth", "fadeRate", "layerCount", "tex", "UVs", "viewTangentSpace"), false);
outputString.AddShaderChunk("{", false);
outputString.Indent();
outputString.AddShaderChunk(precision + "2 texcoord = UVs;", false);
outputString.AddShaderChunk(precision + "2 offset = -viewTangentSpace.xy * depth / layerCount;", false);
outputString.AddShaderChunk(precision + outputDimension + " result = 0.0f;", false);
outputString.AddShaderChunk(precision + outputDimension + " fade = 1.0f;", false);
outputString.AddShaderChunk(precision + " alpha = 0.0f;", false);
outputString.AddShaderChunk("for (int i = 0; i < 10; i++) {", false);
outputString.Indent();
outputString.AddShaderChunk("result += fade * tex2D(tex, texcoord);", false);
outputString.AddShaderChunk("texcoord += offset;", false);
outputString.AddShaderChunk("fade *= fadeRate;", false);
outputString.Deindent();
outputString.AddShaderChunk("}", false);
outputString.AddShaderChunk("return result / layerCount;", false);
outputString.Deindent();
outputString.AddShaderChunk("}", false);
visitor.AddShaderChunk(outputString.GetShaderString(0), true);
}
protected virtual string GetFunctionCallBody(string depthValue, string fadeRateValue, string layerCountValue, string texValue)
{
return GetFunctionName() + " (" +
depthValue + ", " +
fadeRateValue + ", " +
layerCountValue + ", " +
texValue + ", " +
UVChannel.uv0.GetUVName() + ", " +
ShaderGeneratorNames.TangentSpaceViewDirection + ")";
}
public bool RequiresMeshUV(UVChannel channel)
{
return channel == UVChannel.uv0;
}
public bool RequiresViewDirectionTangentSpace()
{
return true;
}
}
}

12
MaterialGraphProject/Assets/NewNodes/WIP/MultiLayerParallaxNode.cs.meta


fileFormatVersion: 2
guid: 1970e51ab882ec24cb06ec8cbbefd184
timeCreated: 1495557243
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存