浏览代码

Merge pull request #144 (Upgrade to use new shader library)

Also includes WIP HD Unlit Master Node
/main
GitHub 7 年前
当前提交
c3ae833e
共有 78 个文件被更改,包括 1384 次插入1756 次删除
  1. 8
      MaterialGraphProject/Assets/LightweightAsset.asset
  2. 11
      MaterialGraphProject/Assets/UnityShaderEditor.meta
  3. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorMaterialSlot.cs
  4. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorRGBMaterialSlot.cs
  5. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapShaderProperty.cs
  6. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs
  7. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs.meta
  8. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SamplerStateShaderProperty.cs
  9. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TextureShaderProperty.cs
  10. 22
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs
  11. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs
  12. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs
  13. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/ColorNode.cs
  14. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs
  15. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs
  16. 32
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs
  17. 14
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/GraphUtil.cs
  18. 53
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGenerator.cs
  19. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/DefaultShaderIncludes.cs
  20. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources.meta
  21. 92
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template
  22. 96
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template
  23. 28
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template
  24. 2
      MaterialGraphProject/UnityPackageManager/manifest.json
  25. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs
  26. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs
  27. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline.meta
  28. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes.meta
  29. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs
  30. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs.meta
  31. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs
  32. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs.meta
  33. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs
  34. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs.meta
  35. 74
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template
  36. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template.meta
  37. 8
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary.meta
  38. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs.meta
  39. 204
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs
  40. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs
  41. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs.meta
  42. 14
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl
  43. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl.meta
  44. 173
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl
  45. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl.meta
  46. 15
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl
  47. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl.meta
  48. 279
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl
  49. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl.meta
  50. 192
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl
  51. 10
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl.meta
  52. 21
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl
  53. 10
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl.meta
  54. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs.meta
  55. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SpecularMasterNode.cs.meta
  56. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs.meta
  57. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs.meta
  58. 97
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs
  59. 156
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs
  60. 88
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs
  61. 87
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SpecularMasterNode.cs
  62. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/2DPreview.template.meta
  63. 54
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/2DPreview.template
  64. 46
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/ExportTexture.template
  65. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/ExportTexture.template.meta
  66. 872
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/advancedSubshader.template
  67. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/advancedSubshader.template.meta
  68. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/LightWeightShaderPaths.cs.meta
  69. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/LightWeightShaderPaths.cs
  70. 26
      MaterialGraphProject/Assets/Beachball.mat
  71. 8
      MaterialGraphProject/Assets/Beachball.mat.meta
  72. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs.meta
  73. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs.meta
  74. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs
  75. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs

8
MaterialGraphProject/Assets/LightweightAsset.asset


m_EditorClassIdentifier:
m_MaxPixelLights: 4
m_SupportsVertexLight: 0
m_SupportSoftParticles: 0
m_RequireCameraDepthTexture: 0
m_MSAA: 4
m_RenderScale: 1
m_ShadowType: 1

m_DefaultShader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
m_BlitShader: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3}
m_CopyDepthShader: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3}
m_DefaultMaterial: {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d, type: 2}
m_DefaultParticleMaterial: {fileID: 2100000, guid: e823cd5b5d27c0f4b8256e7c12ee3e6d,
type: 2}
m_DefaultTerrainMaterial: {fileID: 2100000, guid: 594ea882c5a793440b60ff72d896021e,
type: 2}
m_ResourceAsset: {fileID: 11400000, guid: c8afc0a27fb8c0b4da18151c689a1082, type: 2}

11
MaterialGraphProject/Assets/UnityShaderEditor.meta


fileFormatVersion: 2
guid: b100142c357c2d745b9707d6e2f987fd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 0b601fe23f0347ab8e4892edf2cf76d7
timeCreated: 1513757926

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorMaterialSlot.cs


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return string.Format("IsGammaSpace() ? {0}4({1}, {2}, {3}, {4}) : {0}4 (GammaToLinearSpace({0}3({1}, {2}, {3})), {4})"
return string.Format("IsGammaSpace() ? {0}4({1}, {2}, {3}, {4}) : {0}4 (SRGBToLinear({0}3({1}, {2}, {3})), {4})"
, precision
, value.x
, value.y

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorRGBMaterialSlot.cs


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return string.Format("IsGammaSpace() ? {0}3({1}, {2}, {3}) : GammaToLinearSpace({0}3({1}, {2}, {3}))"
return string.Format("IsGammaSpace() ? {0}3({1}, {2}, {3}) : SRGBToLinear({0}3({1}, {2}, {3}))"
, precision
, value.x
, value.y

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapShaderProperty.cs


public override string GetPropertyDeclarationString()
{
return "samplerCUBE " + referenceName + ";";
return string.Format("TEXTURECUBE({0});\nSAMPLER(sampler{0});", referenceName);
}
public override PreviewProperty GetPreviewMaterialProperty()

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs


using System;
using System.Linq;
using UnityEngine;
using System.Reflection;

{
public static bool ShaderHasError(Shader shader)
{
var hasErrorsCall = typeof(ShaderUtil).GetMethod("GetShaderErrorCount", BindingFlags.Static | BindingFlags.NonPublic);
var result = hasErrorsCall.Invoke(null, new object[] { shader });
return (int)result != 0;
var errors = GetShaderErrors(shader);
return errors.Any(x => x.warning == 0);
}
public struct ShaderError

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs.meta


fileFormatVersion: 2
guid: 562bd27a5e73fc64d80a1d9d936ffbd5
timeCreated: 1464601236
licenseType: Pro
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SamplerStateShaderProperty.cs


public override string GetPropertyDeclarationString()
{
return string.Format(@"
#ifdef UNITY_COMPILER_HLSL
SamplerState {0};
#endif", referenceName);
return string.Format(@"SAMPLER2D({0});", referenceName);
}
public override PreviewProperty GetPreviewMaterialProperty()

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TextureShaderProperty.cs


public override string GetPropertyDeclarationString()
{
return "UNITY_DECLARE_TEX2D(" + referenceName + ");";
return string.Format("TEXTURE2D({0});\nSAMPLER(sampler{0});", referenceName);
return "UNITY_DECLARE_TEX2D_NOSAMPLER(" + referenceName + ");";
return string.Format("TEXTURE2D({0});", referenceName);
}
public override PreviewProperty GetPreviewMaterialProperty()

22
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs


PBRMasterNode.MetallicSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
};

PBRMasterNode.SpecularSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
};

foreach (var channel in graphRequiements.requiresMeshUVs.Distinct())
vertexInputs.AddShaderChunk(string.Format("float4 texcoord{0} : TEXCOORD{0};", (int)channel), false);
vertexInputs.AddShaderChunk("UNITY_VERTEX_INPUT_INSTANCE_ID", false);
vertexInputs.Deindent();
vertexInputs.AddShaderChunk("};", false);
}

case PBRMasterNode.AlphaMode.AdditiveBlend:
defines.AddShaderChunk("#define _AlphaOut 1", true);
break;
case PBRMasterNode.AlphaMode.Clip:
defines.AddShaderChunk("#define _AlphaClip 1", true);
break;
if (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId))
defines.AddShaderChunk("#define _AlphaClip 1", true);
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
surfaceOutputRemap.AddShaderChunk(string.Format("{0} = surf.{0};", slot.shaderOutputName), true);
}
if (!File.Exists(templateLocation))

var materialOptions = new SurfaceMaterialOptions();
switch (masterNode.alphaMode)
{
case PBRMasterNode.AlphaMode.Overwrite:
case PBRMasterNode.AlphaMode.Clip:
case PBRMasterNode.AlphaMode.Opaque:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs


namespace UnityEditor.ShaderGraph
{
public class LightWeightUnlitSubShader
public class LightWeightUnlitSubShader : IUnlitSubShader
{
Pass m_UnlitPass = new Pass()
{

return resultPass;
}
public IEnumerable<string> GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
public string GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);

subShader.Deindent();
subShader.AddShaderChunk("}", true);
return new[] { subShader.GetShaderString(0) };
return subShader.GetShaderString(0);
}
}
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs


return
@"
{
Out = UnpackNormal(In);
Out = UnpackNormalmapRGorAG(In);
}
";
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/ColorNode.cs


return;
visitor.AddShaderChunk(string.Format(
@"{0}4 {1} = IsGammaSpace() ? {0}4({2}, {3}, {4}, {5}) : {0}4(GammaToLinearSpace({0}3({2}, {3}, {4})), {5});"
@"{0}4 {1} = IsGammaSpace() ? {0}4({2}, {3}, {4}, {5}) : {0}4(SRGBToLinear({0}3({2}, {3}, {4})), {5});"
, precision
, GetVariableNameForNode()
, color.r

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs


using System.ComponentModel;
using UnityEditor.Graphing;
using System.Collections.Generic;
using UnityEditor.ShaderGraph.Drawing.Controls;

{TransformationMatrixType.ViewProjection, "UNITY_MATRIX_VP"},
{TransformationMatrixType.TransposeModelView, "UNITY_MATRIX_T_MV"},
{TransformationMatrixType.InverseTransposeModelView, "UNITY_MATRIX_IT_MV"},
{TransformationMatrixType.ObjectToWorld, "unity_ObjectToWorld"},
{TransformationMatrixType.WorldToObject, "unity_WorldToObject"},
{TransformationMatrixType.ObjectToWorld, "UNITY_MATRIX_M"},
{TransformationMatrixType.WorldToObject, "UNITY_MATRIX_I_M"},
};
[SerializeField]

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs


using System.Linq;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

// Node generations
public virtual void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
string result = string.Format("{0}4 {1} = texCUBElod ({2}, {0}4(reflect(-{3}, {4}), {5}));"
, precision
, GetVariableNameForSlot(OutputSlotId)
, GetSlotValue(CubemapInputId, generationMode)
, GetSlotValue(ViewDirInputId, generationMode)
, GetSlotValue(NormalInputId, generationMode)
, GetSlotValue(LODInputId, generationMode));
var id = GetSlotValue(CubemapInputId, generationMode);
string result = string.Format("{0}4 {1} = SAMPLE_TEXTURECUBE_LOD({2}, {3}, reflect(-{4}, {5}), {6});"
, precision
, GetVariableNameForSlot(OutputSlotId)
, id
, "sampler" + id
, GetSlotValue(ViewDirInputId, generationMode)
, GetSlotValue(NormalInputId, generationMode)
, GetSlotValue(LODInputId, generationMode));
visitor.AddShaderChunk(result, true);
}

32
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs


var samplerSlot = FindInputSlot<MaterialSlot>(SamplerInput);
var edgesSampler = owner.GetEdges(samplerSlot.slotReference);
string result;
if (edgesSampler.Any())
{
result = string.Format(@"
#ifdef UNITY_COMPILER_HLSL
{0}4 {1} = {2}.Sample({3}, {4});
#else
{0}4 {1} = UNITY_SAMPLE_TEX2D({2}, {4});
#endif"
, precision
, GetVariableNameForSlot(OutputSlotRGBAId)
, GetSlotValue(TextureInputId, generationMode)
, GetSlotValue(SamplerInput, generationMode)
, uvName);
}
else
{
result = string.Format("{0}4 {1} = UNITY_SAMPLE_TEX2D({2},{3});"
, precision
, GetVariableNameForSlot(OutputSlotRGBAId)
, GetSlotValue(TextureInputId, generationMode)
, uvName);
}
var id = GetSlotValue(TextureInputId, generationMode);
var result = string.Format("{0}4 {1} = SAMPLE_TEXTURE2D({2}, {3}, {4});"
, precision
, GetVariableNameForSlot(OutputSlotRGBAId)
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id
, uvName);
visitor.AddShaderChunk(string.Format("{0}.rgb = UnpackNormal({0});", GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0}.rgb = UnpackNormalmapRGorAG({0});", GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.r;", precision, GetVariableNameForSlot(OutputSlotRId), GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.g;", precision, GetVariableNameForSlot(OutputSlotGId), GetVariableNameForSlot(OutputSlotRGBAId)), true);

14
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/GraphUtil.cs


vertexInputIndex++;
}
vertexInputs.AddShaderChunk("UNITY_VERTEX_INPUT_INSTANCE_ID", false);
vertexInputs.Deindent();
vertexInputs.AddShaderChunk("};", false);
}

finalBuilder.AppendLines(shaderProperties.GetPropertiesBlock(0));
}
finalBuilder.AppendLine(@"CGINCLUDE");
finalBuilder.AppendLine(@"#include ""UnityCG.cginc""");
finalBuilder.AppendLine(@"HLSLINCLUDE");
finalBuilder.AppendLine("#define USE_LEGACY_UNITY_MATRIX_VARIABLES");
finalBuilder.AppendLine(@"#include ""CoreRP/ShaderLibrary/Common.hlsl""");
finalBuilder.AppendLine(@"#include ""CoreRP/ShaderLibrary/Packing.hlsl""");
finalBuilder.AppendLine(@"#include ""CoreRP/ShaderLibrary/Color.hlsl""");
finalBuilder.AppendLine(@"#include ""ShaderGraphLibrary/Functions.hlsl""");
finalBuilder.AppendLine(@"#include ""ShaderGraphLibrary/ShaderVariables.hlsl""");
finalBuilder.AppendLine(@"#include ""ShaderGraphLibrary/ShaderVariablesFunctions.hlsl""");
finalBuilder.Concat(functionBuilder);
finalBuilder.AppendLines(vertexInputs.GetShaderString(0));
finalBuilder.AppendLines(surfaceInputs.GetShaderString(0));

finalBuilder.AppendLines(surfaceDescriptionFunction.GetShaderString(0));
finalBuilder.AppendLine(@"ENDCG");
finalBuilder.AppendLine(@"ENDHLSL");
finalBuilder.AppendLines(ShaderGenerator.GetPreviewSubShader(node, requirements));
ListPool<INode>.Release(activeNodeList);

53
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGenerator.cs


namespace UnityEditor.ShaderGraph
{
public static class ShaderGeneratorNames
{
private static string[] UV = {"uv0", "uv1", "uv2", "uv3"};
public static int UVCount = 4;
public const string ScreenPosition = "screenPosition";
public const string VertexColor = "vertexColor";
public static string GetUVName(this UVChannel channel)
{
return UV[(int)channel];
}
}
public enum UVChannel
{
uv0 = 0,
uv1 = 1,
uv2 = 2,
uv3 = 3,
}
public class ShaderGenerator
{
private struct ShaderChunk

m_transforms[(int)CoordinateSpace.World, (int)CoordinateSpace.World] = new TransformDesc[] {};
m_transforms[(int)CoordinateSpace.Tangent, (int)CoordinateSpace.Tangent] = new TransformDesc[] {};
m_transforms[(int)CoordinateSpace.Object, (int)CoordinateSpace.World]
= new TransformDesc[] {new TransformDesc("unity_ObjectToWorld")};
= new TransformDesc[] {new TransformDesc(MatrixNames.Model)};
= new TransformDesc[] {new TransformDesc("UNITY_MATRIX_I_V")};
= new TransformDesc[] {new TransformDesc(MatrixNames.ViewInverse) };
= new TransformDesc[] {new TransformDesc("unity_WorldToObject")};
= new TransformDesc[] {new TransformDesc(MatrixNames.ModelInverse)};
= new TransformDesc[] {new TransformDesc("UNITY_MATRIX_V")};
= new TransformDesc[] {new TransformDesc(MatrixNames.View)};
for (var from = CoordinateSpace.Object; from != CoordinateSpace.Tangent; from++)
{
for (var to = CoordinateSpace.Object; to != CoordinateSpace.Tangent; to++)

public static string EmitTransform(TransformDesc[] matrices, TransformDesc[] invMatrices, string variable, bool isAffine, bool noMatrixCast, bool inverseTranspose)
{
// Use inverse transpose for situations where
// scale needs to be considered (normals)
if (isAffine)
{
variable = string.Format("float4({0},1.0)", variable);

{
matrix = "(float3x3)" + matrix;
}
// if the matrix is NOT a transpose type
// invert the order of multiplication
// it is implicit transpose.
if (m.transpose)
inverseTranspose = !inverseTranspose;
variable = inverseTranspose

{
var name = preferedCoordinateSpace.ToVariableName(InterpolatorType.ViewDirection);
interpolators.AddShaderChunk(string.Format("float3 {0} : TEXCOORD{1};", name, interpolatorIndex), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = {1};", name, ConvertBetweenSpace("ObjSpaceViewDir(v.vertex)", CoordinateSpace.Object, preferedCoordinateSpace, InputType.Vector)), false);
var worldSpaceViewDir = "SafeNormalize(_WorldSpaceCameraPos.xyz - mul(GetObjectToWorldMatrix(), float4(v.vertex.xyz, 1.0)).xyz)";
vertexShader.AddShaderChunk(string.Format("o.{0} = {1};", name, ConvertBetweenSpace(worldSpaceViewDir, CoordinateSpace.World, preferedCoordinateSpace, InputType.Vector)), false);
pixelShader.AddShaderChunk(string.Format("float3 {0} = normalize(IN.{0});", name), false);
interpolatorIndex++;
}

Pass
{
CGPROGRAM
HLSLPROGRAM
#include ""UnityCG.cginc""
struct GraphVertexOutput
{

v = PopulateVertexData(v);
GraphVertexOutput o;
o.position = UnityObjectToClipPos(v.vertex);
float3 positionWS = TransformObjectToWorld(v.vertex);
o.position = TransformWorldToHClip(positionWS);
fixed4 frag (GraphVertexOutput IN) : SV_Target
float4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}

SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
${SurfaceOutputRemap}
}
ENDCG
ENDHLSL
}
}";
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/DefaultShaderIncludes.cs


using System.IO;
namespace UnityEditor
{
internal static class DefaultShaderIncludes

{
return new[]
{
"Assets/ScriptableRenderPipeline/",
"Assets/SRP/ScriptableRenderPipeline/LightweightPipeline/Shaders"
Path.GetFullPath("Assets/UnityShaderEditor"),
Path.GetFullPath("Packages/com.unity.shadergraph"),
};
}
}

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources.meta


fileFormatVersion: 2
guid: c34a1714ab2ee6c47b8fb9a14777df23
guid: 64c9c5df0004c44f0896e816c69c7aa1
timeCreated: 1485544540
licenseType: Pro
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

92
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template


Pass
{
Tags{"LightMode" = "ShadowCaster"}
Pass
{
Tags{"LightMode" = "ShadowCaster"}
ZWrite On ZTest LEqual
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
#include "LWRP/Shaders/LightweightPassShadow.hlsl"
ENDHLSL
}
Pass
{
Tags{"LightMode" = "DepthOnly"}
Pass
{
Tags{"LightMode" = "DepthOnly"}
ZWrite On
ColorMask 0
ZWrite On
ColorMask 0
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return TransformObjectToHClip(pos.xyz);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDHLSL
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDCG
}
// This pass it not used during regular rendering, only for lightmap baking.
Pass
{
Tags{"LightMode" = "Meta"}
Cull Off
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature EDITOR_VISUALIZATION
#pragma shader_feature _SPECGLOSSMAP
#include "LWRP/Shaders/LightweightPassMeta.hlsl"
ENDHLSL
}

96
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template


${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
// -------------------------------------
// Lightweight Pipeline keywords
// We have no good approach exposed to skip shader variants, e.g, ideally we would like to skip _CASCADE for all puctual lights
// Lightweight combines light classification and shadows keywords to reduce shader variants.
// Lightweight shader library declares defines based on these keywords to avoid having to check them in the shaders
// Core.hlsl defines _MAIN_LIGHT_DIRECTIONAL and _MAIN_LIGHT_SPOT (point lights can't be main light)
// Shadow.hlsl defines _SHADOWS_ENABLED, _SHADOWS_SOFT, _SHADOWS_CASCADE, _SHADOWS_PERSPECTIVE
#pragma multi_compile _ _MAIN_LIGHT_DIRECTIONAL_SHADOW _MAIN_LIGHT_DIRECTIONAL_SHADOW_CASCADE _MAIN_LIGHT_DIRECTIONAL_SHADOW_SOFT _MAIN_LIGHT_DIRECTIONAL_SHADOW_CASCADE_SOFT _MAIN_LIGHT_SPOT_SHADOW _MAIN_LIGHT_SPOT_SHADOW_SOFT
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT
#pragma multi_compile _ _VERTEX_LIGHTS
// -------------------------------------
// Unity defined keywords
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_instancing
#pragma glsl
#pragma debug
#include "LightweightLighting.cginc"
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
#include "LWRP/Shaders/LightweightShaderLibrary/Lighting.hlsl"
#include "CoreRP/ShaderLibrary/Color.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"
float4 position : SV_POSITION;
#ifdef LIGHTMAP_ON
float4 lightmapUV : TEXCOORD0;
#else
float4 vertexSH : TEXCOORD0;
#endif
float4 clipPos : SV_POSITION;
float4 lightmapUVOrVertexSH : TEXCOORD0;
UNITY_VERTEX_OUTPUT_STEREO
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
float3 lwWNormal = normalize(UnityObjectToWorldNormal(v.normal));
float4 lwWorldPos = mul(unity_ObjectToWorld, v.vertex);
float4 clipPos = mul(UNITY_MATRIX_VP, lwWorldPos);
float3 lwWNormal = TransformObjectToWorldNormal(v.normal);
float3 lwWorldPos = TransformObjectToWorld(v.vertex.xyz);
float4 clipPos = TransformWorldToHClip(lwWorldPos);
#ifdef LIGHTMAP_ON
o.lightmapUV.zw = v.texcoord1 * unity_LightmapST.xy + unity_LightmapST.zw;
#else
o.vertexSH = half4(EvaluateSHPerVertex(lwWNormal), 0.0);
#endif
// We either sample GI from lightmap or SH. lightmap UV and vertex SH coefficients
// are packed in lightmapUVOrVertexSH to save interpolator.
// The following funcions initialize
OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUVOrVertexSH);
OUTPUT_SH(lwWNormal, o.lightmapUVOrVertexSH);
o.fogFactorAndVertexLight.yzw = VertexLighting(lwWorldPos.xyz, lwWNormal);
o.fogFactorAndVertexLight.x = ComputeFogFactor(clipPos.z);
o.position = clipPos;
half3 vertexLight = VertexLighting(lwWorldPos, lwWNormal);
half fogFactor = ComputeFogFactor(clipPos.z);
o.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
o.clipPos = clipPos;
fixed4 frag (GraphVertexOutput IN) : SV_Target
half4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}

float Smoothness = 0.5;
float Occlusion = 1;
float Alpha = 1;
float AlphaClipThreshold = 0;
#if defined(UNITY_COLORSPACE_GAMMA)
Albedo = Albedo * Albedo;
Emission = Emission * Emission;
#endif
#if _NORMALMAP
half3 normalWS = TangentToWorldNormal(Normal, WorldSpaceTangent, WorldSpaceBiTangent, WorldSpaceNormal);
#else

#if LIGHTMAP_ON
half3 indirectDiffuse = SampleLightmap(IN.lightmapUV.zw, normalWS);
#else
half3 indirectDiffuse = EvaluateSHPerPixel(normalWS, IN.vertexSH);
#endif
half3 indirectDiffuse = SampleGI(IN.lightmapUVOrVertexSH, normalWS);
half4 color = LightweightFragmentPBR(
WorldSpacePosition,

IN.fogFactorAndVertexLight.yzw,
IN.fogFactorAndVertexLight.yzw,
Albedo,
Metallic,
Specular,

#endif
#if _AlphaClip
clip(Alpha - 0.01);
clip(Alpha - AlphaClipThreshold);
ENDCG
}
ENDHLSL
}

28
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template


${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ENABLE STEREO_MULTIVIEW_ENABLE
#pragma multi_compile_instancing
#pragma glsl
#pragma debug
#include "UnityCG.cginc"
// Lighting include is needed because of GI
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
#include "LWRP/Shaders/LightweightShaderLibrary/Lighting.hlsl"
#include "CoreRP/ShaderLibrary/Color.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"
${Defines}

{
float4 position : POSITION;
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)

UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
o.position = TransformObjectToHClip(v.vertex.xyz);
fixed4 frag (GraphVertexOutput IN) : SV_Target
half4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}

float Alpha = 0;
${SurfaceOutputRemap}
return fixed4(Color, Alpha);
return half4(Color, Alpha);
ENDCG
ENDHLSL
}

2
MaterialGraphProject/UnityPackageManager/manifest.json


{
"registry": "https://staging-packages.unity.com",
"dependencies": {
"com.unity.render-pipelines.lightweight" : "0.1.20"
"com.unity.render-pipelines.lightweight" : "0.1.23"
}
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs


finalShader.AddShaderChunk("}", false);
var lwSub = new LightWeightUnlitSubShader();
foreach (var subshader in lwSub.GetSubshader(this, mode))
finalShader.AddShaderChunk(subshader, true);
finalShader.AddShaderChunk(lwSub.GetSubshader(this, mode), true);
var hdSub = new HDUnlitSubShader();
finalShader.AddShaderChunk(hdSub.GetSubshader(this, mode), true);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs


public const string SmoothnessSlotName = "Smoothness";
public const string OcclusionSlotName = "Occlusion";
public const string AlphaSlotName = "Alpha";
public const string AlphaClipThresholdSlotName = "AlphaClipThreshold";
public const string VertexOffsetName = "VertexPosition";
public const int AlbedoSlotId = 0;

public const int SmoothnessSlotId = 5;
public const int OcclusionSlotId = 6;
public const int AlphaSlotId = 7;
public const int AlphaThresholdSlotId = 8;
public enum Model
{

public enum AlphaMode
{
Overwrite,
Opaque,
AdditiveBlend,
Clip
AdditiveBlend
}
[SerializeField]

AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0f, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support

model == Model.Metallic ? MetallicSlotId : SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
AlphaSlotId,
AlphaThresholdSlotId
}, true);
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline.meta


fileFormatVersion: 2
guid: 621b9da5e0cd5cc449775c0394b63d58
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes.meta


fileFormatVersion: 2
guid: be7d4ec304eccd8489095f90e0909d93
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs


using System;
namespace UnityEditor.ShaderGraph {
public struct MatrixNames
{
public const string Model = "UNITY_MATRIX_M";
public const string ModelInverse = "UNITY_MATRIX_I_M";
public const string View = "UNITY_MATRIX_V";
public const string ViewInverse = "UNITY_MATRIX_I_V";
public const string Projection = "UNITY_MATRIX_P";
public const string ViewProjection = "UNITY_MATRIX_VP";
public const string ModelView = "UNITY_MATRIX_MV";
public const string ModelViewTransposed = "UNITY_MATRIX_T_MV";
public const string ModelViewInverseTransposed = "UNITY_MATRIX_IT_MV";
public const string ModelViewProjection = "UNITY_MATRIX_MVP";
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs.meta


fileFormatVersion: 2
guid: 1358e9b39cd7e8442bece5b15a2a7c63
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs


using System;
namespace UnityEditor.ShaderGraph {
public static class ShaderGeneratorNames
{
private static string[] UV = {"uv0", "uv1", "uv2", "uv3"};
public static int UVCount = 4;
public const string ScreenPosition = "screenPosition";
public const string VertexColor = "vertexColor";
public static string GetUVName(this UVChannel channel)
{
return UV[(int)channel];
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs.meta


fileFormatVersion: 2
guid: 33854ecfd53cd054a99d8cb17b260170
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs


using System;
namespace UnityEditor.ShaderGraph {
public enum UVChannel
{
uv0 = 0,
uv1 = 1,
uv2 = 2,
uv3 = 3,
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs.meta


fileFormatVersion: 2
guid: d77363d2f0df1f544b21d9e8a05f01a1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

74
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template


// Unlit shader always render in forward
Pass
{
Name "ForwardUnlit"
Tags { "LightMode" = "${LightMode}" }
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
//#pragma enable_d3d11_debug_symbols
#pragma vertex Vert
#pragma fragment Frag
#define UNITY_MATERIAL_UNLIT // Need to be define before including Material.hlsl
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "HDRP/ShaderVariables.hlsl"
#include "HDRP/ShaderPass/FragInputs.hlsl"
#include "HDRP/ShaderPass/ShaderPass.cs.hlsl"
${Defines}
#include "HDRP/Material/Material.hlsl"
// This include will define the various Attributes/Varyings structure
#include "HDRP/ShaderPass/VaryingMesh.hlsl"
${Graph}
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
{
${LocalPixelShader}
SurfaceInputs surfaceInput;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Color = 0;
float Alpha = 0;
${SurfaceOutputRemap}
surfaceData.color = Color;
#ifdef _ALPHATEST_ON
DoAlphaTest(Alpha, _AlphaCutoff);
#endif
// Builtin Data
builtinData.opacity = Alpha;
builtinData.bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
builtinData.emissiveIntensity = 0;
builtinData.emissiveColor = 0;
builtinData.velocity = float2(0.0, 0.0);
builtinData.shadowMask0 = 0.0;
builtinData.shadowMask1 = 0.0;
builtinData.shadowMask2 = 0.0;
builtinData.shadowMask3 = 0.0;
builtinData.distortion = float2(0.0, 0.0);
builtinData.distortionBlur = 0.0;
builtinData.depthOffset = 0.0;
}
#include "HDRP/ShaderPass/${ShaderPassInclude}.hlsl"
ENDHLSL
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template.meta


fileFormatVersion: 2
guid: 6eeaaca43ab129049ae23a1bd89420c4
timeCreated: 1481194716
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

8
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary.meta


fileFormatVersion: 2
guid: c1bc9b92d5eaa40f8a85c1f48ba87de9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs.meta


fileFormatVersion: 2
guid: 292c6a3c80161fa4cb49a9d11d35cbe9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

204
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs


using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public class HDUnlitSubShader : IUnlitSubShader
{
struct Pass
{
public string Name;
public string ShaderPassName;
public string ShaderPassInclude;
public List<int> VertexShaderSlots;
public List<int> PixelShaderSlots;
}
Pass m_UnlitPassForwardOnly = new Pass()
{
Name = "ForwardOnly",
ShaderPassName = "SHADERPASS_FORWARD_UNLIT",
ShaderPassInclude = "ShaderPassForwardUnlit",
PixelShaderSlots = new List<int>()
{
UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId
}
};
Pass m_UnlitPassForwardDepthOnly = new Pass()
{
Name = "DepthForwardOnly",
ShaderPassName = "SHADERPASS_DEPTH_ONLY",
ShaderPassInclude = "ShaderPassDepthOnly",
PixelShaderSlots = new List<int>()
{
UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId
}
};
private static string GetShaderPassFromTemplate(UnlitMasterNode masterNode, Pass pass, GenerationMode mode)
{
var builder = new ShaderStringBuilder();
builder.IncreaseIndent();
builder.IncreaseIndent();
var surfaceDescriptionFunction = new ShaderGenerator();
var surfaceDescriptionStruct = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
var functionRegistry = new FunctionRegistry(builder);
var shaderProperties = new PropertyCollector();
surfaceInputs.AddShaderChunk("struct SurfaceInputs{", false);
surfaceInputs.Indent();
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var requirements = ShaderGraphRequirements.FromNodes(activeNodeList);
/*
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresPosition, InterpolatorType.Position, surfaceInputs);*/
ShaderGenerator defines = new ShaderGenerator();
defines.AddShaderChunk(string.Format("#define SHADERPASS {0}", pass.ShaderPassName), true);
if (requirements.requiresVertexColor)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.VertexColor), false);
/*if (requirements.requiresScreenPosition)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.ScreenPosition), false);*/
foreach (var channel in requirements.requiresMeshUVs.Distinct())
{
surfaceInputs.AddShaderChunk(string.Format("half4 {0};", channel.GetUVName()), false);
defines.AddShaderChunk("#define ATTRIBUTES_NEED_TEXCOORD" + (int)channel, true);
defines.AddShaderChunk("#define VARYINGS_NEED_TEXCOORD" + (int)channel, true);
}
surfaceInputs.Deindent();
surfaceInputs.AddShaderChunk("};", false);
var slots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
{
var slot = masterNode.FindSlot<MaterialSlot>(id);
if (slot != null)
slots.Add(slot);
}
GraphUtil.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, slots, true);
var usedSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
GraphUtil.GenerateSurfaceDescription(
activeNodeList,
masterNode,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
functionRegistry,
shaderProperties,
requirements,
mode,
"PopulateSurfaceData",
"SurfaceDescription",
null,
usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderFunctionVisitor.GetShaderString(2), false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionStruct.GetShaderString(2), false);
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
var materialOptions = new SurfaceMaterialOptions();
materialOptions.GetTags(tagsVisitor);
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);
materialOptions.GetDepthTest(zTestVisitor);
materialOptions.GetDepthWrite(zWriteVisitor);
var localPixelShader = new ShaderGenerator();
var localSurfaceInputs = new ShaderGenerator();
var surfaceOutputRemap = new ShaderGenerator();
foreach (var channel in requirements.requiresMeshUVs.Distinct())
localSurfaceInputs.AddShaderChunk(string.Format("surfaceInput.{0} = {1};", channel.GetUVName(), string.Format("half4(input.texCoord{0}, 0, 0)", (int)channel)), false);
var templateLocation = ShaderGenerator.GetTemplatePath("HDUnlitPassForward.template");
foreach (var slot in usedSlots)
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
if (!File.Exists(templateLocation))
return string.Empty;
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultPass = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultPass = resultPass.Replace("${Graph}", graph.GetShaderString(3));
resultPass = resultPass.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${LightMode}", pass.Name);
resultPass = resultPass.Replace("${ShaderPassInclude}", pass.ShaderPassInclude);
resultPass = resultPass.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${LOD}", "" + materialOptions.lod);
return resultPass;
}
public string GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);
subShader.AddShaderChunk("{", true);
subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderType\" = \"Opaque\" }", true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
masterNode,
m_UnlitPassForwardDepthOnly,
mode),
true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
masterNode,
m_UnlitPassForwardOnly,
mode),
true);
subShader.Deindent();
subShader.AddShaderChunk("}", true);
return subShader.GetShaderString(0);
}
}
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs


using System;
namespace UnityEditor.ShaderGraph {
public interface IUnlitSubShader
{
string GetSubshader(UnlitMasterNode masterNode, GenerationMode mode);
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs.meta


fileFormatVersion: 2
guid: 1f0e14eed65d43342acaeb7f9e597621
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

14
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl


// UNITY_SHADER_NO_UPGRADE
#ifndef UNITY_SHADER_GRAPH_INCLUDED
#define UNITY_SHADER_GRAPH_INCLUDED
bool IsGammaSpace()
{
#ifdef UNITY_COLORSPACE_GAMMA
return true;
#else
return false;
#endif
}
#endif // UNITY_SHADER_GRAPH_INCLUDED

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl.meta


fileFormatVersion: 2
guid: 76c5c0b7561134f0ca526e50f239a4a2
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

173
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl


#ifndef UNITY_GEOMETRICTOOLS_INCLUDED
#define UNITY_GEOMETRICTOOLS_INCLUDED
//-----------------------------------------------------------------------------
// Intersection functions
//-----------------------------------------------------------------------------
// return furthest near intersection in x and closest far intersection in y
// if (intersections.y > intersections.x) the ray hit the box, else it miss it
// Assume dir is normalize
float2 BoxRayIntersect(float3 start, float3 dir, float3 boxMin, float3 boxMax)
{
float3 invDir = 1.0 / dir;
// Find the ray intersection with box plane
float3 firstPlaneIntersect = (boxMin - start) * invDir;
float3 secondPlaneIntersect = (boxMax - start) * invDir;
// Get the closest/furthest of these intersections along the ray (Ok because x/0 give +inf and -x/0 give �inf )
float3 closestPlane = min(firstPlaneIntersect, secondPlaneIntersect);
float3 furthestPlane = max(firstPlaneIntersect, secondPlaneIntersect);
float2 intersections;
// Find the furthest near intersection
intersections.x = max(closestPlane.x, max(closestPlane.y, closestPlane.z));
// Find the closest far intersection
intersections.y = min(min(furthestPlane.x, furthestPlane.y), furthestPlane.z);
return intersections;
}
// This simplified version assume that we care about the result only when we are inside the box
// Assume dir is normalize
float BoxRayIntersectSimple(float3 start, float3 dir, float3 boxMin, float3 boxMax)
{
float3 invDir = 1.0 / dir;
// Find the ray intersection with box plane
float3 rbmin = (boxMin - start) * invDir;
float3 rbmax = (boxMax - start) * invDir;
float3 rbminmax = (dir > 0.0) ? rbmax : rbmin;
return min(min(rbminmax.x, rbminmax.y), rbminmax.z);
}
// Assume Sphere is at the origin (i.e start = position - spherePosition)
float2 SphereRayIntersect(float3 start, float3 dir, float radius, out bool intersect)
{
float a = dot(dir, dir);
float b = dot(dir, start) * 2.0;
float c = dot(start, start) - radius * radius;
float discriminant = b * b - 4.0 * a * c;
float2 intersections = float2(0.0, 0.0);
intersect = false;
if (discriminant < 0.0 || a == 0.0)
{
intersections.x = 0.0;
intersections.y = 0.0;
}
else
{
float sqrtDiscriminant = sqrt(discriminant);
intersections.x = (-b - sqrtDiscriminant) / (2.0 * a);
intersections.y = (-b + sqrtDiscriminant) / (2.0 * a);
intersect = true;
}
return intersections;
}
// This simplified version assume that we care about the result only when we are inside the sphere
// Assume Sphere is at the origin (i.e start = position - spherePosition) and dir is normalized
// Ref: http://http.developer.nvidia.com/GPUGems/gpugems_ch19.html
float SphereRayIntersectSimple(float3 start, float3 dir, float radius)
{
float b = dot(dir, start) * 2.0;
float c = dot(start, start) - radius * radius;
float discriminant = b * b - 4.0 * c;
return abs(sqrt(discriminant) - b) * 0.5;
}
float3 RayPlaneIntersect(in float3 rayOrigin, in float3 rayDirection, in float3 planeOrigin, in float3 planeNormal)
{
float dist = dot(planeNormal, planeOrigin - rayOrigin) / dot(planeNormal, rayDirection);
return rayOrigin + rayDirection * dist;
}
//-----------------------------------------------------------------------------
// Miscellaneous functions
//-----------------------------------------------------------------------------
// Box is AABB
float DistancePointBox(float3 position, float3 boxMin, float3 boxMax)
{
return length(max(max(position - boxMax, boxMin - position), float3(0.0, 0.0, 0.0)));
}
float3 ProjectPointOnPlane(float3 position, float3 planePosition, float3 planeNormal)
{
return position - (dot(position - planePosition, planeNormal) * planeNormal);
}
// Plane equation: {(a, b, c) = N, d = -dot(N, P)}.
// Returns the distance from the plane to the point 'p' along the normal.
// Positive -> in front (above), negative -> behind (below).
float DistanceFromPlane(float3 p, float4 plane)
{
return dot(float4(p, 1.0), plane);
}
// Returns 'true' if the triangle is outside of the frustum.
// 'epsilon' is the (negative) distance to (outside of) the frustum below which we cull the triangle.
bool CullTriangleFrustum(float3 p0, float3 p1, float3 p2, float epsilon, float4 frustumPlanes[6], int numPlanes)
{
bool outside = false;
for (int i = 0; i < numPlanes; i++)
{
// If all 3 points are behind any of the planes, we cull.
outside = outside || Max3(DistanceFromPlane(p0, frustumPlanes[i]),
DistanceFromPlane(p1, frustumPlanes[i]),
DistanceFromPlane(p2, frustumPlanes[i])) < epsilon;
}
return outside;
}
// Returns 'true' if the edge of the triangle is outside of the frustum.
// The edges are defined s.t. they are on the opposite side of the point with the given index.
// 'epsilon' is the (negative) distance to (outside of) the frustum below which we cull the triangle.
bool3 CullTriangleEdgesFrustum(float3 p0, float3 p1, float3 p2, float epsilon, float4 frustumPlanes[6], int numPlanes)
{
bool3 edgesOutside = false;
for (int i = 0; i < numPlanes; i++)
{
bool3 pointsOutside = bool3(DistanceFromPlane(p0, frustumPlanes[i]) < epsilon,
DistanceFromPlane(p1, frustumPlanes[i]) < epsilon,
DistanceFromPlane(p2, frustumPlanes[i]) < epsilon);
// If both points of the edge are behind any of the planes, we cull.
edgesOutside.x = edgesOutside.x || (pointsOutside.y && pointsOutside.z);
edgesOutside.y = edgesOutside.y || (pointsOutside.x && pointsOutside.z);
edgesOutside.z = edgesOutside.z || (pointsOutside.x && pointsOutside.y);
}
return edgesOutside;
}
// Returns 'true' if a triangle defined by 3 vertices is back-facing.
// 'epsilon' is the (negative) value of dot(N, V) below which we cull the triangle.
// 'winding' can be used to change the order: pass 1 for (p0 -> p1 -> p2), or -1 for (p0 -> p2 -> p1).
bool CullTriangleBackFace(float3 p0, float3 p1, float3 p2, float epsilon, float3 viewPos, float winding)
{
float3 edge1 = p1 - p0;
float3 edge2 = p2 - p0;
float3 N = cross(edge1, edge2);
float3 V = viewPos - p0;
float NdotV = dot(N, V) * winding;
// Optimize:
// NdotV / (length(N) * length(V)) < Epsilon
// NdotV < Epsilon * length(N) * length(V)
// NdotV < Epsilon * sqrt(dot(N, N)) * sqrt(dot(V, V))
// NdotV < Epsilon * sqrt(dot(N, N) * dot(V, V))
return NdotV < epsilon * sqrt(dot(N, N) * dot(V, V));
}
#endif // UNITY_GEOMETRICTOOLS_INCLUDED

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl.meta


fileFormatVersion: 2
guid: 07d3f5482ecfe425f91b12cd32be4cbe
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

15
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl


//
// This file was automatically generated. Please don't edit by hand.
//
#ifndef SHADERCONFIG_CS_HLSL
#define SHADERCONFIG_CS_HLSL
//
// UnityEngine.Experimental.Rendering.HDPipeline.ShaderOptions: static fields
//
#define SHADEROPTIONS_VELOCITY_IN_GBUFFER (0)
#define SHADEROPTIONS_PACK_GBUFFER_IN_U16 (0)
#define SHADEROPTIONS_CAMERA_RELATIVE_RENDERING (1)
#endif

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl.meta


fileFormatVersion: 2
guid: 2c6472a689b6ae34e806881d3066cfb3
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

279
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl


// UNITY_SHADER_NO_UPGRADE
#ifndef UNITY_SHADER_VARIABLES_INCLUDED
#define UNITY_SHADER_VARIABLES_INCLUDED
#include "ShaderConfig.cs.hlsl"
// CAUTION:
// Currently the shaders compiler always include regualr Unity shaderVariables, so I get a conflict here were UNITY_SHADER_VARIABLES_INCLUDED is already define, this need to be fixed.
// As I haven't change the variables name yet, I simply don't define anything, and I put the transform function at the end of the file outside the guard header.
// This need to be fixed.
#if defined (DIRECTIONAL_COOKIE) || defined (DIRECTIONAL)
#define USING_DIRECTIONAL_LIGHT
#endif
#if defined(UNITY_SINGLE_PASS_STEREO) || defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define USING_STEREO_MATRICES
#endif
#if defined(USING_STEREO_MATRICES)
#define glstate_matrix_projection unity_StereoMatrixP[unity_StereoEyeIndex]
#define unity_MatrixV unity_StereoMatrixV[unity_StereoEyeIndex]
#define unity_MatrixInvV unity_StereoMatrixInvV[unity_StereoEyeIndex]
#define unity_MatrixVP unity_StereoMatrixVP[unity_StereoEyeIndex]
#define unity_CameraProjection unity_StereoCameraProjection[unity_StereoEyeIndex]
#define unity_CameraInvProjection unity_StereoCameraInvProjection[unity_StereoEyeIndex]
#define unity_WorldToCamera unity_StereoWorldToCamera[unity_StereoEyeIndex]
#define unity_CameraToWorld unity_StereoCameraToWorld[unity_StereoEyeIndex]
#define _WorldSpaceCameraPos unity_StereoWorldSpaceCameraPos[unity_StereoEyeIndex]
#endif
#define UNITY_LIGHTMODEL_AMBIENT (glstate_lightmodel_ambient * 2)
// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerCamera)
// Time (t = time since current level load) values from Unity
float4 _Time; // (t/20, t, t*2, t*3)
float4 _LastTime; // Last frame time (t/20, t, t*2, t*3)
float4 _SinTime; // sin(t/8), sin(t/4), sin(t/2), sin(t)
float4 _CosTime; // cos(t/8), cos(t/4), cos(t/2), cos(t)
float4 unity_DeltaTime; // dt, 1/dt, smoothdt, 1/smoothdt
#if !defined(USING_STEREO_MATRICES)
float3 _WorldSpaceCameraPos;
#endif
// x = 1 or -1 (-1 if projection is flipped)
// y = near plane
// z = far plane
// w = 1/far plane
float4 _ProjectionParams;
// x = width
// y = height
// z = 1 + 1.0/width
// w = 1 + 1.0/height
float4 _ScreenParams;
// Values used to linearize the Z buffer (http://www.humus.name/temp/Linearize%20depth.txt)
// x = 1-far/near
// y = far/near
// z = x/far
// w = y/far
// or in case of a reversed depth buffer (UNITY_REVERSED_Z is 1)
// x = -1+far/near
// y = 1
// z = x/far
// w = 1/far
float4 _ZBufferParams;
// x = orthographic camera's width
// y = orthographic camera's height
// z = unused
// w = 1.0 if camera is ortho, 0.0 if perspective
float4 unity_OrthoParams;
CBUFFER_END
CBUFFER_START(UnityPerCameraRare)
float4 unity_CameraWorldClipPlanes[6];
#if !defined(USING_STEREO_MATRICES)
// Projection matrices of the camera. Note that this might be different from projection matrix
// that is set right now, e.g. while rendering shadows the matrices below are still the projection
// of original camera.
float4x4 unity_CameraProjection;
float4x4 unity_CameraInvProjection;
float4x4 unity_WorldToCamera;
float4x4 unity_CameraToWorld;
#endif
CBUFFER_END
// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerDraw : register(b0))
#ifdef UNITY_USE_PREMULTIPLIED_MATRICES
float4x4 glstate_matrix_mvp;
float4x4 glstate_matrix_modelview0;
float4x4 glstate_matrix_invtrans_modelview0;
#endif
float4x4 unity_ObjectToWorld;
float4x4 unity_WorldToObject;
float4 unity_LODFade; // x is the fade value ranging within [0,1]. y is x quantized into 16 levels
float4 unity_WorldTransformParams; // w is usually 1.0, or -1.0 for odd-negative scale transforms
float4 unity_LightmapST;
float4 unity_DynamicLightmapST;
// SH lighting environment
float4 unity_SHAr;
float4 unity_SHAg;
float4 unity_SHAb;
float4 unity_SHBr;
float4 unity_SHBg;
float4 unity_SHBb;
float4 unity_SHC;
// x = Disabled(0)/Enabled(1)
// y = Computation are done in global space(0) or local space(1)
// z = Texel size on U texture coordinate
float4 unity_ProbeVolumeParams;
float4x4 unity_ProbeVolumeWorldToObject;
float3 unity_ProbeVolumeSizeInv;
float3 unity_ProbeVolumeMin;
// This contain occlusion factor from 0 to 1 for dynamic objects (no SH here)
float4 unity_ProbesOcclusion;
CBUFFER_END
#if defined(USING_STEREO_MATRICES)
CBUFFER_START(UnityStereoGlobals)
float4x4 unity_StereoMatrixP[2];
float4x4 unity_StereoMatrixV[2];
float4x4 unity_StereoMatrixInvV[2];
float4x4 unity_StereoMatrixVP[2];
float4x4 unity_StereoCameraProjection[2];
float4x4 unity_StereoCameraInvProjection[2];
float4x4 unity_StereoWorldToCamera[2];
float4x4 unity_StereoCameraToWorld[2];
float3 unity_StereoWorldSpaceCameraPos[2];
float4 unity_StereoScaleOffset[2];
CBUFFER_END
#endif
#if defined(USING_STEREO_MATRICES) && defined(UNITY_STEREO_MULTIVIEW_ENABLED)
CBUFFER_START(UnityStereoEyeIndices)
float4 unity_StereoEyeIndices[2];
CBUFFER_END
#endif
#if defined(UNITY_STEREO_MULTIVIEW_ENABLED) && defined(SHADER_STAGE_VERTEX)
#define unity_StereoEyeIndex UNITY_VIEWID
UNITY_DECLARE_MULTIVIEW(2);
#elif defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
static uint unity_StereoEyeIndex;
#elif defined(UNITY_SINGLE_PASS_STEREO)
CBUFFER_START(UnityStereoEyeIndex)
int unity_StereoEyeIndex;
CBUFFER_END
#endif
CBUFFER_START(UnityPerDrawRare)
float4x4 glstate_matrix_transpose_modelview0;
CBUFFER_END
// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerFrame)
float4 glstate_lightmodel_ambient;
float4 unity_AmbientSky;
float4 unity_AmbientEquator;
float4 unity_AmbientGround;
float4 unity_IndirectSpecColor;
#if !defined(USING_STEREO_MATRICES)
float4x4 glstate_matrix_projection;
float4x4 unity_MatrixV;
float4x4 unity_MatrixInvV;
float4x4 unity_MatrixVP;
float4 unity_StereoScaleOffset;
int unity_StereoEyeIndex;
#endif
float3 unity_ShadowColor;
uint _TaaFrameIndex; // [0, 7]
CBUFFER_END
// ----------------------------------------------------------------------------
// These are the samplers available in the HDRenderPipeline.
// Avoid declaring extra samplers as they are 4x SGPR each on GCN.
SAMPLER(s_linear_clamp_sampler);
SAMPLER(s_trilinear_clamp_sampler);
// ----------------------------------------------------------------------------
TEXTURE2D(_MainDepthTexture);
SAMPLER(sampler_MainDepthTexture);
// Main lightmap
TEXTURE2D(unity_Lightmap);
SAMPLER(samplerunity_Lightmap);
// Dual or directional lightmap (always used with unity_Lightmap, so can share sampler)
TEXTURE2D(unity_LightmapInd);
// Dynamic GI lightmap
TEXTURE2D(unity_DynamicLightmap);
SAMPLER(samplerunity_DynamicLightmap);
TEXTURE2D(unity_DynamicDirectionality);
// We can have shadowMask only if we have lightmap, so no sampler
TEXTURE2D(unity_ShadowMask);
// TODO: Change code here so probe volume use only one transform instead of all this parameters!
TEXTURE3D(unity_ProbeVolumeSH);
SAMPLER(samplerunity_ProbeVolumeSH);
CBUFFER_START(UnityVelocityPass)
float4x4 unity_MatrixNonJitteredVP;
float4x4 unity_MatrixPreviousVP;
float4x4 unity_MatrixPreviousM;
float4x4 unity_MatrixPreviousMI;
//X : Use last frame positions (right now skinned meshes are the only objects that use this
//Y : Force No Motion
//Z : Z bias value
float4 unity_MotionVectorsParams;
CBUFFER_END
// ----------------------------------------------------------------------------
// TODO: all affine matrices should be 3x4.
// TODO: sort these vars by the frequency of use (descending), and put commonly used vars together.
// Note: please use UNITY_MATRIX_X macros instead of referencing matrix variables directly.
CBUFFER_START(UnityPerPass)
float4x4 _PrevViewProjMatrix;
float4x4 _ViewProjMatrix;
float4x4 _NonJitteredViewProjMatrix;
float4x4 _ViewMatrix;
float4x4 _ProjMatrix;
float4x4 _InvViewProjMatrix;
float4x4 _InvViewMatrix;
float4x4 _InvProjMatrix;
float4 _InvProjParam;
float4 _ScreenSize; // {w, h, 1/w, 1/h}
float4 _FrustumPlanes[6]; // {(a, b, c) = N, d = -dot(N, P)} [L, R, T, B, N, F]
CBUFFER_END
float4x4 OptimizeProjectionMatrix(float4x4 M)
{
// Matrix format (x = non-constant value).
// Orthographic Perspective Combined(OR)
// | x 0 0 x | | x 0 x 0 | | x 0 x x |
// | 0 x 0 x | | 0 x x 0 | | 0 x x x |
// | x x x x | | x x x x | | x x x x | <- oblique projection row
// | 0 0 0 1 | | 0 0 x 0 | | 0 0 x x |
// Notice that some values are always 0.
// We can avoid loading and doing math with constants.
M._21_41 = 0;
M._12_42 = 0;
return M;
}
#ifdef USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "ShaderVariablesMatrixDefsLegacyUnity.hlsl"
#else
#include "ShaderVariablesMatrixDefsHDCamera.hlsl"
#endif
#include "ShaderVariablesFunctions.hlsl"
#endif // UNITY_SHADER_VARIABLES_INCLUDED

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl.meta


fileFormatVersion: 2
guid: 2bc64066748469e48861ed835a8b806d
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

192
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl


#ifndef UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED
#define UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED
float4x4 GetWorldToViewMatrix()
{
return UNITY_MATRIX_V;
}
float4x4 GetObjectToWorldMatrix()
{
return UNITY_MATRIX_M;
}
float4x4 GetWorldToObjectMatrix()
{
return UNITY_MATRIX_I_M;
}
// Transform to homogenous clip space
float4x4 GetWorldToHClipMatrix()
{
return UNITY_MATRIX_VP;
}
float GetOddNegativeScale()
{
return unity_WorldTransformParams.w;
}
float3 TransformWorldToView(float3 positionWS)
{
return mul(GetWorldToViewMatrix(), float4(positionWS, 1.0)).xyz;
}
float3 TransformObjectToWorld(float3 positionOS)
{
return mul(GetObjectToWorldMatrix(), float4(positionOS, 1.0)).xyz;
}
float3 TransformWorldToObject(float3 positionWS)
{
return mul(GetWorldToObjectMatrix(), float4(positionWS, 1.0)).xyz;
}
float3 TransformObjectToWorldDir(float3 dirOS)
{
// Normalize to support uniform scaling
return normalize(mul((float3x3)GetObjectToWorldMatrix(), dirOS));
}
float3 TransformWorldToObjectDir(float3 dirWS)
{
// Normalize to support uniform scaling
return normalize(mul((float3x3)GetWorldToObjectMatrix(), dirWS));
}
// Transforms normal from object to world space
float3 TransformObjectToWorldNormal(float3 normalOS)
{
#ifdef UNITY_ASSUME_UNIFORM_SCALING
return UnityObjectToWorldDir(normalOS);
#else
// Normal need to be multiply by inverse transpose
// mul(IT_M, norm) => mul(norm, I_M) => {dot(norm, I_M.col0), dot(norm, I_M.col1), dot(norm, I_M.col2)}
return normalize(mul(normalOS, (float3x3)GetWorldToObjectMatrix()));
#endif
}
// Tranforms position from world space to homogenous space
float4 TransformWorldToHClip(float3 positionWS)
{
return mul(GetWorldToHClipMatrix(), float4(positionWS, 1.0));
}
float3 GetAbsolutePositionWS(float3 positionWS)
{
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
positionWS += _WorldSpaceCameraPos;
#endif
return positionWS;
}
float3 GetCameraRelativePositionWS(float3 positionWS)
{
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
positionWS -= _WorldSpaceCameraPos;
#endif
return positionWS;
}
// Note: '_WorldSpaceCameraPos' is set by the legacy Unity code.
float3 GetPrimaryCameraPosition()
{
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
return float3(0, 0, 0);
#else
return _WorldSpaceCameraPos;
#endif
}
// Could be e.g. the position of a primary camera or a shadow-casting light.
float3 GetCurrentViewPosition()
{
#if defined(SHADERPASS) && (SHADERPASS != SHADERPASS_SHADOWS)
return GetPrimaryCameraPosition();
#else
// This is a generic solution.
// However, for the primary camera, using '_WorldSpaceCameraPos' is better for cache locality,
// and in case we enable camera-relative rendering, we can statically set the position is 0.
return UNITY_MATRIX_I_V._14_24_34;
#endif
}
// Returns the forward (central) direction of the current view in the world space.
float3 GetViewForwardDir()
{
float4x4 viewMat = GetWorldToViewMatrix();
return -viewMat[2].xyz;
}
// Returns 'true' if the current view performs a perspective projection.
bool IsPerspectiveProjection()
{
#if defined(SHADERPASS) && (SHADERPASS != SHADERPASS_SHADOWS)
return (unity_OrthoParams.w == 0);
#else
// TODO: set 'unity_OrthoParams' during the shadow pass.
return UNITY_MATRIX_P[3][3] == 0;
#endif
}
// Computes the world space view direction (pointing towards the viewer).
float3 GetWorldSpaceNormalizeViewDir(float3 positionWS)
{
if (IsPerspectiveProjection())
{
// Perspective
float3 V = GetCurrentViewPosition() - positionWS;
return normalize(V);
}
else
{
// Orthographic
return -GetViewForwardDir();
}
}
float3x3 CreateWorldToTangent(float3 normal, float3 tangent, float flipSign)
{
// For odd-negative scale transforms we need to flip the sign
float sgn = flipSign * GetOddNegativeScale();
float3 bitangent = cross(normal, tangent) * sgn;
return float3x3(tangent, bitangent, normal);
}
float3 TransformTangentToWorld(float3 dirTS, float3x3 worldToTangent)
{
// Use transpose transformation to go from tangent to world as the matrix is orthogonal
return mul(dirTS, worldToTangent);
}
float3 TransformWorldToTangent(float3 dirWS, float3x3 worldToTangent)
{
return mul(worldToTangent, dirWS);
}
float3 TransformTangentToObject(float3 dirTS, float3x3 worldToTangent)
{
// Use transpose transformation to go from tangent to world as the matrix is orthogonal
float3 normalWS = mul(dirTS, worldToTangent);
return mul((float3x3)GetWorldToObjectMatrix(), normalWS);
}
float3 TransformObjectToTangent(float3 dirOS, float3x3 worldToTangent)
{
return mul(worldToTangent, TransformObjectToWorldDir(dirOS));
}
// UNITY_MATRIX_V defines a right-handed view space with the Z axis pointing towards the viewer.
// This function reverses the direction of the Z axis (so that it points forward),
// making the view space coordinate system left-handed.
void GetLeftHandedViewSpaceMatrices(out float4x4 viewMatrix, out float4x4 projMatrix)
{
viewMatrix = UNITY_MATRIX_V;
viewMatrix._31_32_33_34 = -viewMatrix._31_32_33_34;
projMatrix = UNITY_MATRIX_P;
projMatrix._13_23_33_43 = -projMatrix._13_23_33_43;
}
#endif // UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED

10
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl.meta


fileFormatVersion: 2
guid: 919263f29f66aed49a283fe1f971c094
timeCreated: 1498227267
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

21
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl


#ifdef UNITY_SHADER_VARIABLES_MATRIX_DEFS_HDCAMERA_INCLUDED
#error Mixing HDCamera and legacy Unity matrix definitions
#endif
#ifndef UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_MATRIX_M unity_ObjectToWorld
#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_V unity_MatrixV
#define UNITY_MATRIX_I_V unity_MatrixInvV
#define UNITY_MATRIX_P OptimizeProjectionMatrix(glstate_matrix_projection)
#define UNITY_MATRIX_I_P ERROR_UNITY_MATRIX_I_P_IS_NOT_DEFINED
#define UNITY_MATRIX_VP unity_MatrixVP
#define UNITY_MATRIX_I_VP ERROR_UNITY_MATRIX_I_VP_IS_NOT_DEFINED
#define UNITY_MATRIX_MV mul(UNITY_MATRIX_V, UNITY_MATRIX_M)
#define UNITY_MATRIX_T_MV transpose(UNITY_MATRIX_MV)
#define UNITY_MATRIX_IT_MV transpose(mul(UNITY_MATRIX_I_M, UNITY_MATRIX_I_V))
#define UNITY_MATRIX_MVP mul(UNITY_MATRIX_VP, UNITY_MATRIX_M)
#endif // UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED

10
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl.meta


fileFormatVersion: 2
guid: 77ec57a2ba7588b4b96bc4c87934003f
timeCreated: 1498228363
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SpecularMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs.meta


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

97
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs


/*using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public abstract class ProjectSpecificMasterNode : AbstractMasterNode
{
public override string GetSubShader(GenerationMode mode)
{
}
public override string GetFullShader(
GenerationMode mode,
out List<PropertyGenerator.TextureInfo> configuredTextures)
{
var shaderTemplateLocation = ShaderGenerator.GetTemplatePath("shader.template");
if (!File.Exists(shaderTemplateLocation))
{
configuredTextures = new List<PropertyGenerator.TextureInfo>();
return string.Empty;
}
var templateText = File.ReadAllText(shaderTemplateLocation);
var shaderBodyVisitor = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var shaderPropertiesVisitor = new PropertyGenerator();
var shaderPropertyUsagesVisitor = new ShaderGenerator();
var shaderInputVisitor = new ShaderGenerator();
var vertexShaderBlock = new ShaderGenerator();
GenerateSurfaceShaderInternal(
shaderBodyVisitor,
shaderFunctionVisitor,
shaderInputVisitor,
vertexShaderBlock,
shaderPropertiesVisitor,
shaderPropertyUsagesVisitor,
mode);
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
m_MaterialOptions.GetTags(tagsVisitor);
m_MaterialOptions.GetBlend(blendingVisitor);
m_MaterialOptions.GetCull(cullingVisitor);
m_MaterialOptions.GetDepthTest(zTestVisitor);
m_MaterialOptions.GetDepthWrite(zWriteVisitor);
var resultShader = templateText.Replace("${ShaderName}", GetType() + guid.ToString());
resultShader = resultShader.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ShaderPropertyUsages}", shaderPropertyUsagesVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${LightingFunctionName}", GetLightFunction());
resultShader = resultShader.Replace("${SurfaceOutputStructureName}", GetSurfaceOutputName());
resultShader = resultShader.Replace("${ShaderFunctions}", shaderFunctionVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ShaderInputs}", shaderInputVisitor.GetShaderString(3));
resultShader = resultShader.Replace("${PixelShaderBody}", shaderBodyVisitor.GetShaderString(3));
resultShader = resultShader.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${VertexShaderDecl}", "vertex:vert");
resultShader = resultShader.Replace("${VertexShaderBody}", vertexShaderBlock.GetShaderString(3));
configuredTextures = shaderPropertiesVisitor.GetConfiguredTexutres();
return Regex.Replace(resultShader, @"\r\n|\n\r|\n|\r", Environment.NewLine);
}
private void GenerateSurfaceShaderInternal(
ShaderGenerator propertyUsages,
GenerationMode mode)
{
var activeNodeList = new List<INode>();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
foreach (var node in activeNodeList.OfType<AbstractMaterialNode>())
{
node.GeneratePropertyUsages(propertyUsages, mode);
}
}
}
}*/

156
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
/* [Serializable]
[Title("Master", "Custom Texture")]
public class ExportTextureMasterNode : MasterNode
{
public const string ColorSlotName = "Color";
public const int ColorSlotId = 0;
public ExportTextureMasterNode()
{
name = "ExportTextureMasterNode";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, SlotValueType.Vector4, Vector4.zero));
// clear out slot names that do not match the slots we support
RemoveSlotsNameNotMatching(new[] { ColorSlotId });
}
public override PreviewMode previewMode
{
get
{
return PreviewMode.Preview2D;
}
}
public override string GetSubShader(GenerationMode mode, PropertyCollector shaderPropertiesVisitor)
{
return "";
}
public override bool has3DPreview()
{
return false;
}
public override string GetFullShader(GenerationMode generationMode, string name, out List<PropertyCollector.TextureInfo> configuredTextures)
{
// figure out what kind of preview we want!
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
string templateLocation = ShaderGenerator.GetTemplatePath("ExportTexture.template");
if (!File.Exists(templateLocation))
{
configuredTextures = new List<PropertyCollector.TextureInfo>();
return string.Empty;
}
string template = File.ReadAllText(templateLocation);
var shaderBodyVisitor = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var shaderPropertiesVisitor = new PropertyCollector();
var shaderPropertyUsagesVisitor = new ShaderGenerator();
var shaderInputVisitor = new ShaderGenerator();
// always add color because why not.
shaderInputVisitor.AddShaderChunk("float4 color : COLOR;", true);
bool needBitangent = activeNodeList.OfType<IMayRequireBitangent>().Any(x => x.RequiresBitangent());
bool needsWorldPos = activeNodeList.OfType<IMayRequireViewDirection>().Any(x => x.RequiresViewDirection());
if (needsWorldPos || activeNodeList.OfType<IMayRequireWorldPosition>().Any(x => x.RequiresWorldPosition()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpacePosition + " = float3(0.0, 0.0, 0.0);", true);
}
if (needBitangent || activeNodeList.OfType<IMayRequireNormal>().Any(x => x.RequiresNormal()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceNormal + " = float3(0.0, 0.0, 1.0);", true);
}
for (int uvIndex = 0; uvIndex < ShaderGeneratorNames.UVCount; ++uvIndex)
{
var channel = (UVChannel)uvIndex;
if (activeNodeList.OfType<IMayRequireMeshUV>().Any(x => x.RequiresMeshUV(channel)))
{
shaderBodyVisitor.AddShaderChunk("half4 " + channel.GetUVName() + " = float4(IN.localTexcoord.xyz,1.0);", true);
}
}
if (activeNodeList.OfType<IMayRequireViewDirection>().Any(x => x.RequiresViewDirection()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceViewDirection + " = float3(0.0, 0.0, -1.0);", true);
}
if (activeNodeList.OfType<IMayRequireScreenPosition>().Any(x => x.RequiresScreenPosition()))
{
shaderBodyVisitor.AddShaderChunk("half4 " + ShaderGeneratorNames.ScreenPosition + " = float4(IN.globalTexcoord.xyz, 1.0);", true);
}
if (needBitangent || activeNodeList.OfType<IMayRequireTangent>().Any(x => x.RequiresTangent()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceTangent + " = float3(1.0,0.0,0.0);", true);
}
if (needBitangent)
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceBitangent + " = float3(0.0,1.0,0.0);", true);
}
if (activeNodeList.OfType<IMayRequireVertexColor>().Any(x => x.RequiresVertexColor()))
{
shaderBodyVisitor.AddShaderChunk("float4 " + ShaderGeneratorNames.VertexColor + " = float4(1.0,1.0,1.0,1.0);", true);
}
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
{
if (activeNode is IGeneratesFunction)
(activeNode as IGeneratesFunction).GenerateNodeFunction(shaderFunctionVisitor, generationMode);
if (activeNode is IGeneratesBodyCode)
(activeNode as IGeneratesBodyCode).GenerateNodeCode(shaderBodyVisitor, generationMode);
activeNode.GeneratePropertyBlock(shaderPropertiesVisitor, generationMode);
activeNode.GeneratePropertyUsages(shaderPropertyUsagesVisitor, generationMode);
}
var inputSlot = GetInputSlots<MaterialSlot>().First();
var edges = owner.GetEdges(inputSlot.slotReference);
if (edges.Count() > 0)
{
var outputRef = edges.First().outputSlot;
var fromNode = owner.GetNodeFromGuid<AbstractMaterialNode>(outputRef.nodeGuid);
shaderBodyVisitor.AddShaderChunk("return " + fromNode.GetVariableNameForSlot(outputRef.slotId) + ";", true);
}
else
{
shaderBodyVisitor.AddShaderChunk("return float4(0.5, 0.5, 0.5, 0.5);", true);
}
ListPool<INode>.Release(activeNodeList);
template = template.Replace("${ShaderName}", name);
template = template.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetPropertiesBlock(2));
template = template.Replace("${ShaderPropertyUsages}", shaderPropertyUsagesVisitor.GetShaderString(3));
template = template.Replace("${ShaderFunctions}", shaderFunctionVisitor.GetShaderString(3));
template = template.Replace("${PixelShaderBody}", shaderBodyVisitor.GetShaderString(4));
//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);
}
}*/
}

88
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs


using System;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
/* [Serializable]
[Title("Master", "Metallic")]
public class MetallicMasterNode : AbstractSurfaceMasterNode
{
public const string MetallicSlotName = "Metallic";
public const int MetallicSlotId = 2;
public const string LightFunctionName = "Standard";
public const string SurfaceOutputStructureName = "SurfaceOutputStandard";
public MetallicMasterNode()
{
name = "MetallicMasterNode";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(VertexOffsetId, VertexOffsetName, VertexOffsetName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Vertex));
AddSlot(new MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
VertexOffsetId
});
}
protected override int[] surfaceInputs
{
get
{
return new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
};
}
}
protected override int[] vertexInputs
{
get
{
return new[]
{
VertexOffsetId
};
}
}
public override string GetSurfaceOutputName()
{
return SurfaceOutputStructureName;
}
public override string GetLightFunction()
{
return LightFunctionName;
}
}*/
}

87
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SpecularMasterNode.cs


using System;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
/* [Serializable]
[Title("Master", "Specular")]
public class SpecularMasterNode : AbstractSurfaceMasterNode
{
public const string SpecularSlotName = "Specular";
public const int SpecularSlotId = 2;
public const string LightFunctionName = "StandardSpecular";
public const string SurfaceOutputStructureName = "SurfaceOutputStandardSpecular";
public SpecularMasterNode()
{
name = "SpecularMasterNode";
UpdateNodeAfterDeserialization();
}
protected override int[] surfaceInputs
{
get
{
return new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
SpecularSlotId
};
}
}
protected override int[] vertexInputs
{
get
{
return new[]
{
VertexOffsetId
};
}
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(VertexOffsetId, VertexOffsetName, VertexOffsetName, SlotType.Input, SlotValueType.Vector3, Vector4.zero));
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(SpecularSlotId, SpecularSlotName, SpecularSlotName, 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(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
});
}
public override string GetSurfaceOutputName()
{
return SurfaceOutputStructureName;
}
public override string GetLightFunction()
{
return LightFunctionName;
}
}*/
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/2DPreview.template.meta


fileFormatVersion: 2
guid: 427b9101977f31a4f9aa026285086d5c
DefaultImporter:
userData:

54
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/2DPreview.template


Shader "${ShaderName}" {
Properties {
${ShaderPropertiesHeader}
}
SubShader {
// inside SubShader
Tags
{
"Queue"="Geometry"
"RenderType"="Opaque"
"IgnoreProjector"="True"
}
// inside Pass
ZWrite On
Blend One Zero
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
${ShaderPropertyUsages}
struct v2f
{
float4 pos : SV_POSITION;
${ShaderInputs}
};
${ShaderFunctions}
v2f vert (appdata_full v)
{
v2f o = (v2f)0;
o.pos = UnityObjectToClipPos(v.vertex);;
${VertexShaderBody}
return o;
}
half4 frag (v2f IN) : COLOR
{
${PixelShaderBody}
}
ENDCG
}
}
Fallback Off
}

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


Shader "${ShaderName}"
{
Properties
{
${ShaderPropertiesHeader}
}
SubShader
{
Tags { "Queue"="Geometry" "IgnoreProjector"="True" "RenderType"="Opaque" }
ZWrite Off
Blend One Zero
Pass
{
CGPROGRAM
#include "UnityCustomRenderTexture.cginc"
#pragma vertex CustomRenderTextureVertexShader${ShaderIsUsingPreview}
#pragma fragment frag
#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;
}
${ShaderPropertyUsages}
${ShaderFunctions}
float4 frag(v2f_customrendertexture IN) : COLOR
{
${PixelShaderBody}
}
ENDCG
}
}
Fallback Off
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/ExportTexture.template.meta


fileFormatVersion: 2
guid: db810b4437bc78b4f94f31af1d276775
DefaultImporter:
userData:

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


SubShader
{
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
LOD ${LOD}
CGPROGRAM
#include "UnityCG.cginc"
//#include "AdvancedBRDF.cginc"
//#include "AdvancedShading.cginc"
//#include "AdvancedLighting.cginc"
${MaterialID}
// ------------------------------------------------------------------
// 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 * 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);
}
// ------------------------------------------------------------------
// 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 ${LightingFunctionName} ${VertexShaderDecl}
#pragma glsl
#pragma debug
${ShaderFunctions}
${ShaderPropertyUsages}
struct Input
{
${ShaderInputs}
};
void vert (inout appdata_full v, out Input o)
{
UNITY_INITIALIZE_OUTPUT(Input,o);
${VertexShaderBody}
}
void surf (Input IN, inout ${SurfaceOutputStructureName} o)
{
${PixelShaderBody}
}
ENDCG
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/advancedSubshader.template.meta


fileFormatVersion: 2
guid: f508073728247984aaa6da15ea564f6e
timeCreated: 1495550333
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/LightWeightShaderPaths.cs.meta


fileFormatVersion: 2
guid: cddd8645d2052584eaee32f4bfc5cc0b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/LightWeightShaderPaths.cs


using System.Linq;
using UnityEngine;
using System.IO;
namespace UnityEditor.Experimental.Rendering
{
static class LightweightIncludePaths
{
[ShaderIncludePath]
public static string[] GetPaths()
{
return new[]
{
Path.GetFullPath("Packages/com.unity.render-pipelines.lightweight/Shaders")
};
}
}
}

26
MaterialGraphProject/Assets/Beachball.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Beachball
m_Shader: {fileID: 4800000, guid: b141c720617d37f45a2fd27af59ccf42, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _Texture2D_A24EBBFA_Tex:
m_Texture: {fileID: 2800000, guid: e017404169662f041a969b0a924cc2ed, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats: []
m_Colors: []

8
MaterialGraphProject/Assets/Beachball.mat.meta


fileFormatVersion: 2
guid: b232af1498b13d14db58368a73b45744
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs.meta → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs.meta

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs.meta → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs.meta

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs

正在加载...
取消
保存