This commit is contained in:
2024-09-20 20:30:10 +02:00
commit 4fabf1a6fd
29169 changed files with 1706941 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 24f978237d7204d78b8266e4b1fd1248
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5f2f816913824e14396c945dc22a5ad1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ff73c880c054e8c40b71704dbc0c1beb
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Rendering.BuiltIn;
using UnityEngine;
using static UnityEditor.Rendering.BuiltIn.ShaderUtils;
namespace UnityEditor.Rendering.BuiltIn
{
class MaterialModificationProcessor : AssetModificationProcessor
{
static void OnWillCreateAsset(string asset)
{
if (!asset.ToLowerInvariant().EndsWith(".mat"))
{
return;
}
MaterialPostprocessor.s_CreatedAssets.Add(asset);
}
}
class MaterialReimporter : Editor
{
// Currently this is never called because there's no way for built-in target shader graph
// materials to track when they need to be upgraded at a global level. To do this currently
// we'd have to iterate over all materials to see if they need upgrading. We may want to add a
// global settings object like UniversalProjectSettings but for built-in to track this.
static void ReimportAllMaterials()
{
string[] guids = AssetDatabase.FindAssets("t:material", null);
// There can be several materials subAssets per guid ( ie : FBX files ), remove duplicate guids.
var distinctGuids = guids.Distinct();
int materialIdx = 0;
int totalMaterials = distinctGuids.Count();
foreach (var asset in distinctGuids)
{
materialIdx++;
var path = AssetDatabase.GUIDToAssetPath(asset);
EditorUtility.DisplayProgressBar("Material Upgrader re-import", string.Format("({0} of {1}) {2}", materialIdx, totalMaterials, path), (float)materialIdx / (float)totalMaterials);
AssetDatabase.ImportAsset(path);
}
EditorUtility.ClearProgressBar();
MaterialPostprocessor.s_NeedsSavingAssets = true;
}
[InitializeOnLoadMethod]
static void RegisterUpgraderReimport()
{
}
}
class MaterialPostprocessor : AssetPostprocessor
{
public static List<string> s_CreatedAssets = new List<string>();
internal static List<string> s_ImportedAssetThatNeedSaving = new List<string>();
internal static bool s_NeedsSavingAssets = false;
internal static readonly Action<Material, ShaderID>[] k_Upgraders = { };
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
var upgradeCount = 0;
foreach (var asset in importedAssets)
{
// We only care about materials
if (!asset.EndsWith(".mat", StringComparison.InvariantCultureIgnoreCase))
continue;
// Load the material and look for it's BuiltIn ShaderID.
// We only care about versioning materials using a known BuiltIn ShaderID.
// This skips any materials that only target other render pipelines, are user shaders,
// or are shaders we don't care to version
var material = (Material)AssetDatabase.LoadAssetAtPath(asset, typeof(Material));
var shaderID = GetShaderID(material.shader);
if (shaderID == ShaderID.Unknown)
continue;
var wasUpgraded = false;
// Look for the BuiltIn AssetVersion
AssetVersion assetVersion = null;
var allAssets = AssetDatabase.LoadAllAssetsAtPath(asset);
foreach (var subAsset in allAssets)
{
if (subAsset is AssetVersion sub)
{
assetVersion = sub;
}
}
if (!assetVersion)
{
wasUpgraded = true;
assetVersion = ScriptableObject.CreateInstance<AssetVersion>();
// The asset was newly created, force initialize them
if (s_CreatedAssets.Contains(asset))
{
assetVersion.version = k_Upgraders.Length;
s_CreatedAssets.Remove(asset);
InitializeLatest(material, shaderID);
}
else if (shaderID.IsShaderGraph())
{
// Assumed to be version 0 since no asset version was found
assetVersion.version = 0;
}
assetVersion.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector | HideFlags.NotEditable;
AssetDatabase.AddObjectToAsset(assetVersion, asset);
}
while (assetVersion.version < k_Upgraders.Length)
{
k_Upgraders[assetVersion.version](material, shaderID);
assetVersion.version++;
wasUpgraded = true;
}
if (wasUpgraded)
{
upgradeCount++;
EditorUtility.SetDirty(assetVersion);
s_ImportedAssetThatNeedSaving.Add(asset);
s_NeedsSavingAssets = true;
}
}
}
static void InitializeLatest(Material material, ShaderID shaderID)
{
// newly created shadergraph materials should reset their keywords immediately (in case inspector doesn't get invoked)
ShaderUtils.ResetMaterialKeywords(material);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1b9beb1a3480dfc43b16ca024c921089
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,54 @@
using UnityEditor.ShaderGraph;
using UnityEngine;
namespace UnityEditor.Rendering.BuiltIn
{
class BuiltInShaderGraphSaveContext
{
public bool updateMaterials;
}
[InitializeOnLoad]
class ShaderGraphMaterialsUpdater
{
static ShaderGraphMaterialsUpdater()
{
GraphData.onSaveGraph += OnShaderGraphSaved;
}
static void OnShaderGraphSaved(Shader shader, object saveContext)
{
// In case the shader is not BuiltIn
if (!(saveContext is BuiltInShaderGraphSaveContext builtInShaderGraphSaveContext))
return;
if (!builtInShaderGraphSaveContext.updateMaterials)
return;
// Iterate over all loaded Materials
Material[] materials = Resources.FindObjectsOfTypeAll<Material>();
try
{
for (int i = 0, length = materials.Length; i < length; i++)
{
// Only update progress bar every 10 materials
if (i % 10 == 9)
{
EditorUtility.DisplayProgressBar(
"Checking material dependencies...",
$"{i} / {length} materials.",
i / (float)(length - 1));
}
// Reset keywords
if (materials[i].shader.name == shader.name)
ShaderUtils.ResetMaterialKeywords(materials[i]);
}
}
finally
{
EditorUtility.ClearProgressBar();
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 96dcdfbd3dc811444976b0a1cebe8444
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
using UnityEngine;
namespace UnityEditor.Rendering.BuiltIn
{
class AssetVersion : ScriptableObject
{
public int version;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 639247ca83abc874e893eb93af2b5e44
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 045465d8500b94f469580f232db2929f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,373 @@
using System;
using UnityEngine;
using UnityEngine.Rendering;
using RenderQueue = UnityEngine.Rendering.RenderQueue;
using UnityEditor.ShaderGraph.Drawing;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
public class BuiltInBaseShaderGUI : ShaderGUI
{
[Flags]
protected enum Expandable
{
SurfaceOptions = 1 << 0,
SurfaceInputs = 1 << 1,
Advanced = 1 << 2
}
public enum SurfaceType
{
Opaque,
Transparent
}
public enum BlendMode
{
Alpha, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Premultiply, // Physically plausible transparency mode, implemented as alpha pre-multiply
Additive,
Multiply
}
public enum RenderFace
{
Front = 2,
Back = 1,
Both = 0
}
public enum QueueControl
{
Auto = 0,
UserOverride = 1
}
protected class Styles
{
public static readonly string[] surfaceTypeNames = Enum.GetNames(typeof(SurfaceType));
public static readonly string[] blendModeNames = Enum.GetNames(typeof(BlendMode));
public static readonly string[] renderFaceNames = Enum.GetNames(typeof(RenderFace));
public static readonly string[] zwriteNames = Enum.GetNames(typeof(UnityEditor.Rendering.BuiltIn.ShaderGraph.ZWriteControl));
// need to skip the first entry for ztest (ZTestMode.Disabled is not a valid value)
public static readonly int[] ztestValues = (int[])Enum.GetValues(typeof(UnityEditor.Rendering.BuiltIn.ShaderGraph.ZTestMode));
public static readonly string[] ztestNames = Enum.GetNames(typeof(UnityEditor.Rendering.BuiltIn.ShaderGraph.ZTestMode));
public static readonly string[] queueControlNames = Enum.GetNames(typeof(QueueControl));
// Categories
public static readonly GUIContent SurfaceOptions =
EditorGUIUtility.TrTextContent("Surface Options", "Controls how Built-In RP renders the Material on a screen.");
public static readonly GUIContent SurfaceInputs = EditorGUIUtility.TrTextContent("Surface Inputs",
"These settings describe the look and feel of the surface itself.");
public static readonly GUIContent AdvancedLabel = EditorGUIUtility.TrTextContent("Advanced Options",
"These settings affect behind-the-scenes rendering and underlying calculations.");
public static readonly GUIContent surfaceType = EditorGUIUtility.TrTextContent("Surface Type",
"Select a surface type for your texture. Choose between Opaque or Transparent.");
public static readonly GUIContent blendingMode = EditorGUIUtility.TrTextContent("Blending Mode",
"Controls how the color of the Transparent surface blends with the Material color in the background.");
public static readonly GUIContent cullingText = EditorGUIUtility.TrTextContent("Render Face",
"Specifies which faces to cull from your geometry. Front culls front faces. Back culls backfaces. None means that both sides are rendered.");
public static readonly GUIContent zwriteText = EditorGUIUtility.TrTextContent("Depth Write",
"Controls whether the shader writes depth. Auto will write only when the shader is opaque.");
public static readonly GUIContent ztestText = EditorGUIUtility.TrTextContent("Depth Test",
"Specifies the depth test mode. The default is LEqual.");
public static readonly GUIContent alphaClipText = EditorGUIUtility.TrTextContent("Alpha Clipping",
"Makes your Material act like a Cutout shader. Use this to create a transparent effect with hard edges between opaque and transparent areas.");
public static readonly GUIContent queueSlider = EditorGUIUtility.TrTextContent("Sorting Priority",
"Determines the chronological rendering order for a Material. Materials with lower value are rendered first.");
public static readonly GUIContent queueControl = EditorGUIUtility.TrTextContent("Queue Control",
"Controls whether render queue is automatically set based on material surface type, or explicitly set by the user.");
}
public bool m_FirstTimeApply = true;
// By default, everything is expanded, except advanced
readonly MaterialHeaderScopeList m_MaterialScopeList = new MaterialHeaderScopeList(uint.MaxValue & ~(uint)Expandable.Advanced);
// These have to be stored due to how MaterialHeaderScopeList callbacks work (they don't provide this data in the callbacks)
MaterialEditor m_MaterialEditor;
MaterialProperty[] m_Properties;
private const int queueOffsetRange = 50;
override public void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
m_MaterialEditor = materialEditor;
m_Properties = properties;
Material targetMat = materialEditor.target as Material;
if (m_FirstTimeApply)
{
OnOpenGUI(targetMat, materialEditor, properties);
m_FirstTimeApply = false;
}
ShaderPropertiesGUI(materialEditor, targetMat, properties);
}
public virtual void OnOpenGUI(Material material, MaterialEditor materialEditor, MaterialProperty[] properties)
{
// Generate the foldouts
m_MaterialScopeList.RegisterHeaderScope(Styles.SurfaceOptions, (uint)Expandable.SurfaceOptions, DrawSurfaceOptions);
m_MaterialScopeList.RegisterHeaderScope(Styles.SurfaceInputs, (uint)Expandable.SurfaceInputs, DrawSurfaceInputs);
m_MaterialScopeList.RegisterHeaderScope(Styles.AdvancedLabel, (uint)Expandable.Advanced, DrawAdvancedOptions);
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
// Clear all keywords for fresh start
// Note: this will nuke user-selected custom keywords when they change shaders
material.shaderKeywords = null;
base.AssignNewShaderToMaterial(material, oldShader, newShader);
// Setup keywords based on the new shader
UnityEditor.Rendering.BuiltIn.ShaderUtils.ResetMaterialKeywords(material);
}
void ShaderPropertiesGUI(MaterialEditor materialEditor, Material material, MaterialProperty[] properties)
{
m_MaterialScopeList.DrawHeaders(materialEditor, material);
}
protected virtual void DrawSurfaceOptions(Material material)
{
var materialEditor = m_MaterialEditor;
var properties = m_Properties;
var surfaceTypeProp = FindProperty(Property.Surface(), properties, false);
if (surfaceTypeProp != null)
{
DoPopup(Styles.surfaceType, materialEditor, surfaceTypeProp, Styles.surfaceTypeNames);
var surfaceType = (SurfaceType)surfaceTypeProp.floatValue;
if (surfaceType == SurfaceType.Transparent)
{
var blendModeProp = FindProperty(Property.Blend(), properties, false);
DoPopup(Styles.blendingMode, materialEditor, blendModeProp, Styles.blendModeNames);
}
}
var cullingProp = FindProperty(Property.Cull(), properties, false);
DoPopup(Styles.cullingText, materialEditor, cullingProp, Enum.GetNames(typeof(RenderFace)));
var zWriteProp = FindProperty(Property.ZWriteControl(), properties, false);
DoPopup(Styles.zwriteText, materialEditor, zWriteProp, Styles.zwriteNames);
var ztestProp = FindProperty(Property.ZTest(), properties, false);
DoIntPopup(Styles.ztestText, materialEditor, ztestProp, Styles.ztestNames, Styles.ztestValues);
var alphaClipProp = FindProperty(Property.AlphaClip(), properties, false);
DrawFloatToggleProperty(Styles.alphaClipText, alphaClipProp);
}
protected virtual void DrawSurfaceInputs(Material material)
{
DrawShaderGraphProperties(m_MaterialEditor, material, m_Properties);
}
protected virtual void DrawAdvancedOptions(Material material)
{
// Only draw sorting priority if queue control is set to "auto", otherwise draw render queue
// GetAutomaticQueueControlSetting will guarantee we have a sane queue control value
bool autoQueueControl = GetAutomaticQueueControlSetting(material);
var queueControlProp = FindProperty(Property.QueueControl(), m_Properties, false);
DoPopup(Styles.queueControl, m_MaterialEditor, queueControlProp, Styles.queueControlNames);
if (autoQueueControl)
DrawQueueOffsetField(m_MaterialEditor, material, m_Properties);
else
m_MaterialEditor.RenderQueueField();
}
protected void DrawQueueOffsetField(MaterialEditor materialEditor, Material material, MaterialProperty[] properties)
{
var queueOffsetProp = FindProperty(Property.QueueOffset(), properties, false);
if (queueOffsetProp != null)
materialEditor.IntSliderShaderProperty(queueOffsetProp, -queueOffsetRange, queueOffsetRange, Styles.queueSlider);
}
static void DrawShaderGraphProperties(MaterialEditor materialEditor, Material material, MaterialProperty[] properties)
{
if (properties == null)
return;
ShaderGraphPropertyDrawers.DrawShaderGraphGUI(materialEditor, properties);
}
internal static void UpdateMaterialRenderQueueControl(Material material)
{
//
// Render Queue Control handling
//
// Check for a raw render queue (the actual serialized setting - material.renderQueue has already been converted)
// setting of -1, indicating that the material property should be inherited from the shader.
// If we find this, add a new property "render queue control" set to 0 so we will
// always know to follow the surface type of the material (this matches the hand-written behavior)
// If we find another value, add the the property set to 1 so we will know that the
// user has explicitly selected a render queue and we should not override it.
//
int rawRenderQueue = MaterialAccess.ReadMaterialRawRenderQueue(material);
if (rawRenderQueue == -1)
{
material.SetFloat(Property.QueueControl(), (float)QueueControl.Auto); // Automatic behavior - surface type override
}
else
{
material.SetFloat(Property.QueueControl(), (float)QueueControl.UserOverride); // User has selected explicit render queue
}
}
internal static bool GetAutomaticQueueControlSetting(Material material)
{
// If the material doesn't yet have the queue control property,
// we should not engage automatic behavior until the shader gets reimported.
bool automaticQueueControl = false;
if (material.HasProperty(Property.QueueControl()))
{
var queueControl = material.GetFloat(Property.QueueControl());
if (queueControl < 0.0f)
{
// The property was added with a negative value, indicating it needs to be validated for this material
UpdateMaterialRenderQueueControl(material);
}
automaticQueueControl = (material.GetFloat(Property.QueueControl()) == (float)QueueControl.Auto);
}
return automaticQueueControl;
}
public override void ValidateMaterial(Material material) => SetupSurface(material);
public static void SetupSurface(Material material)
{
bool alphaClipping = false;
var alphaClipProp = Property.AlphaClip();
if (material.HasProperty(alphaClipProp))
alphaClipping = material.GetFloat(alphaClipProp) >= 0.5;
CoreUtils.SetKeyword(material, Keyword.SG_AlphaTestOn, alphaClipping);
CoreUtils.SetKeyword(material, Keyword.SG_AlphaClip, alphaClipping);
int renderQueue = material.shader.renderQueue;
var surfaceTypeProp = Property.Surface();
if (material.HasProperty(surfaceTypeProp))
{
bool zwrite = false;
var surfaceType = (SurfaceType)material.GetFloat(surfaceTypeProp);
if (surfaceType == SurfaceType.Opaque)
{
string renderType;
if (alphaClipping)
{
renderQueue = (int)RenderQueue.AlphaTest;
renderType = "TransparentCutout";
}
else
{
renderQueue = (int)RenderQueue.Geometry;
renderType = "Opaque";
}
material.SetOverrideTag("RenderType", "Transparent");
material.SetOverrideTag("RenderType", renderType);
SetBlendMode(material, UnityEngine.Rendering.BlendMode.One, UnityEngine.Rendering.BlendMode.Zero);
material.DisableKeyword(Keyword.SG_AlphaPremultiplyOn);
zwrite = true;
}
else
{
var blendProp = Property.Blend();
if (material.HasProperty(blendProp))
{
var blendMode = (BlendMode)material.GetFloat(blendProp);
if (blendMode == BlendMode.Alpha)
SetBlendMode(material, UnityEngine.Rendering.BlendMode.SrcAlpha, UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
else if (blendMode == BlendMode.Premultiply)
SetBlendMode(material, UnityEngine.Rendering.BlendMode.One, UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
else if (blendMode == BlendMode.Additive)
SetBlendMode(material, UnityEngine.Rendering.BlendMode.SrcAlpha, UnityEngine.Rendering.BlendMode.One);
else if (blendMode == BlendMode.Multiply)
SetBlendMode(material, UnityEngine.Rendering.BlendMode.DstColor, UnityEngine.Rendering.BlendMode.Zero);
CoreUtils.SetKeyword(material, Keyword.SG_AlphaPremultiplyOn, blendMode == BlendMode.Premultiply);
}
renderQueue = (int)RenderQueue.Transparent;
material.SetOverrideTag("RenderType", "Transparent");
}
CoreUtils.SetKeyword(material, Keyword.SG_SurfaceTypeTransparent, surfaceType == SurfaceType.Transparent);
// check for override enum
var zwriteProp = Property.ZWriteControl();
if (material.HasProperty(zwriteProp))
{
var zwriteControl = (UnityEditor.Rendering.BuiltIn.ShaderGraph.ZWriteControl)material.GetFloat(zwriteProp);
if (zwriteControl == UnityEditor.Rendering.BuiltIn.ShaderGraph.ZWriteControl.ForceEnabled)
zwrite = true;
else if (zwriteControl == UnityEditor.Rendering.BuiltIn.ShaderGraph.ZWriteControl.ForceDisabled)
zwrite = false;
}
SetMaterialZWriteProperty(material, zwrite);
}
// must always apply queue offset, even if not set to material control
if (material.HasProperty(Property.QueueOffset()))
renderQueue += (int)material.GetFloat(Property.QueueOffset());
// apply automatic render queue
bool automaticRenderQueue = GetAutomaticQueueControlSetting(material);
if (automaticRenderQueue && (renderQueue != material.renderQueue))
material.renderQueue = renderQueue;
}
static void SetMaterialZWriteProperty(Material material, bool state)
{
var zWriteProp = Property.ZWrite();
if (material.HasProperty(zWriteProp))
{
material.SetFloat(zWriteProp, state == true ? 1.0f : 0.0f);
}
}
static void SetBlendMode(Material material, UnityEngine.Rendering.BlendMode srcBlendMode, UnityEngine.Rendering.BlendMode dstBlendMode)
{
var srcBlendProp = Property.SrcBlend();
if (material.HasProperty(srcBlendProp))
material.SetFloat(srcBlendProp, (int)srcBlendMode);
var dstBlendProp = Property.DstBlend();
if (material.HasProperty(dstBlendProp))
material.SetFloat(dstBlendProp, (int)dstBlendMode);
}
public static void DoPopup(GUIContent label, MaterialEditor materialEditor, MaterialProperty property, string[] options)
{
if (property == null)
return;
materialEditor.PopupShaderProperty(property, label, options);
}
public static void DoIntPopup(GUIContent label, MaterialEditor materialEditor, MaterialProperty property, string[] options, int[] optionValues)
{
if (property == null)
return;
materialEditor.IntPopupShaderProperty(property, label.text, options, optionValues);
}
public static void DrawFloatToggleProperty(GUIContent styles, MaterialProperty prop)
{
if (prop == null)
return;
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = prop.hasMixedValue;
bool newValue = EditorGUILayout.Toggle(styles, prop.floatValue == 1);
if (EditorGUI.EndChangeCheck())
prop.floatValue = newValue ? 1.0f : 0.0f;
EditorGUI.showMixedValue = false;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9294601d4849f0445b9a00cc1d2de1a8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,13 @@
using UnityEngine;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
// Currently this is just the base shader gui, but was put in place in case they're separate later
public class BuiltInLitGUI : BuiltInBaseShaderGUI
{
public static void UpdateMaterial(Material material)
{
SetupSurface(material);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 81c69b3c2bf4fe14ab3de9d0335c8cd8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,13 @@
using UnityEngine;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
// Currently this is just the base shader gui, but was put in place in case they're separate later
public class BuiltInUnlitGUI : BuiltInBaseShaderGUI
{
public static void UpdateMaterial(Material material)
{
SetupSurface(material);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 850309cc5616532479e9a794256f66e7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 70b217def86e248a0bc2815bd1edf95f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a5dc74f441d4a4402b0ef3e2b5977c37
AssemblyDefinitionReferenceImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,15 @@
using System.Runtime.CompilerServices;
using UnityEngine;
[assembly: InternalsVisibleTo("Unity.ShaderGraph.Editor")]
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
internal static class MaterialAccess
{
internal static int ReadMaterialRawRenderQueue(Material mat)
{
return mat.rawRenderQueue;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0a17aaa807e5d45b8b0d33beaae4955e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: aa741e0e92d3608409867b98aabf2070
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cebe13fbe292c6648ae282c4ce3908e8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,31 @@
using System;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
static class CreateLitShaderGraph
{
[MenuItem("Assets/Create/Shader Graph/BuiltIn/Lit Shader Graph", priority = CoreUtils.Sections.section1 + CoreUtils.Priorities.assetsCreateShaderMenuPriority)]
public static void CreateLitGraph()
{
var target = (BuiltInTarget)Activator.CreateInstance(typeof(BuiltInTarget));
target.TrySetActiveSubTarget(typeof(BuiltInLitSubTarget));
var blockDescriptors = new[]
{
BlockFields.VertexDescription.Position,
BlockFields.VertexDescription.Normal,
BlockFields.VertexDescription.Tangent,
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.NormalTS,
BlockFields.SurfaceDescription.Metallic,
BlockFields.SurfaceDescription.Smoothness,
BlockFields.SurfaceDescription.Emission,
BlockFields.SurfaceDescription.Occlusion,
};
GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2d3968242695bd843acae565342dc94a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,26 @@
using System;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
static class CreateUnlitShaderGraph
{
[MenuItem("Assets/Create/Shader Graph/BuiltIn/Unlit Shader Graph", priority = CoreUtils.Sections.section1 + CoreUtils.Priorities.assetsCreateShaderMenuPriority)]
public static void CreateUnlitGraph()
{
var target = (BuiltInTarget)Activator.CreateInstance(typeof(BuiltInTarget));
target.TrySetActiveSubTarget(typeof(BuiltInUnlitSubTarget));
var blockDescriptors = new[]
{
BlockFields.VertexDescription.Position,
BlockFields.VertexDescription.Normal,
BlockFields.VertexDescription.Tangent,
BlockFields.SurfaceDescription.BaseColor,
};
GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6ef7b00e3331f8248bae14525a086473
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,34 @@
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
internal static class BuiltInFields
{
#region Tags
public const string kFeatures = "features";
public const string kSurfaceType = "SurfaceType";
public const string kBlendMode = "BlendMode";
#endregion
#region Fields
// TODO: figure which ones are actually URP only, leave those here and put others shared/core Fields in Fields.cs
public static FieldDescriptor SurfaceOpaque = new FieldDescriptor(kSurfaceType, "Opaque", "_SURFACE_TYPE_OPAQUE 1");
public static FieldDescriptor SurfaceTransparent = new FieldDescriptor(kSurfaceType, "Transparent", "_SURFACE_TYPE_TRANSPARENT 1");
public static FieldDescriptor BlendAdd = new FieldDescriptor(kBlendMode, "Add", "_BLENDMODE_ADD 1");
public static FieldDescriptor BlendPremultiply = new FieldDescriptor(kBlendMode, "Premultiply", "_ALPHAPREMULTIPLY_ON 1");
public static FieldDescriptor BlendMultiply = new FieldDescriptor(kBlendMode, "Multiply", "_BLENDMODE_MULTIPLY 1");
public static FieldDescriptor VelocityPrecomputed = new FieldDescriptor(string.Empty, "AddPrecomputedVelocity", "_ADD_PRECOMPUTED_VELOCITY");
public static FieldDescriptor SpecularSetup = new FieldDescriptor(string.Empty, "SpecularSetup", "_SPECULAR_SETUP");
public static FieldDescriptor Normal = new FieldDescriptor(string.Empty, "Normal", "_NORMALMAP 1");
public static FieldDescriptor NormalDropOffTS = new FieldDescriptor(string.Empty, "NormalDropOffTS", "_NORMAL_DROPOFF_TS 1");
public static FieldDescriptor NormalDropOffOS = new FieldDescriptor(string.Empty, "NormalDropOffOS", "_NORMAL_DROPOFF_OS 1");
public static FieldDescriptor NormalDropOffWS = new FieldDescriptor(string.Empty, "NormalDropOffWS", "_NORMAL_DROPOFF_WS 1");
#endregion
// A predicate is field that has a matching template command, for example: $<name> <content>
// It is only used to enable/disable <content> in the tempalate
#region Predicates
//public static FieldDescriptor PredicateClearCoat = new FieldDescriptor(string.Empty, "ClearCoat", "_CLEARCOAT 1");
#endregion
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c416272edf15143c4a421402c821ee45
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,19 @@
using System;
using UnityEngine;
using UnityEditor.Rendering.BuiltIn;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
[Serializable]
sealed class BuiltInMetadata : ScriptableObject
{
[SerializeField]
ShaderUtils.ShaderID m_ShaderID;
public ShaderUtils.ShaderID shaderID
{
get => m_ShaderID;
set => m_ShaderID = value;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 44dc38476d77dd54d91833b3d57ee8b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,87 @@
using UnityEditor.Rendering.BuiltIn.ShaderGraph;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Internal;
namespace UnityEditor.Rendering.BuiltIn
{
internal static class Property
{
public static string SpecularWorkflowMode() { return SG_SpecularWorkflowMode; }
public static string Surface() { return SG_Surface; }
public static string Blend() { return SG_Blend; }
public static string AlphaClip() { return SG_AlphaClip; }
public static string SrcBlend() { return SG_SrcBlend; }
public static string DstBlend() { return SG_DstBlend; }
public static string ZWrite() { return SG_ZWrite; }
public static string ZWriteControl() { return SG_ZWriteControl; }
public static string ZTest() { return SG_ZTest; } // no HW equivalent
public static string Cull() { return SG_Cull; }
public static string CastShadows() { return SG_CastShadows; }
public static string ReceiveShadows() { return SG_ReceiveShadows; }
public static string QueueOffset() { return SG_QueueOffset; }
public static string QueueControl() { return SG_QueueControl; }
// for shadergraph shaders (renamed more uniquely to avoid potential naming collisions with HDRP properties and user properties)
public static readonly string SG_SpecularWorkflowMode = "_BUILTIN_WorkflowMode";
public static readonly string SG_Surface = "_BUILTIN_Surface";
public static readonly string SG_Blend = "_BUILTIN_Blend";
public static readonly string SG_AlphaClip = "_BUILTIN_AlphaClip";
public static readonly string SG_SrcBlend = "_BUILTIN_SrcBlend";
public static readonly string SG_DstBlend = "_BUILTIN_DstBlend";
public static readonly string SG_ZWrite = "_BUILTIN_ZWrite";
public static readonly string SG_ZWriteControl = "_BUILTIN_ZWriteControl";
public static readonly string SG_ZTest = "_BUILTIN_ZTest";
public static readonly string SG_Cull = "_BUILTIN_CullMode";
public static readonly string SG_CastShadows = "_BUILTIN_CastShadows";
public static readonly string SG_ReceiveShadows = "_BUILTIN_ReceiveShadows";
public static readonly string SG_QueueOffset = "_BUILTIN_QueueOffset";
public static readonly string SG_QueueControl = "_BUILTIN_QueueControl";
// Global Illumination requires some properties to be named specifically:
public static readonly string EmissionMap = "_EmissionMap";
public static readonly string EmissionColor = "_EmissionColor";
public static Vector1ShaderProperty WorkflowModeProperty(WorkflowMode workflowModeDefault)
{
return new Vector1ShaderProperty()
{
floatType = FloatType.Default,
hidden = true,
overrideHLSLDeclaration = true,
hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
value = (float)workflowModeDefault,
displayName = "Workflow Mode",
overrideReferenceName = SG_SpecularWorkflowMode,
};
}
}
internal static class Keyword
{
// for ShaderGraph shaders (renamed more uniquely to avoid potential naming collisions with HDRP and user keywords).
// These should be used to control the above (currently in the template)
public static readonly string SG_ReceiveShadowsOff = "_BUILTIN_RECEIVE_SHADOWS_OFF";
public static readonly string SG_Emission = "_BUILTIN_EMISSION";
public static readonly string SG_AlphaTestOn = "_BUILTIN_ALPHATEST_ON";
public static readonly string SG_AlphaClip = "_BUILTIN_AlphaClip";
public static readonly string SG_SurfaceTypeTransparent = "_BUILTIN_SURFACE_TYPE_TRANSPARENT";
public static readonly string SG_AlphaPremultiplyOn = "_BUILTIN_ALPHAPREMULTIPLY_ON";
public static readonly string SG_AlphaModulateOn = "_BUILTIN_ALPHAMODULATE_ON";
}
internal static class BuiltInMaterialInspectorUtilities
{
internal static void AddFloatProperty(this PropertyCollector collector, string referenceName, float defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare)
{
collector.AddShaderProperty(new Vector1ShaderProperty
{
floatType = FloatType.Default,
hidden = true,
overrideHLSLDeclaration = true,
hlslDeclarationOverride = declarationType,
value = defaultValue,
overrideReferenceName = referenceName,
});
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 94ef141d84292aa449f735ddb4def15e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
static class BuiltInStructFields
{
public struct Varyings
{
public static string name = "Varyings";
public static FieldDescriptor lightmapUV = new FieldDescriptor(Varyings.name, "lightmapUV", "", ShaderValueType.Float2,
preprocessor: "defined(LIGHTMAP_ON)", subscriptOptions: StructFieldOptions.Optional);
public static FieldDescriptor sh = new FieldDescriptor(Varyings.name, "sh", "", ShaderValueType.Float3,
preprocessor: "!defined(LIGHTMAP_ON)", subscriptOptions: StructFieldOptions.Optional);
public static FieldDescriptor fogFactorAndVertexLight = new FieldDescriptor(Varyings.name, "fogFactorAndVertexLight", "VARYINGS_NEED_FOG_AND_VERTEX_LIGHT", ShaderValueType.Float4,
subscriptOptions: StructFieldOptions.Optional);
public static FieldDescriptor shadowCoord = new FieldDescriptor(Varyings.name, "shadowCoord", "VARYINGS_NEED_SHADOWCOORD", ShaderValueType.Float4,
subscriptOptions: StructFieldOptions.Optional);
public static FieldDescriptor stereoTargetEyeIndexAsRTArrayIdx = new FieldDescriptor(Varyings.name, "stereoTargetEyeIndexAsRTArrayIdx", "", ShaderValueType.Uint,
"SV_RenderTargetArrayIndex", "(defined(UNITY_STEREO_INSTANCING_ENABLED))", StructFieldOptions.Generated);
public static FieldDescriptor stereoTargetEyeIndexAsBlendIdx0 = new FieldDescriptor(Varyings.name, "stereoTargetEyeIndexAsBlendIdx0", "", ShaderValueType.Uint,
"BLENDINDICES0", "(defined(UNITY_STEREO_MULTIVIEW_ENABLED)) || (defined(UNITY_STEREO_INSTANCING_ENABLED) && (defined(SHADER_API_GLES3) || defined(SHADER_API_GLCORE)))");
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 533c433efb1474f5199ca27d33120f21
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,35 @@
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
static class BuiltInStructs
{
public static StructDescriptor Varyings = new StructDescriptor()
{
name = "Varyings",
packFields = true,
populateWithCustomInterpolators = true,
fields = new FieldDescriptor[]
{
StructFields.Varyings.positionCS,
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS,
StructFields.Varyings.tangentWS,
StructFields.Varyings.texCoord0,
StructFields.Varyings.texCoord1,
StructFields.Varyings.texCoord2,
StructFields.Varyings.texCoord3,
StructFields.Varyings.color,
StructFields.Varyings.screenPosition,
BuiltInStructFields.Varyings.lightmapUV,
BuiltInStructFields.Varyings.sh,
BuiltInStructFields.Varyings.fogFactorAndVertexLight,
BuiltInStructFields.Varyings.shadowCoord,
StructFields.Varyings.instanceID,
BuiltInStructFields.Varyings.stereoTargetEyeIndexAsBlendIdx0,
BuiltInStructFields.Varyings.stereoTargetEyeIndexAsRTArrayIdx,
StructFields.Varyings.cullFace,
}
};
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 593a7d950e7c0481098971e6732237b1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0b48c6912333f1a4fa13346aaf390d56
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,43 @@
#ifndef UNITY_BUILD_INTPUT_DATA_INCLUDED
#define UNITY_BUILD_INTPUT_DATA_INCLUDED
void BuildInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = input.positionWS;
#ifdef _NORMALMAP
#if _NORMAL_DROPOFF_TS
// IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped.
float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale();
float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz);
inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, half3x3(input.tangentWS.xyz, bitangent, input.normalWS.xyz));
#elif _NORMAL_DROPOFF_OS
inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS);
#elif _NORMAL_DROPOFF_WS
inputData.normalWS = surfaceDescription.NormalWS;
#endif
#else
inputData.normalWS = input.normalWS;
#endif
inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS);
inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
inputData.shadowCoord = input.shadowCoord;
#elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
inputData.fogCoord = input.fogFactorAndVertexLight.x;
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
#if defined(LIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.lightmapUV, input.sh, inputData.normalWS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.lightmapUV);
#endif
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
}
#endif // UNITY_BUILD_INTPUT_DATA_INCLUDED

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: f1a1da3eef3aa834d9c94eb0a5c04358
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,37 @@
#ifndef SG_DEPTH_ONLY_PASS_INCLUDED
#define SG_DEPTH_ONLY_PASS_INCLUDED
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
half4 frag(PackedVaryings packedInput) : SV_TARGET
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
#if _AlphaClip
clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold);
#endif
float4 outColor = 0;
#ifdef SCENESELECTIONPASS
// We use depth prepass for scene selection in the editor, this code allow to output the outline correctly
outColor = float4(_ObjectId, _PassValue, 1.0, 1.0);
#elif defined(SCENEPICKINGPASS)
outColor = _SelectionID;
#endif
return outColor;
}
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: cd9e404a0c5b4bb4787c63d916f217a2
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,54 @@
#ifndef UNITY_LEGACY_BUILDING_INCLUDED
#define UNITY_LEGACY_BUILDING_INCLUDED
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/SurfaceData.hlsl"
SurfaceData SurfaceDescriptionToSurfaceData(SurfaceDescription surfaceDescription)
{
#if _AlphaClip
half alpha = surfaceDescription.Alpha;
clip(alpha - surfaceDescription.AlphaClipThreshold);
#elif _SURFACE_TYPE_TRANSPARENT
half alpha = surfaceDescription.Alpha;
#else
half alpha = 1;
#endif
#ifdef _SPECULAR_SETUP
float3 specular = surfaceDescription.Specular;
float metallic = 1;
#else
float3 specular = 0;
float metallic = surfaceDescription.Metallic;
#endif
SurfaceData surface = (SurfaceData)0;
surface.albedo = surfaceDescription.BaseColor;
surface.metallic = saturate(metallic);
surface.specular = specular;
surface.smoothness = saturate(surfaceDescription.Smoothness),
surface.occlusion = surfaceDescription.Occlusion,
surface.emission = surfaceDescription.Emission,
surface.alpha = saturate(alpha);
surface.clearCoatMask = 0;
surface.clearCoatSmoothness = 1;
return surface;
}
SurfaceOutputStandard BuildStandardSurfaceOutput(SurfaceDescription surfaceDescription, InputData inputData)
{
SurfaceData surface = SurfaceDescriptionToSurfaceData(surfaceDescription);
SurfaceOutputStandard o = (SurfaceOutputStandard)0;
o.Albedo = surface.albedo;
o.Normal = inputData.normalWS;
o.Metallic = surface.metallic;
o.Smoothness = surface.smoothness;
o.Occlusion = surface.occlusion;
o.Emission = surface.emission;
o.Alpha = surface.alpha;
return o;
}
#endif // UNITY_LEGACY_BUILDING_INCLUDED

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5ef47fafdf6082a4ca29b49f85810af3
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,26 @@
#ifndef UNITY_LEGACY_SURFACE_VERTEX
#define UNITY_LEGACY_SURFACE_VERTEX
struct v2f_surf {
float4 pos;//UNITY_POSITION(pos);
float3 worldNormal;// : TEXCOORD1;
float3 worldPos;// : TEXCOORD2;
float3 viewDir;
float4 lmap;// : TEXCOORD3;
#if UNITY_SHOULD_SAMPLE_SH
half3 sh;// : TEXCOORD3; // SH
#endif
float1 fogCoord; //UNITY_FOG_COORDS(4)
DECLARE_LIGHT_COORDS(4)//unityShadowCoord4 _LightCoord;
UNITY_SHADOW_COORDS(5)//unityShadowCoord4 _ShadowCoord;
//#ifdef DIRLIGHTMAP_COMBINED
float4 tSpace0 : TEXCOORD6;
float4 tSpace1 : TEXCOORD7;
float4 tSpace2 : TEXCOORD8;
//#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
#endif // UNITY_LEGACY_SURFACE_VERTEX

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5461cde96a0881146aed77bccd1c72ec
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,156 @@
#ifndef SG_LIT_META_INCLUDED
#define SG_LIT_META_INCLUDED
#include "UnityMetaPass.cginc"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/SurfaceData.hlsl"
SurfaceData SurfaceDescriptionToSurfaceData(SurfaceDescription surfaceDescription)
{
#if _AlphaClip
half alpha = surfaceDescription.Alpha;
clip(alpha - surfaceDescription.AlphaClipThreshold);
#elif _SURFACE_TYPE_TRANSPARENT
half alpha = surfaceDescription.Alpha;
#else
half alpha = 1;
#endif
SurfaceData surface = (SurfaceData)0;
surface.albedo = surfaceDescription.BaseColor;
surface.alpha = saturate(alpha);
surface.clearCoatMask = 0;
surface.clearCoatSmoothness = 1;
surface.emission = surfaceDescription.Emission;
return surface;
}
SurfaceOutputStandard BuildStandardSurfaceOutput(SurfaceDescription surfaceDescription)
{
SurfaceData surface = SurfaceDescriptionToSurfaceData(surfaceDescription);
SurfaceOutputStandard o = (SurfaceOutputStandard)0;
o.Albedo = surface.albedo;
o.Metallic = surface.metallic;
o.Smoothness = surface.smoothness;
o.Occlusion = surface.occlusion;
o.Emission = surface.emission;
o.Alpha = surface.alpha;
return o;
}
v2f_surf MetaVertex(appdata_full v)
{
UNITY_SETUP_INSTANCE_ID(v);
v2f_surf o;
UNITY_INITIALIZE_OUTPUT(v2f_surf,o);
UNITY_TRANSFER_INSTANCE_ID(v,o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.pos = UnityMetaVertexPosition(v.vertex, v.texcoord1.xy, v.texcoord2.xy, unity_LightmapST, unity_DynamicLightmapST);
#ifdef EDITOR_VISUALIZATION
o.vizUV = 0;
o.lightCoord = 0;
if (unity_VisualizationMode == EDITORVIZ_TEXTURE)
o.vizUV = UnityMetaVizUV(unity_EditorViz_UVIndex, v.texcoord.xy, v.texcoord1.xy, v.texcoord2.xy, unity_EditorViz_Texture_ST);
else if (unity_VisualizationMode == EDITORVIZ_SHOWLIGHTMASK)
{
o.vizUV = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw;
o.lightCoord = mul(unity_EditorViz_WorldToLight, mul(unity_ObjectToWorld, float4(v.vertex.xyz, 1)));
}
#endif
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
float3 worldNormal = UnityObjectToWorldNormal(v.normal);
fixed3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz);
fixed tangentSign = v.tangent.w * unity_WorldTransformParams.w;
fixed3 worldBinormal = cross(worldNormal, worldTangent) * tangentSign;
o.tSpace0 = float4(worldTangent.x, worldBinormal.x, worldNormal.x, worldPos.x);
o.tSpace1 = float4(worldTangent.y, worldBinormal.y, worldNormal.y, worldPos.y);
o.tSpace2 = float4(worldTangent.z, worldBinormal.z, worldNormal.z, worldPos.z);
o.worldPos.xyz = worldPos;
return o;
}
void MetaVertex(Attributes input, VertexDescription vertexDescription, inout Varyings varyings)
{
appdata_full v;
ZERO_INITIALIZE(appdata_full, v);
BuildAppDataFull(input, vertexDescription, v);
v2f_surf o = MetaVertex(v);
SurfaceVertexToVaryings(o, varyings);
}
half4 MetaFragment(v2f_surf IN, SurfaceOutputStandard o)
{
UNITY_SETUP_INSTANCE_ID(IN);
#ifdef FOG_COMBINED_WITH_TSPACE
UNITY_EXTRACT_FOG_FROM_TSPACE(IN);
#elif defined FOG_COMBINED_WITH_WORLD_POS
UNITY_EXTRACT_FOG_FROM_WORLD_POS(IN);
#else
UNITY_EXTRACT_FOG(IN);
#endif
#ifdef FOG_COMBINED_WITH_TSPACE
UNITY_RECONSTRUCT_TBN(IN);
#else
UNITY_EXTRACT_TBN(IN);
#endif
float3 worldPos = IN.worldPos.xyz;//float3(IN.tSpace0.w, IN.tSpace1.w, IN.tSpace2.w);
#ifndef USING_DIRECTIONAL_LIGHT
fixed3 lightDir = normalize(UnityWorldSpaceLightDir(worldPos));
#else
fixed3 lightDir = _WorldSpaceLightPos0.xyz;
#endif
fixed3 normalWorldVertex = fixed3(0,0,1);
UnityMetaInput metaIN;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, metaIN);
metaIN.Albedo = o.Albedo;
metaIN.Emission = o.Emission;
#ifdef EDITOR_VISUALIZATION
metaIN.VizUV = IN.vizUV;
metaIN.LightCoord = IN.lightCoord;
#endif
return UnityMetaFragment(metaIN);
}
half4 MetaFragment(SurfaceDescription surfaceDescription, Varyings varyings)
{
v2f_surf vertexSurf;
ZERO_INITIALIZE(v2f_surf, vertexSurf);
VaryingsToSurfaceVertex(varyings, vertexSurf);
SurfaceOutputStandard o = BuildStandardSurfaceOutput(surfaceDescription);
return MetaFragment(vertexSurf, o);
}
PackedVaryings vert(Attributes input)
{
Varyings output;
ZERO_INITIALIZE(Varyings, output);
output = BuildVaryings(input);
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
MetaVertex(input, vertexDescription, output);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
half4 frag(PackedVaryings packedInput) : SV_TARGET
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
half4 color = MetaFragment(surfaceDescription, unpacked);
return color;
}
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 395ef430db5747842b555e50b3c7b330
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,181 @@
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/LegacyBuilding.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/BuildInputData.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/UnityGBuffer.hlsl"
v2f_surf PBRDeferredVertex(appdata_full v)
{
UNITY_SETUP_INSTANCE_ID(v);
v2f_surf o;
UNITY_INITIALIZE_OUTPUT(v2f_surf,o);
UNITY_TRANSFER_INSTANCE_ID(v,o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.pos = UnityObjectToClipPos(v.vertex);
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
float3 worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos.xyz = worldPos;
o.worldNormal = worldNormal;
float3 viewDirForLight = UnityWorldSpaceViewDir(worldPos);
#ifndef DIRLIGHTMAP_OFF
o.viewDir = viewDirForLight;
#endif
#ifdef DYNAMICLIGHTMAP_ON
o.lmap.zw = v.texcoord2.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
#else
o.lmap.zw = 0;
#endif
#ifdef LIGHTMAP_ON
o.lmap.xy = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw;
#ifdef DIRLIGHTMAP_OFF
o.lmapFadePos.xyz = (mul(unity_ObjectToWorld, v.vertex).xyz - unity_ShadowFadeCenterAndType.xyz) * unity_ShadowFadeCenterAndType.w;
o.lmapFadePos.w = (-UnityObjectToViewPos(v.vertex).z) * (1.0 - unity_ShadowFadeCenterAndType.w);
#endif
#else
o.lmap.xy = 0;
#if UNITY_SHOULD_SAMPLE_SH && !UNITY_SAMPLE_FULL_SH_PER_PIXEL
o.sh = 0;
o.sh = ShadeSHPerVertex (worldNormal, o.sh);
#endif
#endif
return o;
}
void PBRDeferredVertex(Attributes input, VertexDescription vertexDescription, inout Varyings varyings)
{
appdata_full v;
ZERO_INITIALIZE(appdata_full, v);
BuildAppDataFull(input, vertexDescription, v);
v2f_surf o = PBRDeferredVertex(v);
SurfaceVertexToVaryings(o, varyings);
}
void PBRDeferredFragment(v2f_surf IN, SurfaceOutputStandard o,
out half4 outGBuffer0 : SV_Target0,
out half4 outGBuffer1 : SV_Target1,
out half4 outGBuffer2 : SV_Target2,
out half4 outEmission : SV_Target3
#if defined(SHADOWS_SHADOWMASK) && (UNITY_ALLOWED_MRT_COUNT > 4)
, out half4 outShadowMask : SV_Target4
#endif
)
{
UNITY_SETUP_INSTANCE_ID(IN);
// prepare and unpack data
#ifdef FOG_COMBINED_WITH_TSPACE
UNITY_EXTRACT_FOG_FROM_TSPACE(IN);
#elif defined FOG_COMBINED_WITH_WORLD_POS
UNITY_EXTRACT_FOG_FROM_WORLD_POS(IN);
#else
UNITY_EXTRACT_FOG(IN);
#endif
float3 worldPos = IN.worldPos.xyz;
#ifndef USING_DIRECTIONAL_LIGHT
fixed3 lightDir = normalize(UnityWorldSpaceLightDir(worldPos));
#else
fixed3 lightDir = _WorldSpaceLightPos0.xyz;
#endif
float3 worldViewDir = normalize(UnityWorldSpaceViewDir(worldPos));
fixed3 normalWorldVertex = fixed3(0,0,1);
normalWorldVertex = IN.worldNormal;
// call surface function
fixed3 originalNormal = o.Normal;
half atten = 1;
// Setup lighting environment
UnityGI gi;
UNITY_INITIALIZE_OUTPUT(UnityGI, gi);
gi.indirect.diffuse = 0;
gi.indirect.specular = 0;
gi.light.color = 0;
gi.light.dir = half3(0,1,0);
// Call GI (lightmaps/SH/reflections) lighting function
UnityGIInput giInput;
UNITY_INITIALIZE_OUTPUT(UnityGIInput, giInput);
giInput.light = gi.light;
giInput.worldPos = worldPos;
giInput.worldViewDir = worldViewDir;
giInput.atten = atten;
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
giInput.lightmapUV = IN.lmap;
#else
giInput.lightmapUV = 0.0;
#endif
#if UNITY_SHOULD_SAMPLE_SH && !UNITY_SAMPLE_FULL_SH_PER_PIXEL
giInput.ambient = IN.sh;
#else
giInput.ambient.rgb = 0.0;
#endif
giInput.probeHDR[0] = unity_SpecCube0_HDR;
giInput.probeHDR[1] = unity_SpecCube1_HDR;
#if defined(UNITY_SPECCUBE_BLENDING) || defined(UNITY_SPECCUBE_BOX_PROJECTION)
giInput.boxMin[0] = unity_SpecCube0_BoxMin; // .w holds lerp value for blending
#endif
#ifdef UNITY_SPECCUBE_BOX_PROJECTION
giInput.boxMax[0] = unity_SpecCube0_BoxMax;
giInput.probePosition[0] = unity_SpecCube0_ProbePosition;
giInput.boxMax[1] = unity_SpecCube1_BoxMax;
giInput.boxMin[1] = unity_SpecCube1_BoxMin;
giInput.probePosition[1] = unity_SpecCube1_ProbePosition;
#endif
LightingStandard_GI(o, giInput, gi);
// call lighting function to output g-buffer
outEmission = LightingStandard_Deferred (o, worldViewDir, gi, outGBuffer0, outGBuffer1, outGBuffer2);
#if defined(SHADOWS_SHADOWMASK) && (UNITY_ALLOWED_MRT_COUNT > 4)
outShadowMask = UnityGetRawBakedOcclusions (IN.lmap.xy, worldPos);
#endif
#ifndef UNITY_HDR_ON
outEmission.rgb = exp2(-outEmission.rgb);
#endif
}
FragmentOutput PBRDeferredFragment(SurfaceDescription surfaceDescription, InputData inputData, Varyings varyings)
{
v2f_surf vertexSurf;
ZERO_INITIALIZE(v2f_surf, vertexSurf);
VaryingsToSurfaceVertex(varyings, vertexSurf);
SurfaceOutputStandard o = BuildStandardSurfaceOutput(surfaceDescription, inputData);
FragmentOutput result;
PBRDeferredFragment(vertexSurf, o, result.GBuffer0, result.GBuffer1, result.GBuffer2, result.GBuffer3
#if OUTPUT_SHADOWMASK
, result.GBuffer4
#endif
);
return result;
}
PackedVaryings vert(Attributes input)
{
Varyings output;
ZERO_INITIALIZE(Varyings, output);
output = BuildVaryings(input);
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
PBRDeferredVertex(input, vertexDescription, output);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
FragmentOutput frag(PackedVaryings packedInput)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
InputData inputData;
BuildInputData(unpacked, surfaceDescription, inputData);
return PBRDeferredFragment(surfaceDescription, inputData, unpacked);
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 12263a5b80a209c44ae6188994252ecd
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,117 @@
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/LegacyBuilding.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/BuildInputData.hlsl"
v2f_surf PBRForwardAddVertex(appdata_full v)
{
UNITY_SETUP_INSTANCE_ID(v);
v2f_surf o;
UNITY_INITIALIZE_OUTPUT(v2f_surf,o);
UNITY_TRANSFER_INSTANCE_ID(v,o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.pos = UnityObjectToClipPos(v.vertex);
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
float3 worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos.xyz = worldPos;
o.worldNormal = worldNormal;
UNITY_TRANSFER_LIGHTING(o,v.texcoord1.xy); // pass shadow and, possibly, light cookie coordinates to pixel shader
UNITY_TRANSFER_FOG(o,o.pos); // pass fog coordinates to pixel shader
return o;
}
void PBRForwardAddVertex(Attributes input, VertexDescription vertexDescription, inout Varyings varyings)
{
appdata_full v;
ZERO_INITIALIZE(appdata_full, v);
BuildAppDataFull(input, vertexDescription, v);
v2f_surf o = PBRForwardAddVertex(v);
SurfaceVertexToVaryings(o, varyings);
}
half4 PBRForwardAddFragment(v2f_surf vertexSurf, SurfaceOutputStandard o)
{
v2f_surf IN = vertexSurf;
UNITY_SETUP_INSTANCE_ID(IN);
#ifdef FOG_COMBINED_WITH_TSPACE
UNITY_EXTRACT_FOG_FROM_TSPACE(IN);
#elif defined FOG_COMBINED_WITH_WORLD_POS
UNITY_EXTRACT_FOG_FROM_WORLD_POS(IN);
#else
UNITY_EXTRACT_FOG(IN);
#endif
float3 worldPos = IN.worldPos.xyz;
#ifndef USING_DIRECTIONAL_LIGHT
fixed3 lightDir = normalize(UnityWorldSpaceLightDir(worldPos));
#else
fixed3 lightDir = _WorldSpaceLightPos0.xyz;
#endif
float3 worldViewDir = normalize(UnityWorldSpaceViewDir(worldPos));
fixed3 normalWorldVertex = fixed3(0,0,1);
normalWorldVertex = IN.worldNormal;
UNITY_LIGHT_ATTENUATION(atten, IN, worldPos)
fixed4 c = 0;
// Setup lighting environment
UnityGI gi;
UNITY_INITIALIZE_OUTPUT(UnityGI, gi);
gi.indirect.diffuse = 0;
gi.indirect.specular = 0;
gi.light.color = _LightColor0.rgb;
gi.light.dir = lightDir;
gi.light.color *= atten;
c += LightingStandard (o, worldViewDir, gi);
UNITY_APPLY_FOG(_unity_fogCoord, c); // apply fog
#ifndef _SURFACE_TYPE_TRANSPARENT
UNITY_OPAQUE_ALPHA(c.a);
#endif
return c;
}
half4 PBRForwardAddFragment(SurfaceDescription surfaceDescription, InputData inputData, Varyings varyings)
{
v2f_surf vertexSurf;
ZERO_INITIALIZE(v2f_surf, vertexSurf);
VaryingsToSurfaceVertex(varyings, vertexSurf);
SurfaceOutputStandard o = BuildStandardSurfaceOutput(surfaceDescription, inputData);
return PBRForwardAddFragment(vertexSurf, o);
}
PackedVaryings vert(Attributes input)
{
Varyings output;
ZERO_INITIALIZE(Varyings, output);
output = BuildVaryings(input);
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
PBRForwardAddVertex(input, vertexDescription, output);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
half4 frag(PackedVaryings packedInput) : SV_TARGET
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
InputData inputData;
BuildInputData(unpacked, surfaceDescription, inputData);
half4 color = PBRForwardAddFragment(surfaceDescription, inputData, unpacked);
return color;
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 32b23321ec58ddc4e88879d693256c3a
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,186 @@
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/LegacyBuilding.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/BuildInputData.hlsl"
v2f_surf PBRStandardVertex(appdata_full v)
{
UNITY_SETUP_INSTANCE_ID(v);
v2f_surf o;
UNITY_INITIALIZE_OUTPUT(v2f_surf,o);
UNITY_TRANSFER_INSTANCE_ID(v,o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.pos = UnityObjectToClipPos(v.vertex);
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
float3 worldNormal = UnityObjectToWorldNormal(v.normal);
#if defined(LIGHTMAP_ON) && defined(DIRLIGHTMAP_COMBINED)
fixed3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz);
fixed tangentSign = v.tangent.w * unity_WorldTransformParams.w;
fixed3 worldBinormal = cross(worldNormal, worldTangent) * tangentSign;
#endif
#if defined(LIGHTMAP_ON) && defined(DIRLIGHTMAP_COMBINED) && !defined(UNITY_HALF_PRECISION_FRAGMENT_SHADER_REGISTERS)
o.tSpace0 = float4(worldTangent.x, worldBinormal.x, worldNormal.x, worldPos.x);
o.tSpace1 = float4(worldTangent.y, worldBinormal.y, worldNormal.y, worldPos.y);
o.tSpace2 = float4(worldTangent.z, worldBinormal.z, worldNormal.z, worldPos.z);
#endif
o.worldPos.xyz = worldPos;
o.worldNormal = worldNormal;
#ifdef DYNAMICLIGHTMAP_ON
o.lmap.zw = v.texcoord2.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
#endif
#ifdef LIGHTMAP_ON
o.lmap.xy = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw;
#endif
// SH/ambient and vertex lights
#ifndef LIGHTMAP_ON
#if UNITY_SHOULD_SAMPLE_SH && !UNITY_SAMPLE_FULL_SH_PER_PIXEL
o.sh = 0;
// Approximated illumination from non-important point lights
#ifdef VERTEXLIGHT_ON
o.sh += Shade4PointLights (
unity_4LightPosX0, unity_4LightPosY0, unity_4LightPosZ0,
unity_LightColor[0].rgb, unity_LightColor[1].rgb, unity_LightColor[2].rgb, unity_LightColor[3].rgb,
unity_4LightAtten0, worldPos, worldNormal);
#endif
o.sh = ShadeSHPerVertex (worldNormal, o.sh);
#endif
#endif // !LIGHTMAP_ON
UNITY_TRANSFER_LIGHTING(o,v.texcoord1.xy); // pass shadow and, possibly, light cookie coordinates to pixel shader
#ifdef FOG_COMBINED_WITH_TSPACE
UNITY_TRANSFER_FOG_COMBINED_WITH_TSPACE(o,o.pos); // pass fog coordinates to pixel shader
#elif defined FOG_COMBINED_WITH_WORLD_POS
UNITY_TRANSFER_FOG_COMBINED_WITH_WORLD_POS(o,o.pos); // pass fog coordinates to pixel shader
#else
UNITY_TRANSFER_FOG(o,o.pos); // pass fog coordinates to pixel shader
#endif
return o;
}
void PBRStandardVertex(Attributes input, VertexDescription vertexDescription, inout Varyings varyings)
{
appdata_full v;
ZERO_INITIALIZE(appdata_full, v);
BuildAppDataFull(input, vertexDescription, v);
v2f_surf o = PBRStandardVertex(v);
SurfaceVertexToVaryings(o, varyings);
}
half4 PBRStandardFragment(v2f_surf vertexSurf, SurfaceOutputStandard o)
{
v2f_surf IN = vertexSurf;
UNITY_SETUP_INSTANCE_ID(IN);
#ifdef FOG_COMBINED_WITH_TSPACE
UNITY_EXTRACT_FOG_FROM_TSPACE(IN);
#elif defined FOG_COMBINED_WITH_WORLD_POS
UNITY_EXTRACT_FOG_FROM_WORLD_POS(IN);
#else
UNITY_EXTRACT_FOG(IN);
#endif
float3 worldPos = IN.worldPos.xyz;
#ifndef USING_DIRECTIONAL_LIGHT
fixed3 lightDir = normalize(UnityWorldSpaceLightDir(worldPos));
#else
fixed3 lightDir = _WorldSpaceLightPos0.xyz;
#endif
float3 worldViewDir = normalize(UnityWorldSpaceViewDir(worldPos));
fixed3 normalWorldVertex = fixed3(0,0,1);
normalWorldVertex = IN.worldNormal;
// compute lighting & shadowing factor
UNITY_LIGHT_ATTENUATION(atten, IN, worldPos)
fixed4 c = 0;
// Setup lighting environment
UnityGI gi;
UNITY_INITIALIZE_OUTPUT(UnityGI, gi);
gi.indirect.diffuse = 0;
gi.indirect.specular = 0;
gi.light.color = _LightColor0.rgb;
gi.light.dir = lightDir;
// Call GI (lightmaps/SH/reflections) lighting function
UnityGIInput giInput;
UNITY_INITIALIZE_OUTPUT(UnityGIInput, giInput);
giInput.light = gi.light;
giInput.worldPos = worldPos;
giInput.worldViewDir = worldViewDir;
giInput.atten = atten;
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
giInput.lightmapUV = IN.lmap;
#else
giInput.lightmapUV = 0.0;
#endif
#if UNITY_SHOULD_SAMPLE_SH && !UNITY_SAMPLE_FULL_SH_PER_PIXEL
giInput.ambient = IN.sh;
#else
giInput.ambient.rgb = 0.0;
#endif
giInput.probeHDR[0] = unity_SpecCube0_HDR;
giInput.probeHDR[1] = unity_SpecCube1_HDR;
#if defined(UNITY_SPECCUBE_BLENDING) || defined(UNITY_SPECCUBE_BOX_PROJECTION)
giInput.boxMin[0] = unity_SpecCube0_BoxMin; // .w holds lerp value for blending
#endif
#ifdef UNITY_SPECCUBE_BOX_PROJECTION
giInput.boxMax[0] = unity_SpecCube0_BoxMax;
giInput.probePosition[0] = unity_SpecCube0_ProbePosition;
giInput.boxMax[1] = unity_SpecCube1_BoxMax;
giInput.boxMin[1] = unity_SpecCube1_BoxMin;
giInput.probePosition[1] = unity_SpecCube1_ProbePosition;
#endif
LightingStandard_GI(o, giInput, gi);
// realtime lighting: call lighting function
c += LightingStandard (o, worldViewDir, gi);
c.rgb += o.Emission;
UNITY_APPLY_FOG(_unity_fogCoord, c); // apply fog
#ifndef _SURFACE_TYPE_TRANSPARENT
UNITY_OPAQUE_ALPHA(c.a);
#endif
return c;
}
half4 PBRStandardFragment(SurfaceDescription surfaceDescription, InputData inputData, Varyings varyings)
{
v2f_surf vertexSurf;
ZERO_INITIALIZE(v2f_surf, vertexSurf);
VaryingsToSurfaceVertex(varyings, vertexSurf);
SurfaceOutputStandard o = BuildStandardSurfaceOutput(surfaceDescription, inputData);
return PBRStandardFragment(vertexSurf, o);
}
PackedVaryings vert(Attributes input)
{
Varyings output;
ZERO_INITIALIZE(Varyings, output);
output = BuildVaryings(input);
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
PBRStandardVertex(input, vertexDescription, output);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
half4 frag(PackedVaryings packedInput) : SV_TARGET
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
InputData inputData;
BuildInputData(unpacked, surfaceDescription, inputData);
half4 color = PBRStandardFragment(surfaceDescription, inputData, unpacked);
return color;
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 6fca0a7fb5d1b8648a17c83915199f6e
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,83 @@
void BuildInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData)
{
inputData.positionWS = input.positionWS;
#ifdef _NORMALMAP
#if _NORMAL_DROPOFF_TS
// IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped.
float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale();
float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz);
inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, half3x3(input.tangentWS.xyz, bitangent, input.normalWS.xyz));
#elif _NORMAL_DROPOFF_OS
inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS);
#elif _NORMAL_DROPOFF_WS
inputData.normalWS = surfaceDescription.NormalWS;
#endif
#else
inputData.normalWS = input.normalWS;
#endif
inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS);
inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
#if defined(MAIN_LIGHT_CALCULATE_SHADOWS)
inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
inputData.fogCoord = input.fogFactorAndVertexLight.x;
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
inputData.bakedGI = SAMPLE_GI(input.lightmapUV, input.sh, inputData.normalWS);
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.lightmapUV);
}
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
FragmentOutput frag(PackedVaryings packedInput)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
#if _AlphaClip
half alpha = surfaceDescription.Alpha;
clip(alpha - surfaceDescription.AlphaClipThreshold);
#elif _SURFACE_TYPE_TRANSPARENT
half alpha = surfaceDescription.Alpha;
#else
half alpha = 1;
#endif
InputData inputData;
BuildInputData(unpacked, surfaceDescription, inputData);
#ifdef _SPECULAR_SETUP
float3 specular = surfaceDescription.Specular;
float metallic = 1;
#else
float3 specular = 0;
float metallic = surfaceDescription.Metallic;
#endif
// in LitForwardPass GlobalIllumination (and temporarily LightingPhysicallyBased) are called inside BuiltInFragmentPBR
// in Deferred rendering we store the sum of these values (and of emission as well) in the GBuffer
BRDFData brdfData;
InitializeBRDFData(surfaceDescription.BaseColor, metallic, specular, surfaceDescription.Smoothness, alpha, brdfData);
Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, inputData.shadowMask);
MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI, inputData.shadowMask);
half3 color = GlobalIllumination(brdfData, inputData.bakedGI, surfaceDescription.Occlusion, inputData.normalWS, inputData.viewDirectionWS);
return BRDFDataToGbuffer(brdfData, inputData, surfaceDescription.Smoothness, surfaceDescription.Emission + color, surfaceDescription.Occlusion);
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 3ed09dfc4bb69694ca13ae03dbab44df
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@
#ifndef BUILTIN_SHADERPASS_INCLUDED
#define BUILTIN_SHADERPASS_INCLUDED
#define SHADERPASS_FORWARD (0)
#define SHADERPASS_GBUFFER (1)
#define SHADERPASS_DEPTHONLY (2)
#define SHADERPASS_SHADOWCASTER (3)
#define SHADERPASS_META (4)
#define SHADERPASS_UNLIT (5)
#define SHADERPASS_SPRITELIT (6)
#define SHADERPASS_SPRITENORMAL (7)
#define SHADERPASS_SPRITEFORWARD (8)
#define SHADERPASS_SPRITEUNLIT (9)
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 65e35b38e39fde248977f1e9a8ec2e10
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,92 @@
#ifndef SG_SHADOW_PASS_INCLUDED
#define SG_SHADOW_PASS_INCLUDED
v2f_surf ShadowCasterVertex(appdata_full v)
{
UNITY_SETUP_INSTANCE_ID(v);
v2f_surf o;
UNITY_INITIALIZE_OUTPUT(v2f_surf,o);
UNITY_TRANSFER_INSTANCE_ID(v,o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
float3 worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos.xyz = worldPos;
TRANSFER_SHADOW_CASTER_NORMALOFFSET(o)
return o;
}
void ShadowCasterVertex(Attributes input, VertexDescription vertexDescription, inout Varyings varyings)
{
appdata_full v;
ZERO_INITIALIZE(appdata_full, v);
BuildAppDataFull(input, vertexDescription, v);
v2f_surf o = ShadowCasterVertex(v);
SurfaceVertexToVaryings(o, varyings);
}
half4 ShadowCasterFragment(v2f_surf IN)
{
UNITY_SETUP_INSTANCE_ID(IN);
#ifdef FOG_COMBINED_WITH_TSPACE
UNITY_EXTRACT_FOG_FROM_TSPACE(IN);
#elif defined FOG_COMBINED_WITH_WORLD_POS
UNITY_EXTRACT_FOG_FROM_WORLD_POS(IN);
#else
UNITY_EXTRACT_FOG(IN);
#endif
float3 worldPos = IN.worldPos.xyz;
#ifndef USING_DIRECTIONAL_LIGHT
fixed3 lightDir = normalize(UnityWorldSpaceLightDir(worldPos));
#else
fixed3 lightDir = _WorldSpaceLightPos0.xyz;
#endif
fixed3 normalWorldVertex = fixed3(0,0,1);
SHADOW_CASTER_FRAGMENT(IN)
}
half4 ShadowCasterFragment(Varyings varyings)
{
v2f_surf vertexSurf;
ZERO_INITIALIZE(v2f_surf, vertexSurf);
VaryingsToSurfaceVertex(varyings, vertexSurf);
return ShadowCasterFragment(vertexSurf);
}
PackedVaryings vert(Attributes input)
{
Varyings output;
ZERO_INITIALIZE(Varyings, output);
output = BuildVaryings(input);
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
ShadowCasterVertex(input, vertexDescription, output);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
half4 frag(PackedVaryings packedInput) : SV_TARGET
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
#if _AlphaClip
half alpha = surfaceDescription.Alpha;
clip(alpha - surfaceDescription.AlphaClipThreshold);
#endif
half4 color = ShadowCasterFragment(unpacked);
return color;
}
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 35c8158e574671d43b32c60a61df1b0f
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
half4 _RendererColor;
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
output.color *= _RendererColor;
PackedVaryings packedOutput = PackVaryings(output);
return packedOutput;
}
half4 frag(PackedVaryings packedInput) : SV_TARGET
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
#ifdef BUILTIN_USELEGACYSPRITEBLOCKS
half4 color = surfaceDescription.SpriteColor;
#else
half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha);
#endif
#if ALPHA_CLIP_THRESHOLD
clip(color.a - surfaceDescription.AlphaClipThreshold);
#endif
#ifndef HAVE_VFX_MODIFICATION
color *= unpacked.color;
#endif
return color;
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 7c499715fdb4d7c479dcd3fd13abe0d0
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,32 @@
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = PackVaryings(output);
return packedOutput;
}
half4 frag(PackedVaryings packedInput) : SV_TARGET
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
#if _AlphaClip
half alpha = surfaceDescription.Alpha;
clip(alpha - surfaceDescription.AlphaClipThreshold);
#elif _SURFACE_TYPE_TRANSPARENT
half alpha = surfaceDescription.Alpha;
#else
half alpha = 1;
#endif
#ifdef _ALPHAPREMULTIPLY_ON
surfaceDescription.BaseColor *= alpha;
#endif
return half4(surfaceDescription.BaseColor, alpha);
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 50370b309724a0440808e87f08aed757
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,136 @@
#ifndef BUILTIN_TARGET_API
#if (SHADERPASS == SHADERPASS_SHADOWCASTER)
// Shadow Casting Light geometric parameters. These variables are used when applying the shadow Normal Bias and are set by UnityEngine.Rendering.Universal.ShadowUtils.SetupShadowCasterConstantBuffer in com.unity.render-pipelines.universal/Runtime/ShadowUtils.cs
// For Directional lights, _LightDirection is used when applying shadow Normal Bias.
// For Spot lights and Point lights, _LightPosition is used to compute the actual light direction because it is different at each shadow caster geometry vertex.
float3 _LightDirection;
float3 _LightPosition;
#endif
#endif
Varyings BuildVaryings(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
#if defined(FEATURES_GRAPH_VERTEX)
// Evaluate Vertex Graph
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
#if defined(CUSTOMINTERPOLATOR_VARYPASSTHROUGH_FUNC)
CustomInterpolatorPassThroughFunc(output, vertexDescription);
#endif
// Assign modified vertex attributes
input.positionOS = vertexDescription.Position;
#if defined(VARYINGS_NEED_NORMAL_WS)
input.normalOS = vertexDescription.Normal;
#endif //FEATURES_GRAPH_NORMAL
#if defined(VARYINGS_NEED_TANGENT_WS)
input.tangentOS.xyz = vertexDescription.Tangent.xyz;
#endif //FEATURES GRAPH TANGENT
#endif //FEATURES_GRAPH_VERTEX
// TODO: Avoid path via VertexPositionInputs (BuiltIn)
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
// Returns the camera relative position (if enabled)
float3 positionWS = TransformObjectToWorld(input.positionOS);
#ifdef ATTRIBUTES_NEED_NORMAL
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
#else
// Required to compile ApplyVertexModification that doesn't use normal.
float3 normalWS = float3(0.0, 0.0, 0.0);
#endif
#ifdef ATTRIBUTES_NEED_TANGENT
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
#endif
// TODO: Change to inline ifdef
// Do vertex modification in camera relative space (if enabled)
#if defined(HAVE_VERTEX_MODIFICATION)
ApplyVertexModification(input, normalWS, positionWS, _TimeParameters.xyz);
#endif
#ifdef VARYINGS_NEED_POSITION_WS
output.positionWS = positionWS;
#endif
#ifdef VARYINGS_NEED_NORMAL_WS
output.normalWS = normalWS; // normalized in TransformObjectToWorldNormal()
#endif
#ifdef VARYINGS_NEED_TANGENT_WS
output.tangentWS = tangentWS; // normalized in TransformObjectToWorldDir()
#endif
// Handled by the legacy pipeline
#ifndef BUILTIN_TARGET_API
#if (SHADERPASS == SHADERPASS_SHADOWCASTER)
// Define shadow pass specific clip position for BuiltIn
#if _CASTING_PUNCTUAL_LIGHT_SHADOW
float3 lightDirectionWS = normalize(_LightPosition - positionWS);
#else
float3 lightDirectionWS = _LightDirection;
#endif
output.positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirectionWS));
#if UNITY_REVERSED_Z
output.positionCS.z = min(output.positionCS.z, UNITY_NEAR_CLIP_VALUE);
#else
output.positionCS.z = max(output.positionCS.z, UNITY_NEAR_CLIP_VALUE);
#endif
#elif (SHADERPASS == SHADERPASS_META)
output.positionCS = MetaVertexPosition(float4(input.positionOS, 0), input.uv1, input.uv2, unity_LightmapST, unity_DynamicLightmapST);
#else
output.positionCS = TransformWorldToHClip(positionWS);
#endif
#else
output.positionCS = TransformWorldToHClip(positionWS);
#endif
#if defined(VARYINGS_NEED_TEXCOORD0) || defined(VARYINGS_DS_NEED_TEXCOORD0)
output.texCoord0 = input.uv0;
#endif
#if defined(VARYINGS_NEED_TEXCOORD1) || defined(VARYINGS_DS_NEED_TEXCOORD1)
output.texCoord1 = input.uv1;
#endif
#if defined(VARYINGS_NEED_TEXCOORD2) || defined(VARYINGS_DS_NEED_TEXCOORD2)
output.texCoord2 = input.uv2;
#endif
#if defined(VARYINGS_NEED_TEXCOORD3) || defined(VARYINGS_DS_NEED_TEXCOORD3)
output.texCoord3 = input.uv3;
#endif
#if defined(VARYINGS_NEED_COLOR) || defined(VARYINGS_DS_NEED_COLOR)
output.color = input.color;
#endif
#ifdef VARYINGS_NEED_SCREENPOSITION
output.screenPosition = vertexInput.positionNDC;
#endif
// Handled by the legacy pipeline
#ifndef BUILTIN_TARGET_API
#if (SHADERPASS == SHADERPASS_FORWARD) || (SHADERPASS == SHADERPASS_GBUFFER)
OUTPUT_LIGHTMAP_UV(input.uv1, unity_LightmapST, output.lightmapUV);
OUTPUT_SH(normalWS, output.sh);
#endif
#ifdef VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
half3 vertexLight = VertexLighting(positionWS, normalWS);
half fogFactor = ComputeFogFactor(output.positionCS.z);
output.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#endif
#endif
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
output.shadowCoord = GetShadowCoord(vertexInput);
#endif
return output;
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 48ba7a8ce29978c4690d3d53549a5a4c
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6d8d9b2bfb6f27b478e969b90661882b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,658 @@
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using UnityEditor.ShaderGraph.Legacy;
using static UnityEditor.Rendering.BuiltIn.ShaderUtils;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
sealed class BuiltInLitSubTarget : BuiltInSubTarget
{
static readonly GUID kSourceCodeGuid = new GUID("8c2d5b55aa47443878a55a05f4294270"); // BuiltInLitSubTarget.cs
[SerializeField]
WorkflowMode m_WorkflowMode = WorkflowMode.Metallic;
[SerializeField]
NormalDropOffSpace m_NormalDropOffSpace = NormalDropOffSpace.Tangent;
public BuiltInLitSubTarget()
{
displayName = "Lit";
}
protected override ShaderID shaderID => ShaderID.SG_Lit;
public WorkflowMode workflowMode
{
get => m_WorkflowMode;
set => m_WorkflowMode = value;
}
public NormalDropOffSpace normalDropOffSpace
{
get => m_NormalDropOffSpace;
set => m_NormalDropOffSpace = value;
}
public override bool IsActive() => true;
public override void Setup(ref TargetSetupContext context)
{
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
if (!context.HasCustomEditorForRenderPipeline(""))
context.AddCustomEditorForRenderPipeline(typeof(BuiltInLitGUI).FullName, "");
// Process SubShaders
context.AddSubShader(SubShaders.Lit(target, target.renderType, target.renderQueue));
}
public override void ProcessPreviewMaterial(Material material)
{
if (target.allowMaterialOverride)
{
// copy our target's default settings into the material
// (technically not necessary since we are always recreating the material from the shader each time,
// which will pull over the defaults from the shader definition)
// but if that ever changes, this will ensure the defaults are set
material.SetFloat(Property.SpecularWorkflowMode(), (float)workflowMode);
material.SetFloat(Property.Surface(), (float)target.surfaceType);
material.SetFloat(Property.Blend(), (float)target.alphaMode);
material.SetFloat(Property.AlphaClip(), target.alphaClip ? 1.0f : 0.0f);
material.SetFloat(Property.Cull(), (int)target.renderFace);
material.SetFloat(Property.ZWriteControl(), (float)target.zWriteControl);
material.SetFloat(Property.ZTest(), (float)target.zTestMode);
}
// We always need these properties regardless of whether the material is allowed to override
// Queue control & offset enable correct automatic render queue behavior
// Control == 0 is automatic, 1 is user-specified render queue
material.SetFloat(Property.QueueOffset(), 0.0f);
material.SetFloat(Property.QueueControl(), (float)BuiltInBaseShaderGUI.QueueControl.Auto);
// call the full unlit material setup function
BuiltInLitGUI.UpdateMaterial(material);
}
public override void GetFields(ref TargetFieldContext context)
{
var descs = context.blocks.Select(x => x.descriptor);
// Lit
context.AddField(BuiltInFields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object);
context.AddField(BuiltInFields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent);
context.AddField(BuiltInFields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World);
context.AddField(BuiltInFields.SpecularSetup, workflowMode == WorkflowMode.Specular);
context.AddField(BuiltInFields.Normal, descs.Contains(BlockFields.SurfaceDescription.NormalOS) ||
descs.Contains(BlockFields.SurfaceDescription.NormalTS) ||
descs.Contains(BlockFields.SurfaceDescription.NormalWS));
}
public override void GetActiveBlocks(ref TargetActiveBlockContext context)
{
context.AddBlock(BlockFields.SurfaceDescription.Smoothness);
context.AddBlock(BlockFields.SurfaceDescription.NormalOS, normalDropOffSpace == NormalDropOffSpace.Object);
context.AddBlock(BlockFields.SurfaceDescription.NormalTS, normalDropOffSpace == NormalDropOffSpace.Tangent);
context.AddBlock(BlockFields.SurfaceDescription.NormalWS, normalDropOffSpace == NormalDropOffSpace.World);
context.AddBlock(BlockFields.SurfaceDescription.Emission);
context.AddBlock(BlockFields.SurfaceDescription.Occlusion);
context.AddBlock(BlockFields.SurfaceDescription.Specular, (workflowMode == WorkflowMode.Specular) || target.allowMaterialOverride);
context.AddBlock(BlockFields.SurfaceDescription.Metallic, (workflowMode == WorkflowMode.Metallic) || target.allowMaterialOverride);
context.AddBlock(BlockFields.SurfaceDescription.Alpha, (target.surfaceType == SurfaceType.Transparent || target.alphaClip) || target.allowMaterialOverride);
context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, (target.alphaClip) || target.allowMaterialOverride);
}
public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
if (target.allowMaterialOverride)
{
base.CollectShaderProperties(collector, generationMode);
// setup properties using the defaults
collector.AddFloatProperty(Property.Surface(), (float)target.surfaceType);
collector.AddFloatProperty(Property.Blend(), (float)target.alphaMode);
collector.AddFloatProperty(Property.AlphaClip(), target.alphaClip ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend(), 1.0f); // always set by material inspector (TODO : get src/dst blend and set here?)
collector.AddFloatProperty(Property.DstBlend(), 0.0f); // always set by material inspector
collector.AddFloatProperty(Property.ZWrite(), (target.surfaceType == SurfaceType.Opaque) ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.ZWriteControl(), (float)target.zWriteControl);
collector.AddFloatProperty(Property.ZTest(), (float)target.zTestMode); // ztest mode is designed to directly pass as ztest
collector.AddFloatProperty(Property.Cull(), (float)target.renderFace); // render face enum is designed to directly pass as a cull mode
}
// We always need these properties regardless of whether the material is allowed to override other shader properties.
// Queue control & offset enable correct automatic render queue behavior. Control == 0 is automatic, 1 is user-specified.
// We initialize queue control to -1 to indicate to UpdateMaterial that it needs to initialize it properly on the material.
collector.AddFloatProperty(Property.QueueOffset(), 0.0f);
collector.AddFloatProperty(Property.QueueControl(), -1.0f);
}
public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action<String> registerUndo)
{
// Temporarily remove the workflow mode until specular is supported
//context.AddProperty("Workflow", new EnumField(WorkflowMode.Metallic) { value = workflowMode }, (evt) =>
//{
// if (Equals(workflowMode, evt.newValue))
// return;
// registerUndo("Change Workflow");
// workflowMode = (WorkflowMode)evt.newValue;
// onChange();
//});
// show the target default surface properties
var builtInTarget = (target as BuiltInTarget);
builtInTarget?.AddDefaultMaterialOverrideGUI(ref context, onChange, registerUndo);
builtInTarget?.GetDefaultSurfacePropertiesGUI(ref context, onChange, registerUndo);
context.AddProperty("Fragment Normal Space", new EnumField(NormalDropOffSpace.Tangent) { value = normalDropOffSpace }, (evt) =>
{
if (Equals(normalDropOffSpace, evt.newValue))
return;
registerUndo("Change Fragment Normal Space");
normalDropOffSpace = (NormalDropOffSpace)evt.newValue;
onChange();
});
}
#region SubShader
static class SubShaders
{
// Overloads to do inline PassDescriptor modifications
// NOTE: param order should match PassDescriptor field order for consistency
#region PassVariant
private static PassDescriptor PassVariant(in PassDescriptor source, PragmaCollection pragmas)
{
var result = source;
result.pragmas = pragmas;
return result;
}
private static PassDescriptor PassVariant(in PassDescriptor source, BlockFieldDescriptor[] vertexBlocks, BlockFieldDescriptor[] pixelBlocks, PragmaCollection pragmas, DefineCollection defines)
{
var result = source;
result.validVertexBlocks = vertexBlocks;
result.validPixelBlocks = pixelBlocks;
result.pragmas = pragmas;
result.defines = defines;
return result;
}
#endregion
// SM 2.0
public static SubShaderDescriptor Lit(BuiltInTarget target, string renderType, string renderQueue)
{
var result = new SubShaderDescriptor()
{
//pipelineTag = BuiltInTarget.kPipelineTag,
customTags = BuiltInTarget.kLitMaterialTypeTag,
renderType = renderType,
renderQueue = renderQueue,
generatesPreview = true,
passes = new PassCollection(),
};
result.passes.Add(LitPasses.Forward(target));
result.passes.Add(LitPasses.ForwardAdd(target));
result.passes.Add(LitPasses.Deferred(target));
result.passes.Add(CorePasses.ShadowCaster(target));
if (target.mayWriteDepth)
result.passes.Add(CorePasses.DepthOnly(target));
result.passes.Add(LitPasses.Meta(target));
result.passes.Add(CorePasses.SceneSelection(target));
result.passes.Add(CorePasses.ScenePicking(target));
return result;
}
}
#endregion
#region Passes
static class LitPasses
{
public static PassDescriptor Forward(BuiltInTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "BuiltIn Forward",
referenceName = "SHADERPASS_FORWARD",
lightMode = "ForwardBase",
useInPreview = true,
// Template
passTemplatePath = BuiltInTarget.kTemplatePath,
sharedTemplateDirectories = BuiltInTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = LitBlockMasks.FragmentLit,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.Default(target),
pragmas = CorePragmas.Forward, // NOTE: SM 2.0 only GL
defines = new DefineCollection() { CoreDefines.BuiltInTargetAPI },
keywords = new KeywordCollection { LitKeywords.Forward },
includes = LitIncludes.Forward,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
AddForwardSurfaceControlsToPass(ref result, target);
return result;
}
public static PassDescriptor ForwardAdd(BuiltInTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "BuiltIn ForwardAdd",
referenceName = "SHADERPASS_FORWARD_ADD",
lightMode = "ForwardAdd",
useInPreview = true,
// Template
passTemplatePath = BuiltInTarget.kTemplatePath,
sharedTemplateDirectories = BuiltInTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = LitBlockMasks.FragmentLit,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.ForwardAdd(target),
pragmas = CorePragmas.ForwardAdd, // NOTE: SM 2.0 only GL
defines = new DefineCollection() { CoreDefines.BuiltInTargetAPI },
keywords = new KeywordCollection { LitKeywords.ForwardAdd },
includes = LitIncludes.ForwardAdd,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
AddForwardAddControlsToPass(ref result, target);
return result;
}
public static PassDescriptor ForwardOnly(BuiltInTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "BuiltIn Forward Only",
referenceName = "SHADERPASS_FORWARDONLY",
lightMode = "BuiltInForwardOnly",
useInPreview = true,
// Template
passTemplatePath = BuiltInTarget.kTemplatePath,
sharedTemplateDirectories = BuiltInTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = LitBlockMasks.FragmentLit,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.Default(target),
pragmas = CorePragmas.Forward, // NOTE: SM 2.0 only GL
defines = new DefineCollection() { CoreDefines.BuiltInTargetAPI },
keywords = new KeywordCollection { LitKeywords.Forward },
includes = LitIncludes.Forward,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
AddForwardOnlyControlsToPass(ref result, target);
return result;
}
public static PassDescriptor Deferred(BuiltInTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "BuiltIn Deferred",
referenceName = "SHADERPASS_DEFERRED",
lightMode = "Deferred",
useInPreview = true,
// Template
passTemplatePath = BuiltInTarget.kTemplatePath,
sharedTemplateDirectories = BuiltInTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = LitBlockMasks.FragmentLit,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.Default(target),
pragmas = CorePragmas.Deferred, // NOTE: SM 2.0 only GL
defines = new DefineCollection() { CoreDefines.BuiltInTargetAPI },
keywords = new KeywordCollection { LitKeywords.Deferred },
includes = LitIncludes.Deferred,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
AddDeferredControlsToPass(ref result, target);
return result;
}
public static PassDescriptor Meta(BuiltInTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "Meta",
referenceName = "SHADERPASS_META",
lightMode = "Meta",
// Template
passTemplatePath = BuiltInTarget.kTemplatePath,
sharedTemplateDirectories = BuiltInTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = LitBlockMasks.FragmentMeta,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.Meta,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.Meta,
pragmas = CorePragmas.Default,
defines = new DefineCollection() { CoreDefines.BuiltInTargetAPI },
keywords = new KeywordCollection { LitKeywords.Meta },
includes = LitIncludes.Meta,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
AddMetaControlsToPass(ref result, target);
return result;
}
internal static void AddForwardSurfaceControlsToPass(ref PassDescriptor pass, BuiltInTarget target)
{
CorePasses.AddTargetSurfaceControlsToPass(ref pass, target);
}
internal static void AddForwardAddControlsToPass(ref PassDescriptor pass, BuiltInTarget target)
{
CorePasses.AddSurfaceTypeControlToPass(ref pass, target);
CorePasses.AddAlphaClipControlToPass(ref pass, target);
}
internal static void AddForwardOnlyControlsToPass(ref PassDescriptor pass, BuiltInTarget target)
{
CorePasses.AddTargetSurfaceControlsToPass(ref pass, target);
}
internal static void AddDeferredControlsToPass(ref PassDescriptor pass, BuiltInTarget target)
{
CorePasses.AddTargetSurfaceControlsToPass(ref pass, target);
}
internal static void AddMetaControlsToPass(ref PassDescriptor pass, BuiltInTarget target)
{
CorePasses.AddSurfaceTypeControlToPass(ref pass, target);
CorePasses.AddAlphaClipControlToPass(ref pass, target);
}
}
#endregion
#region PortMasks
static class LitBlockMasks
{
public static readonly BlockFieldDescriptor[] FragmentLit = new BlockFieldDescriptor[]
{
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.NormalOS,
BlockFields.SurfaceDescription.NormalTS,
BlockFields.SurfaceDescription.NormalWS,
BlockFields.SurfaceDescription.Emission,
BlockFields.SurfaceDescription.Metallic,
BlockFields.SurfaceDescription.Specular,
BlockFields.SurfaceDescription.Smoothness,
BlockFields.SurfaceDescription.Occlusion,
BlockFields.SurfaceDescription.Alpha,
BlockFields.SurfaceDescription.AlphaClipThreshold,
};
public static readonly BlockFieldDescriptor[] FragmentMeta = new BlockFieldDescriptor[]
{
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.Emission,
BlockFields.SurfaceDescription.Alpha,
BlockFields.SurfaceDescription.AlphaClipThreshold,
};
public static readonly BlockFieldDescriptor[] FragmentDepthNormals = new BlockFieldDescriptor[]
{
BlockFields.SurfaceDescription.NormalOS,
BlockFields.SurfaceDescription.NormalTS,
BlockFields.SurfaceDescription.NormalWS,
BlockFields.SurfaceDescription.Alpha,
BlockFields.SurfaceDescription.AlphaClipThreshold,
};
}
#endregion
#region RequiredFields
static class LitRequiredFields
{
public static readonly FieldCollection Forward = new FieldCollection()
{
StructFields.Attributes.uv1, // needed for meta vertex position
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS,
StructFields.Varyings.tangentWS, // needed for vertex lighting
BuiltInStructFields.Varyings.lightmapUV,
BuiltInStructFields.Varyings.sh,
BuiltInStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency
BuiltInStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency
};
public static readonly FieldCollection GBuffer = new FieldCollection()
{
StructFields.Attributes.uv1, // needed for meta vertex position
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS,
StructFields.Varyings.tangentWS, // needed for vertex lighting
BuiltInStructFields.Varyings.lightmapUV,
BuiltInStructFields.Varyings.sh,
BuiltInStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency
BuiltInStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency
};
public static readonly FieldCollection DepthNormals = new FieldCollection()
{
StructFields.Attributes.uv1, // needed for meta vertex position
StructFields.Varyings.normalWS,
StructFields.Varyings.tangentWS, // needed for vertex lighting
};
public static readonly FieldCollection Meta = new FieldCollection()
{
StructFields.Attributes.uv1, // needed for meta vertex position
StructFields.Attributes.uv2, //needed for meta vertex position
};
}
#endregion
#region Defines
#endregion
#region Keywords
static class LitKeywords
{
public static readonly KeywordDescriptor GBufferNormalsOct = new KeywordDescriptor()
{
displayName = "GBuffer normal octaedron encoding",
referenceName = "_GBUFFER_NORMALS_OCT",
type = KeywordType.Boolean,
definition = KeywordDefinition.MultiCompile,
scope = KeywordScope.Global,
};
public static readonly KeywordDescriptor ScreenSpaceAmbientOcclusion = new KeywordDescriptor()
{
displayName = "Screen Space Ambient Occlusion",
referenceName = "_SCREEN_SPACE_OCCLUSION",
type = KeywordType.Boolean,
definition = KeywordDefinition.MultiCompile,
scope = KeywordScope.Global,
};
public static readonly KeywordCollection Forward = new KeywordCollection
{
{ ScreenSpaceAmbientOcclusion },
{ CoreKeywordDescriptors.Lightmap },
{ CoreKeywordDescriptors.DirectionalLightmapCombined },
{ CoreKeywordDescriptors.MainLightShadows },
{ CoreKeywordDescriptors.AdditionalLights },
{ CoreKeywordDescriptors.AdditionalLightShadows },
{ CoreKeywordDescriptors.ShadowsSoft },
{ CoreKeywordDescriptors.LightmapShadowMixing },
{ CoreKeywordDescriptors.ShadowsShadowmask },
};
public static readonly KeywordCollection ForwardAdd = new KeywordCollection
{
{ ScreenSpaceAmbientOcclusion },
{ CoreKeywordDescriptors.Lightmap },
{ CoreKeywordDescriptors.DirectionalLightmapCombined },
{ CoreKeywordDescriptors.MainLightShadows },
{ CoreKeywordDescriptors.AdditionalLights },
{ CoreKeywordDescriptors.AdditionalLightShadows },
{ CoreKeywordDescriptors.ShadowsSoft },
{ CoreKeywordDescriptors.LightmapShadowMixing },
{ CoreKeywordDescriptors.ShadowsShadowmask },
};
public static readonly KeywordCollection Deferred = new KeywordCollection
{
{ CoreKeywordDescriptors.Lightmap },
{ CoreKeywordDescriptors.DirectionalLightmapCombined },
{ CoreKeywordDescriptors.MainLightShadows },
{ CoreKeywordDescriptors.ShadowsSoft },
{ CoreKeywordDescriptors.LightmapShadowMixing },
{ CoreKeywordDescriptors.MixedLightingSubtractive },
{ GBufferNormalsOct },
};
public static readonly KeywordCollection Meta = new KeywordCollection
{
{ CoreKeywordDescriptors.SmoothnessChannel },
};
}
#endregion
#region Includes
static class LitIncludes
{
const string kShadows = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Shadows.hlsl";
const string kMetaInput = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/MetaInput.hlsl";
const string kForwardPass = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl";
const string kForwardAddPass = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/PBRForwardAddPass.hlsl";
const string kDeferredPass = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/PBRDeferredPass.hlsl";
const string kGBuffer = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/UnityGBuffer.hlsl";
const string kPBRGBufferPass = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl";
const string kLightingMetaPass = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl";
public static readonly IncludeCollection Forward = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kForwardPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection ForwardAdd = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kForwardAddPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection Deferred = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kDeferredPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection GBuffer = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ kShadows, IncludeLocation.Pregraph },
{ CoreIncludes.ShaderGraphPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kGBuffer, IncludeLocation.Postgraph },
{ kPBRGBufferPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection Meta = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kLightingMetaPass, IncludeLocation.Postgraph },
};
}
#endregion
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8c2d5b55aa47443878a55a05f4294270
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,52 @@
using UnityEditor.ShaderGraph;
using UnityEngine;
using static UnityEditor.Rendering.BuiltIn.ShaderUtils;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
abstract class BuiltInSubTarget : SubTarget<BuiltInTarget>, IHasMetadata
{
static readonly GUID kSourceCodeGuid = new GUID("b0ad362e98650f847a0f2dc834fcbc88"); // BuiltInSubTarget.cs
public override void Setup(ref TargetSetupContext context)
{
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
}
protected abstract ShaderID shaderID { get; }
public virtual string identifier => GetType().Name;
public virtual ScriptableObject GetMetadataObject(GraphDataReadOnly graph)
{
var bultInMetadata = ScriptableObject.CreateInstance<BuiltInMetadata>();
bultInMetadata.shaderID = shaderID;
return bultInMetadata;
}
public override object saveContext
{
get
{
// Currently all SG properties are duplicated inside the material, so changing a value on the SG does not
// impact any already created material
bool needsUpdate = false;
return new BuiltInShaderGraphSaveContext { updateMaterials = needsUpdate };
}
}
}
internal static class SubShaderUtils
{
// Overloads to do inline PassDescriptor modifications
// NOTE: param order should match PassDescriptor field order for consistency
#region PassVariant
internal static PassDescriptor PassVariant(in PassDescriptor source, PragmaCollection pragmas)
{
var result = source;
result.pragmas = pragmas;
return result;
}
#endregion
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b0ad362e98650f847a0f2dc834fcbc88
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d0f59811de3924b6ab62802eb365ef6b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,212 @@
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using UnityEditor.ShaderGraph.Legacy;
using static UnityEditor.Rendering.BuiltIn.ShaderUtils;
namespace UnityEditor.Rendering.BuiltIn.ShaderGraph
{
sealed class BuiltInUnlitSubTarget : BuiltInSubTarget
{
static readonly GUID kSourceCodeGuid = new GUID("3af09b75886c549dbad6eaaaaf342387"); // BuiltInUnlitSubTarget.cs
public BuiltInUnlitSubTarget()
{
displayName = "Unlit";
}
protected override ShaderID shaderID => ShaderID.SG_Unlit;
public override bool IsActive() => true;
public override void Setup(ref TargetSetupContext context)
{
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
if (!context.HasCustomEditorForRenderPipeline(""))
context.AddCustomEditorForRenderPipeline(typeof(BuiltInUnlitGUI).FullName, "");
// Process SubShaders
context.AddSubShader(SubShaders.Unlit(target, target.renderType, target.renderQueue));
}
public override void ProcessPreviewMaterial(Material material)
{
if (target.allowMaterialOverride)
{
// copy our target's default settings into the material
// (technically not necessary since we are always recreating the material from the shader each time,
// which will pull over the defaults from the shader definition)
// but if that ever changes, this will ensure the defaults are set
material.SetFloat(Property.Surface(), (float)target.surfaceType);
material.SetFloat(Property.Blend(), (float)target.alphaMode);
material.SetFloat(Property.AlphaClip(), target.alphaClip ? 1.0f : 0.0f);
material.SetFloat(Property.Cull(), (int)target.renderFace);
material.SetFloat(Property.ZWriteControl(), (float)target.zWriteControl);
material.SetFloat(Property.ZTest(), (float)target.zTestMode);
}
// We always need these properties regardless of whether the material is allowed to override
// Queue control & offset enable correct automatic render queue behavior
// Control == 0 is automatic, 1 is user-specified render queue
material.SetFloat(Property.QueueOffset(), 0.0f);
material.SetFloat(Property.QueueControl(), (float)BuiltInBaseShaderGUI.QueueControl.Auto);
// call the full unlit material setup function
BuiltInUnlitGUI.UpdateMaterial(material);
}
public override void GetFields(ref TargetFieldContext context)
{
}
public override void GetActiveBlocks(ref TargetActiveBlockContext context)
{
context.AddBlock(BlockFields.SurfaceDescription.Alpha, (target.surfaceType == SurfaceType.Transparent || target.alphaClip) || target.allowMaterialOverride);
context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, target.alphaClip || target.allowMaterialOverride);
}
public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
if (target.allowMaterialOverride)
{
base.CollectShaderProperties(collector, generationMode);
// setup properties using the defaults
collector.AddFloatProperty(Property.Surface(), (float)target.surfaceType);
collector.AddFloatProperty(Property.Blend(), (float)target.alphaMode);
collector.AddFloatProperty(Property.AlphaClip(), target.alphaClip ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend(), 1.0f); // always set by material inspector (TODO : get src/dst blend and set here?)
collector.AddFloatProperty(Property.DstBlend(), 0.0f); // always set by material inspector
collector.AddFloatProperty(Property.ZWrite(), (target.surfaceType == SurfaceType.Opaque) ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.ZWriteControl(), (float)target.zWriteControl);
collector.AddFloatProperty(Property.ZTest(), (float)target.zTestMode); // ztest mode is designed to directly pass as ztest
collector.AddFloatProperty(Property.Cull(), (float)target.renderFace); // render face enum is designed to directly pass as a cull mode
}
// We always need these properties regardless of whether the material is allowed to override other shader properties.
// Queue control & offset enable correct automatic render queue behavior. Control == 0 is automatic, 1 is user-specified.
// We initialize queue control to -1 to indicate to UpdateMaterial that it needs to initialize it properly on the material.
collector.AddFloatProperty(Property.QueueOffset(), 0.0f);
collector.AddFloatProperty(Property.QueueControl(), -1.0f);
}
public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action<String> registerUndo)
{
// show the target default surface properties
var builtInTarget = (target as BuiltInTarget);
builtInTarget?.AddDefaultMaterialOverrideGUI(ref context, onChange, registerUndo);
builtInTarget?.GetDefaultSurfacePropertiesGUI(ref context, onChange, registerUndo);
}
#region SubShader
static class SubShaders
{
public static SubShaderDescriptor Unlit(BuiltInTarget target, string renderType, string renderQueue)
{
var result = new SubShaderDescriptor()
{
//pipelineTag = UniversalTarget.kPipelineTag,
customTags = BuiltInTarget.kUnlitMaterialTypeTag,
renderType = renderType,
renderQueue = renderQueue,
generatesPreview = true,
passes = new PassCollection()
};
result.passes.Add(UnlitPasses.Unlit(target));
if (target.mayWriteDepth)
result.passes.Add(CorePasses.DepthOnly(target));
result.passes.Add(CorePasses.ShadowCaster(target));
result.passes.Add(CorePasses.SceneSelection(target));
result.passes.Add(CorePasses.ScenePicking(target));
return result;
}
}
#endregion
#region Pass
static class UnlitPasses
{
public static PassDescriptor Unlit(BuiltInTarget target)
{
var result = new PassDescriptor
{
// Definition
displayName = "Pass",
referenceName = "SHADERPASS_UNLIT",
lightMode = "ForwardBase",
useInPreview = true,
// Template
passTemplatePath = BuiltInTarget.kTemplatePath,
sharedTemplateDirectories = BuiltInTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = CoreBlockMasks.FragmentColorAlpha,
// Fields
structs = CoreStructCollections.Default,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.Default(target),
pragmas = CorePragmas.Forward,
defines = new DefineCollection() { CoreDefines.BuiltInTargetAPI },
keywords = new KeywordCollection(),
includes = UnlitIncludes.Unlit,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddTargetSurfaceControlsToPass(ref result, target);
return result;
}
}
#endregion
#region Keywords
static class UnlitKeywords
{
public static KeywordCollection Unlit(BuiltInTarget target)
{
var result = new KeywordCollection
{
{ CoreKeywordDescriptors.Lightmap },
{ CoreKeywordDescriptors.DirectionalLightmapCombined },
{ CoreKeywordDescriptors.SampleGI },
};
return result;
}
}
#endregion
#region Includes
static class UnlitIncludes
{
const string kUnlitPass = "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/Editor/ShaderGraph/Includes/UnlitPass.hlsl";
public static IncludeCollection Unlit = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kUnlitPass, IncludeLocation.Postgraph },
};
}
#endregion
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3af09b75886c549dbad6eaaaaf342387
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e9e01eb1ed43ca346a8389fc15adb62d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,138 @@
Pass
{
$splice(PassName)
Tags
{
$splice(LightMode)
}
// Render State
$splice(RenderState)
// Debug
$splice(Debug)
// --------------------------------------------------
// Pass
HLSLPROGRAM
// Pragmas
$splice(PassPragmas)
// Keywords
$splice(PassKeywords)
$splice(GraphKeywords)
// Defines
$SurfaceType.Transparent: // UBER SHADER NOW: #define _SURFACE_TYPE_TRANSPARENT 1
$AlphaClip: // UBER SHADER NOW: #define _AlphaClip 1
$Normal: #define _NORMALMAP 1
$BlendMode.Add: // UBER SHADER NOW: #define _BLENDMODE_ADD 1
$BlendMode.Premultiply: // UBER SHADER NOW: #define _ALPHAPREMULTIPLY_ON 1
$SpecularSetup: #define _SPECULAR_SETUP
$NormalDropOffTS: #define _NORMAL_DROPOFF_TS 1
$NormalDropOffOS: #define _NORMAL_DROPOFF_OS 1
$NormalDropOffWS: #define _NORMAL_DROPOFF_WS 1
$Attributes.normalOS: #define ATTRIBUTES_NEED_NORMAL
$Attributes.tangentOS: #define ATTRIBUTES_NEED_TANGENT
$Attributes.uv0: #define ATTRIBUTES_NEED_TEXCOORD0
$Attributes.uv1: #define ATTRIBUTES_NEED_TEXCOORD1
$Attributes.uv2: #define ATTRIBUTES_NEED_TEXCOORD2
$Attributes.uv3: #define ATTRIBUTES_NEED_TEXCOORD3
$Attributes.color: #define ATTRIBUTES_NEED_COLOR
$Attributes.vertexID: #define ATTRIBUTES_NEED_VERTEXID
$Varyings.positionWS: #define VARYINGS_NEED_POSITION_WS
$Varyings.normalWS: #define VARYINGS_NEED_NORMAL_WS
$Varyings.tangentWS: #define VARYINGS_NEED_TANGENT_WS
$Varyings.texCoord0: #define VARYINGS_NEED_TEXCOORD0
$Varyings.texCoord1: #define VARYINGS_NEED_TEXCOORD1
$Varyings.texCoord2: #define VARYINGS_NEED_TEXCOORD2
$Varyings.texCoord3: #define VARYINGS_NEED_TEXCOORD3
$Varyings.color: #define VARYINGS_NEED_COLOR
$Varyings.bitangentWS: #define VARYINGS_NEED_BITANGENT_WS
$Varyings.screenPosition: #define VARYINGS_NEED_SCREENPOSITION
$Varyings.fogFactorAndVertexLight: #define VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
$Varyings.cullFace: #define VARYINGS_NEED_CULLFACE
$features.graphVertex: #define FEATURES_GRAPH_VERTEX
$BuiltIn.UseLegacySpriteBlocks: #define BUILTIN_USELEGACYSPRITEBLOCKS
$splice(PassInstancing)
$splice(GraphDefines)
#ifdef _BUILTIN_SURFACE_TYPE_TRANSPARENT
#define _SURFACE_TYPE_TRANSPARENT _BUILTIN_SURFACE_TYPE_TRANSPARENT
#endif
#ifdef _BUILTIN_ALPHATEST_ON
#define _ALPHATEST_ON _BUILTIN_ALPHATEST_ON
#endif
#ifdef _BUILTIN_AlphaClip
#define _AlphaClip _BUILTIN_AlphaClip
#endif
#ifdef _BUILTIN_ALPHAPREMULTIPLY_ON
#define _ALPHAPREMULTIPLY_ON _BUILTIN_ALPHAPREMULTIPLY_ON
#endif
// custom interpolator pre-include
$splice(sgci_CustomInterpolatorPreInclude)
// Includes
$splice(PreGraphIncludes)
// --------------------------------------------------
// Structs and Packing
// custom interpolators pre packing
$splice(CustomInterpolatorPrePacking)
$splice(PassStructs)
$splice(InterpolatorPack)
// --------------------------------------------------
// Graph
// Graph Properties
$splice(GraphProperties)
// -- Property used by ScenePickingPass
#ifdef SCENEPICKINGPASS
float4 _SelectionID;
#endif
// -- Properties used by SceneSelectionPass
#ifdef SCENESELECTIONPASS
int _ObjectId;
int _PassValue;
#endif
// Graph Includes
$splice(GraphIncludes)
// Graph Functions
$splice(GraphFunctions)
// Custom interpolators pre vertex
$splice(CustomInterpolatorPreVertex)
// Graph Vertex
$splice(GraphVertex)
// Custom interpolators, pre surface
$splice(CustomInterpolatorPreSurface)
// Graph Pixel
$splice(GraphPixel)
// --------------------------------------------------
// Build Graph Inputs
$features.graphVertex: $include("BuildVertexDescriptionInputs.template.hlsl")
$features.graphPixel: $include("SharedCode.template.hlsl")
// --------------------------------------------------
// Main
$splice(PostGraphIncludes)
ENDHLSL
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 37dc84a050227a648b8474dd029e1729
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,148 @@
SurfaceDescriptionInputs BuildSurfaceDescriptionInputs(Varyings input)
{
SurfaceDescriptionInputs output;
ZERO_INITIALIZE(SurfaceDescriptionInputs, output);
$splice(CustomInterpolatorCopyToSDI)
$SurfaceDescriptionInputs.WorldSpaceNormal: // must use interpolated tangent, bitangent and normal before they are normalized in the pixel shader.
$SurfaceDescriptionInputs.WorldSpaceNormal: float3 unnormalizedNormalWS = input.normalWS;
$SurfaceDescriptionInputs.WorldSpaceNormal: const float renormFactor = 1.0 / length(unnormalizedNormalWS);
$SurfaceDescriptionInputs.WorldSpaceBiTangent: // use bitangent on the fly like in hdrp
$SurfaceDescriptionInputs.WorldSpaceBiTangent: // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped.
$SurfaceDescriptionInputs.WorldSpaceBiTangent: float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0)* GetOddNegativeScale();
$SurfaceDescriptionInputs.WorldSpaceBiTangent: float3 bitang = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz);
$SurfaceDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = renormFactor * input.normalWS.xyz; // we want a unit length Normal Vector node in shader graph
$SurfaceDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = normalize(mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_M)); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$SurfaceDescriptionInputs.WorldSpaceTangent: // to preserve mikktspace compliance we use same scale renormFactor as was used on the normal.
$SurfaceDescriptionInputs.WorldSpaceTangent: // This is explained in section 2.2 in "surface gradient based bump mapping framework"
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = renormFactor * input.tangentWS.xyz;
$SurfaceDescriptionInputs.WorldSpaceBiTangent: output.WorldSpaceBiTangent = renormFactor * bitang;
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = TransformWorldToObjectDir(output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
$SurfaceDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);
$SurfaceDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = TransformWorldToObjectDir(output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
$SurfaceDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(input.positionWS);
$SurfaceDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.TangentSpaceViewDirection: float3x3 tangentSpaceTransform = float3x3(output.WorldSpaceTangent, output.WorldSpaceBiTangent, output.WorldSpaceNormal);
$SurfaceDescriptionInputs.TangentSpaceViewDirection: output.TangentSpaceViewDirection = mul(tangentSpaceTransform, output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = input.positionWS;
$SurfaceDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = TransformWorldToObject(input.positionWS);
$SurfaceDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(input.positionWS);
$SurfaceDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
$SurfaceDescriptionInputs.AbsoluteWorldSpacePosition: output.AbsoluteWorldSpacePosition = GetAbsolutePositionWS(input.positionWS);
$SurfaceDescriptionInputs.WorldSpacePositionPredisplacement: output.WorldSpacePositionPredisplacement = input.positionWS;
$SurfaceDescriptionInputs.ObjectSpacePositionPredisplacement: output.ObjectSpacePositionPredisplacement = TransformWorldToObject(input.positionWS);
$SurfaceDescriptionInputs.ViewSpacePositionPredisplacement: output.ViewSpacePositionPredisplacement = TransformWorldToView(input.positionWS);
$SurfaceDescriptionInputs.TangentSpacePositionPredisplacement: output.TangentSpacePositionPredisplacement = float3(0.0f, 0.0f, 0.0f);
$SurfaceDescriptionInputs.AbsoluteWorldSpacePositionPredisplacement:output.AbsoluteWorldSpacePositionPredisplacement = GetAbsolutePositionWS(input.positionWS);
$SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionWS), _ProjectionParams.x);
#if UNITY_UV_STARTS_AT_TOP
$SurfaceDescriptionInputs.PixelPosition: output.PixelPosition = float2(input.positionCS.x, (_ProjectionParams.x < 0) ? (_ScreenParams.y - input.positionCS.y) : input.positionCS.y);
#else
$SurfaceDescriptionInputs.PixelPosition: output.PixelPosition = float2(input.positionCS.x, (_ProjectionParams.x > 0) ? (_ScreenParams.y - input.positionCS.y) : input.positionCS.y);
#endif
$SurfaceDescriptionInputs.NDCPosition: output.NDCPosition = output.PixelPosition.xy / _ScreenParams.xy;
$SurfaceDescriptionInputs.NDCPosition: output.NDCPosition.y = 1.0f - output.NDCPosition.y;
$SurfaceDescriptionInputs.uv0: output.uv0 = input.texCoord0;
$SurfaceDescriptionInputs.uv1: output.uv1 = input.texCoord1;
$SurfaceDescriptionInputs.uv2: output.uv2 = input.texCoord2;
$SurfaceDescriptionInputs.uv3: output.uv3 = input.texCoord3;
$SurfaceDescriptionInputs.VertexColor: output.VertexColor = input.color;
$SurfaceDescriptionInputs.TimeParameters: output.TimeParameters = _TimeParameters.xyz; // This is mainly for LW as HD overwrite this value
#if defined(SHADER_STAGE_FRAGMENT) && defined(VARYINGS_NEED_CULLFACE)
#define BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN output.FaceSign = IS_FRONT_VFACE(input.cullFace, true, false);
#else
#define BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN
#endif
$SurfaceDescriptionInputs.FaceSign: BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN
#undef BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN
return output;
}
void BuildAppDataFull(Attributes attributes, VertexDescription vertexDescription, inout appdata_full result)
{
$Attributes.positionOS: result.vertex = float4(attributes.positionOS, 1);
$Attributes.tangentOS: result.tangent = attributes.tangentOS;
$Attributes.normalOS: result.normal = attributes.normalOS;
$Attributes.uv0: result.texcoord = attributes.uv0;
$Attributes.uv1: result.texcoord1 = attributes.uv1;
$Attributes.uv2: result.texcoord2 = attributes.uv2;
$Attributes.uv3: result.texcoord3 = attributes.uv3;
$Attributes.color: result.color = attributes.color;
$VertexDescription.Position: result.vertex = float4(vertexDescription.Position, 1);
$VertexDescription.Normal: result.normal = vertexDescription.Normal;
$VertexDescription.Tangent: result.tangent = float4(vertexDescription.Tangent, 0);
#if UNITY_ANY_INSTANCING_ENABLED
$Attributes.instanceID: result.instanceID = attributes.instanceID;
#endif
}
void VaryingsToSurfaceVertex(Varyings varyings, inout v2f_surf result)
{
result.pos = varyings.positionCS;
$Varyings.positionWS: result.worldPos = varyings.positionWS;
$Varyings.normalWS: result.worldNormal = varyings.normalWS;
// World Tangent isn't an available input on v2f_surf
$Varyings.shadowCoord: result._ShadowCoord = varyings.shadowCoord;
#if UNITY_ANY_INSTANCING_ENABLED
$Varyings.instanceID: UNITY_TRANSFER_INSTANCE_ID(varyings, result);
#endif
#if UNITY_SHOULD_SAMPLE_SH
#if !defined(LIGHTMAP_ON)
$Varyings.sh: result.sh = varyings.sh;
#endif
#endif
#if defined(LIGHTMAP_ON)
$Varyings.lightmapUV: result.lmap.xy = varyings.lightmapUV;
#endif
#ifdef VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
result.fogCoord = varyings.fogFactorAndVertexLight.x;
COPY_TO_LIGHT_COORDS(result, varyings.fogFactorAndVertexLight.yzw);
#endif
DEFAULT_UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(varyings, result);
}
void SurfaceVertexToVaryings(v2f_surf surfVertex, inout Varyings result)
{
result.positionCS = surfVertex.pos;
$Varyings.positionWS: result.positionWS = surfVertex.worldPos;
$Varyings.normalWS: result.normalWS = surfVertex.worldNormal;
// viewDirectionWS is never filled out in the legacy pass' function. Always use the value computed by SRP
// World Tangent isn't an available input on v2f_surf
$Varyings.shadowCoord: result.shadowCoord = surfVertex._ShadowCoord;
#if UNITY_ANY_INSTANCING_ENABLED
$Varyings.instanceID: UNITY_TRANSFER_INSTANCE_ID(surfVertex, result);
#endif
#if UNITY_SHOULD_SAMPLE_SH
#if !defined(LIGHTMAP_ON)
$Varyings.sh: result.sh = surfVertex.sh;
#endif
#endif
#if defined(LIGHTMAP_ON)
$Varyings.lightmapUV: result.lightmapUV = surfVertex.lmap.xy;
#endif
#ifdef VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
result.fogFactorAndVertexLight.x = surfVertex.fogCoord;
COPY_FROM_LIGHT_COORDS(result.fogFactorAndVertexLight.yzw, surfVertex);
#endif
DEFAULT_UNITY_TRANSFER_VERTEX_OUTPUT_STEREO(surfVertex, result);
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: d1c01b917a304614daf4994f4ca27e6d
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,451 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.Rendering.BuiltIn.ShaderGraph;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.BuiltIn
{
[Flags]
enum ShaderFeatures
{
None = 0,
MainLight = (1 << 0),
MainLightShadows = (1 << 1),
AdditionalLights = (1 << 2),
AdditionalLightShadows = (1 << 3),
VertexLighting = (1 << 4),
SoftShadows = (1 << 5),
MixedLighting = (1 << 6),
TerrainHoles = (1 << 7),
DeferredShading = (1 << 8), // DeferredRenderer is in the list of renderer
DeferredWithAccurateGbufferNormals = (1 << 9),
DeferredWithoutAccurateGbufferNormals = (1 << 10),
ScreenSpaceOcclusion = (1 << 11),
ScreenSpaceShadows = (1 << 12),
ReflectionProbeBlending = (1 << 13),
ReflectionProbeBoxProjection = (1 << 14),
}
// This should really be part of the main BuiltIn Target Keyword list we use for reference names
public static class ShaderKeywordStrings
{
public static readonly string MainLightShadows = "_MAIN_LIGHT_SHADOWS";
public static readonly string MainLightShadowCascades = "_MAIN_LIGHT_SHADOWS_CASCADE";
public static readonly string MainLightShadowScreen = "_MAIN_LIGHT_SHADOWS_SCREEN";
public static readonly string AdditionalLightsVertex = "_ADDITIONAL_LIGHTS_VERTEX";
public static readonly string AdditionalLightsPixel = "_ADDITIONAL_LIGHTS";
public static readonly string AdditionalLightShadows = "_ADDITIONAL_LIGHT_SHADOWS";
public static readonly string ReflectionProbeBlending = "_REFLECTION_PROBE_BLENDING";
public static readonly string ReflectionProbeBoxProjection = "_REFLECTION_PROBE_BOX_PROJECTION";
// This is used during shadow map generation to differentiate between directional and punctual light shadows,
// as they use different formulas to apply Normal Bias
public static readonly string SoftShadows = "_SHADOWS_SOFT";
public static readonly string CastingPunctualLightShadow = "_CASTING_PUNCTUAL_LIGHT_SHADOW";
public static readonly string MixedLightingSubtractive = "_MIXED_LIGHTING_SUBTRACTIVE"; // Backward compatibility
public static readonly string LightmapShadowMixing = "LIGHTMAP_SHADOW_MIXING";
public static readonly string ShadowsShadowMask = "SHADOWS_SHADOWMASK";
public static readonly string ScreenSpaceOcclusion = "_SCREEN_SPACE_OCCLUSION";
public static readonly string _GBUFFER_NORMALS_OCT = "_GBUFFER_NORMALS_OCT";
public static readonly string LIGHTMAP_ON = "LIGHTMAP_ON";
public static readonly string DYNAMICLIGHTMAP_ON = "DYNAMICLIGHTMAP_ON";
public static readonly string _ALPHATEST_ON = "_ALPHATEST_ON";
public static readonly string DIRLIGHTMAP_COMBINED = "DIRLIGHTMAP_COMBINED";
public static readonly string EDITOR_VISUALIZATION = "EDITOR_VISUALIZATION";
}
internal class ShaderPreprocessor : IPreprocessShaders
{
public static readonly string kPassNameGBuffer = "BuiltIn Deferred";
#if PROFILE_BUILD
private const string k_ProcessShaderTag = "OnProcessShader";
#endif
// Event callback to report shader stripping info. Form:
// ReportShaderStrippingData(Shader shader, ShaderSnippetData data, int currentVariantCount, double strippingTime)
internal static event Action<Shader, ShaderSnippetData, int, double> shaderPreprocessed;
ShaderKeyword m_MainLightShadows = new ShaderKeyword(ShaderKeywordStrings.MainLightShadows);
ShaderKeyword m_MainLightShadowsCascades = new ShaderKeyword(ShaderKeywordStrings.MainLightShadowCascades);
ShaderKeyword m_MainLightShadowsScreen = new ShaderKeyword(ShaderKeywordStrings.MainLightShadowScreen);
ShaderKeyword m_AdditionalLightsVertex = new ShaderKeyword(ShaderKeywordStrings.AdditionalLightsVertex);
ShaderKeyword m_AdditionalLightsPixel = new ShaderKeyword(ShaderKeywordStrings.AdditionalLightsPixel);
ShaderKeyword m_AdditionalLightShadows = new ShaderKeyword(ShaderKeywordStrings.AdditionalLightShadows);
ShaderKeyword m_ReflectionProbeBlending = new ShaderKeyword(ShaderKeywordStrings.ReflectionProbeBlending);
ShaderKeyword m_ReflectionProbeBoxProjection = new ShaderKeyword(ShaderKeywordStrings.ReflectionProbeBoxProjection);
ShaderKeyword m_CastingPunctualLightShadow = new ShaderKeyword(ShaderKeywordStrings.CastingPunctualLightShadow);
ShaderKeyword m_SoftShadows = new ShaderKeyword(ShaderKeywordStrings.SoftShadows);
ShaderKeyword m_MixedLightingSubtractive = new ShaderKeyword(ShaderKeywordStrings.MixedLightingSubtractive);
ShaderKeyword m_LightmapShadowMixing = new ShaderKeyword(ShaderKeywordStrings.LightmapShadowMixing);
ShaderKeyword m_ShadowsShadowMask = new ShaderKeyword(ShaderKeywordStrings.ShadowsShadowMask);
ShaderKeyword m_Lightmap = new ShaderKeyword(ShaderKeywordStrings.LIGHTMAP_ON);
ShaderKeyword m_DynamicLightmap = new ShaderKeyword(ShaderKeywordStrings.DYNAMICLIGHTMAP_ON);
ShaderKeyword m_DirectionalLightmap = new ShaderKeyword(ShaderKeywordStrings.DIRLIGHTMAP_COMBINED);
ShaderKeyword m_AlphaTestOn = new ShaderKeyword(ShaderKeywordStrings._ALPHATEST_ON);
ShaderKeyword m_GbufferNormalsOct = new ShaderKeyword(ShaderKeywordStrings._GBUFFER_NORMALS_OCT);
ShaderKeyword m_ScreenSpaceOcclusion = new ShaderKeyword(ShaderKeywordStrings.ScreenSpaceOcclusion);
ShaderKeyword m_EditorVisualization = new ShaderKeyword(ShaderKeywordStrings.EDITOR_VISUALIZATION);
ShaderTagId m_ShaderGraphShaderTag = new ShaderTagId("ShaderGraphShader");
int m_TotalVariantsInputCount;
int m_TotalVariantsOutputCount;
// Multiple callback may be implemented.
// The first one executed is the one where callbackOrder is returning the smallest number.
public int callbackOrder { get { return 0; } }
bool IsFeatureEnabled(ShaderFeatures featureMask, ShaderFeatures feature)
{
return (featureMask & feature) != 0;
}
bool IsSRPPass(ShaderSnippetData snippetData)
{
return (snippetData.passType == PassType.ScriptableRenderPipeline ||
snippetData.passType == PassType.ScriptableRenderPipelineDefaultUnlit);
}
bool IsShaderGraphShader(Shader shader, ShaderSnippetData snippetData)
{
var shaderData = ShaderUtil.GetShaderData(shader);
var serializedSubShader = shaderData.GetSerializedSubshader((int)snippetData.pass.SubshaderIndex);
var shaderGraphTag = serializedSubShader.FindTagValue(m_ShaderGraphShaderTag);
if (shaderGraphTag == ShaderTagId.none)
return false;
return true;
}
bool StripUnusedPass(ShaderFeatures features, ShaderSnippetData snippetData)
{
// Strip all SRP shader variants
if (IsSRPPass(snippetData))
{
return true;
}
// Meta pass is needed in the player for Enlighten Precomputed Realtime GI albedo and emission.
if (snippetData.passType == PassType.Meta)
{
if (SupportedRenderingFeatures.active.enlighten == false ||
((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) == 0)
return true;
}
if (snippetData.passType == PassType.ShadowCaster)
if (!IsFeatureEnabled(features, ShaderFeatures.MainLightShadows) && !IsFeatureEnabled(features, ShaderFeatures.AdditionalLightShadows))
return true;
return false;
}
bool StripUnusedFeatures(ShaderFeatures features, Shader shader, ShaderSnippetData snippetData, ShaderCompilerData compilerData)
{
// strip main light shadows, cascade and screen variants
if (!IsFeatureEnabled(features, ShaderFeatures.MainLightShadows))
{
if (compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadows))
return true;
if (compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadowsCascades))
return true;
if (compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadowsScreen))
return true;
if (snippetData.passType == PassType.ShadowCaster && !compilerData.shaderKeywordSet.IsEnabled(m_CastingPunctualLightShadow))
return true;
}
bool isSoftShadow = compilerData.shaderKeywordSet.IsEnabled(m_SoftShadows);
if (!IsFeatureEnabled(features, ShaderFeatures.SoftShadows) && isSoftShadow)
return true;
// Left for backward compatibility
if (compilerData.shaderKeywordSet.IsEnabled(m_MixedLightingSubtractive) &&
!IsFeatureEnabled(features, ShaderFeatures.MixedLighting))
return true;
// Strip here only if mixed lighting is disabled
// No need to check here if actually used by scenes as this taken care by builtin stripper
if ((compilerData.shaderKeywordSet.IsEnabled(m_LightmapShadowMixing) ||
compilerData.shaderKeywordSet.IsEnabled(m_ShadowsShadowMask)) &&
!IsFeatureEnabled(features, ShaderFeatures.MixedLighting))
return true;
// No additional light shadows
bool isAdditionalLightShadow = compilerData.shaderKeywordSet.IsEnabled(m_AdditionalLightShadows);
if (!IsFeatureEnabled(features, ShaderFeatures.AdditionalLightShadows) && isAdditionalLightShadow)
return true;
bool isReflectionProbeBlending = compilerData.shaderKeywordSet.IsEnabled(m_ReflectionProbeBlending);
if (!IsFeatureEnabled(features, ShaderFeatures.ReflectionProbeBlending) && isReflectionProbeBlending)
return true;
bool isReflectionProbeBoxProjection = compilerData.shaderKeywordSet.IsEnabled(m_ReflectionProbeBoxProjection);
if (!IsFeatureEnabled(features, ShaderFeatures.ReflectionProbeBoxProjection) && isReflectionProbeBoxProjection)
return true;
bool isPunctualLightShadowCasterPass = (snippetData.passType == PassType.ShadowCaster) && compilerData.shaderKeywordSet.IsEnabled(m_CastingPunctualLightShadow);
if (!IsFeatureEnabled(features, ShaderFeatures.AdditionalLightShadows) && isPunctualLightShadowCasterPass)
return true;
// Additional light are shaded per-vertex or per-pixel.
bool isFeaturePerPixelLightingEnabled = IsFeatureEnabled(features, ShaderFeatures.AdditionalLights);
bool isFeaturePerVertexLightingEnabled = IsFeatureEnabled(features, ShaderFeatures.VertexLighting);
bool isAdditionalLightPerPixel = compilerData.shaderKeywordSet.IsEnabled(m_AdditionalLightsPixel);
bool isAdditionalLightPerVertex = compilerData.shaderKeywordSet.IsEnabled(m_AdditionalLightsVertex);
// Strip if Per-Pixel lighting is NOT used in the project and the
// Per-Pixel (_ADDITIONAL_LIGHTS) variant is enabled in the shader.
if (!isFeaturePerPixelLightingEnabled && isAdditionalLightPerPixel)
return true;
// Strip if Per-Vertex lighting is NOT used in the project and the
// Per-Vertex (_ADDITIONAL_LIGHTS_VERTEX) variant is enabled in the shader.
if (!isFeaturePerVertexLightingEnabled && isAdditionalLightPerVertex)
return true;
// Screen Space Shadows
if (!IsFeatureEnabled(features, ShaderFeatures.ScreenSpaceShadows) &&
compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadowsScreen))
return true;
// Screen Space Occlusion
if (!IsFeatureEnabled(features, ShaderFeatures.ScreenSpaceOcclusion) &&
compilerData.shaderKeywordSet.IsEnabled(m_ScreenSpaceOcclusion))
return true;
return false;
}
bool StripUnsupportedVariants(ShaderCompilerData compilerData)
{
// We can strip variants that have directional lightmap enabled but not static nor dynamic lightmap.
if (compilerData.shaderKeywordSet.IsEnabled(m_DirectionalLightmap) &&
!(compilerData.shaderKeywordSet.IsEnabled(m_Lightmap) ||
compilerData.shaderKeywordSet.IsEnabled(m_DynamicLightmap)))
return true;
// As GLES2 has low amount of registers, we strip:
if (compilerData.shaderCompilerPlatform == ShaderCompilerPlatform.GLES20)
{
// Cascade shadows
if (compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadowsCascades))
return true;
// Screen space shadows
if (compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadowsScreen))
return true;
}
// Editor visualization is only used in scene view debug modes.
if (compilerData.shaderKeywordSet.IsEnabled(m_EditorVisualization))
return true;
return false;
}
bool StripInvalidVariants(ShaderCompilerData compilerData)
{
bool isMainShadowNoCascades = compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadows);
bool isMainShadowCascades = compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadowsCascades);
bool isMainShadowScreen = compilerData.shaderKeywordSet.IsEnabled(m_MainLightShadowsScreen);
bool isMainShadow = isMainShadowNoCascades || isMainShadowCascades || isMainShadowScreen;
bool isAdditionalShadow = compilerData.shaderKeywordSet.IsEnabled(m_AdditionalLightShadows);
if (isAdditionalShadow && !compilerData.shaderKeywordSet.IsEnabled(m_AdditionalLightsPixel))
return true;
bool isShadowVariant = isMainShadow || isAdditionalShadow;
if (!isShadowVariant && compilerData.shaderKeywordSet.IsEnabled(m_SoftShadows))
return true;
return false;
}
bool StripUnused(ShaderFeatures features, Shader shader, ShaderSnippetData snippetData, ShaderCompilerData compilerData)
{
if (StripUnusedFeatures(features, shader, snippetData, compilerData))
return true;
if (StripInvalidVariants(compilerData))
return true;
if (StripUnsupportedVariants(compilerData))
return true;
if (StripUnusedPass(features, snippetData))
return true;
// Skip any shaders that weren't built by Shader Graph.
// Note: This needs to be after StripUnusedPass so that other SRP shaders (including hand-written) are stripped.
if (!IsShaderGraphShader(shader, snippetData))
return false;
// // TODO: Test against lightMode tag instead.
if (snippetData.passName == kPassNameGBuffer)
{
if (!IsFeatureEnabled(features, ShaderFeatures.DeferredShading))
return true;
// Do not strip accurateGbufferNormals on Mobile Vulkan as some GPUs do not support R8G8B8A8_SNorm, which then force us to use accurateGbufferNormals
if (!IsFeatureEnabled(features, ShaderFeatures.DeferredWithAccurateGbufferNormals) && compilerData.shaderKeywordSet.IsEnabled(m_GbufferNormalsOct) && compilerData.shaderCompilerPlatform != ShaderCompilerPlatform.Vulkan)
return true;
if (!IsFeatureEnabled(features, ShaderFeatures.DeferredWithoutAccurateGbufferNormals) && !compilerData.shaderKeywordSet.IsEnabled(m_GbufferNormalsOct))
return true;
}
return false;
}
bool ShouldLogShaderVariant(Shader shader, ShaderSnippetData snippetData)
{
if (shader.name.Contains("Shader Graphs/") && !IsSRPPass(snippetData))
{
return true;
}
return false;
}
void LogShaderVariants(Shader shader, ShaderSnippetData snippetData, int prevVariantsCount, int currVariantsCount)
{
float percentageCurrent = (float)currVariantsCount / (float)prevVariantsCount * 100f;
float percentageTotal = (float)m_TotalVariantsOutputCount / (float)m_TotalVariantsInputCount * 100f;
string result = string.Format("STRIPPING: {0} ({1} pass) ({2}) -" +
" Remaining shader variants = {3}/{4} = {5}% - Total = {6}/{7} = {8}%",
shader.name, snippetData.passName, snippetData.shaderType.ToString(), currVariantsCount,
prevVariantsCount, percentageCurrent, m_TotalVariantsOutputCount, m_TotalVariantsInputCount,
percentageTotal);
if (ShouldLogShaderVariant(shader, snippetData))
Debug.Log(result);
}
public void OnProcessShader(Shader shader, ShaderSnippetData snippetData, IList<ShaderCompilerData> compilerDataList)
{
#if PROFILE_BUILD
Profiler.BeginSample(k_ProcessShaderTag);
#endif
// We only want to perform shader variant stripping if the built-in render pipeline
// is the active render pipeline (i.e., there is no SRP asset in place).
RenderPipelineAsset rpAsset = GraphicsSettings.currentRenderPipeline;
if (rpAsset != null || compilerDataList == null || compilerDataList.Count == 0)
return;
double stripTimeMs = 0.0;
int prevVariantCount = compilerDataList.Count;
using (TimedScope.FromRef(ref stripTimeMs))
{
var inputShaderVariantCount = compilerDataList.Count;
for (int i = 0; i < inputShaderVariantCount;)
{
bool removeInput = true;
foreach (var supportedFeatures in ShaderBuildPreprocessor.supportedFeaturesList)
{
if (!StripUnused(supportedFeatures, shader, snippetData, compilerDataList[i]))
{
removeInput = false;
break;
}
}
// Remove at swap back
if (removeInput)
compilerDataList[i] = compilerDataList[--inputShaderVariantCount];
else
++i;
}
if (!compilerDataList.TryRemoveElementsInRange(inputShaderVariantCount, compilerDataList.Count - inputShaderVariantCount, out var error))
Debug.LogException(error);
}
m_TotalVariantsInputCount += prevVariantCount;
m_TotalVariantsOutputCount += compilerDataList.Count;
LogShaderVariants(shader, snippetData, prevVariantCount, compilerDataList.Count);
#if PROFILE_BUILD
Profiler.EndSample();
#endif
shaderPreprocessed?.Invoke(shader, snippetData, prevVariantCount, stripTimeMs);
}
}
class ShaderBuildPreprocessor : IPreprocessBuildWithReport
#if PROFILE_BUILD
, IPostprocessBuildWithReport
#endif
{
public static List<ShaderFeatures> supportedFeaturesList
{
get
{
if (s_SupportedFeaturesList.Count == 0)
FetchAllSupportedFeatures();
return s_SupportedFeaturesList;
}
}
private static List<ShaderFeatures> s_SupportedFeaturesList = new List<ShaderFeatures>();
public int callbackOrder { get { return 0; } }
#if PROFILE_BUILD
public void OnPostprocessBuild(BuildReport report)
{
Profiler.enabled = false;
}
#endif
public void OnPreprocessBuild(BuildReport report)
{
FetchAllSupportedFeatures();
#if PROFILE_BUILD
Profiler.enableBinaryLog = true;
Profiler.logFile = "profilerlog.raw";
Profiler.enabled = true;
#endif
}
private static void FetchAllSupportedFeatures()
{
s_SupportedFeaturesList.Clear();
s_SupportedFeaturesList.Add(GetSupportedShaderFeatures());
}
private static ShaderFeatures GetSupportedShaderFeatures()
{
ShaderFeatures shaderFeatures;
shaderFeatures = ShaderFeatures.MainLight;
ShadowQuality shadows = QualitySettings.shadows;
if (shadows != ShadowQuality.Disable)
{
shaderFeatures |= ShaderFeatures.MainLightShadows;
if (shadows != ShadowQuality.HardOnly)
shaderFeatures |= ShaderFeatures.SoftShadows;
}
shaderFeatures |= ShaderFeatures.AdditionalLightShadows;
// These are both always "on", and dictated by the number of lights
shaderFeatures |= ShaderFeatures.VertexLighting;
shaderFeatures |= ShaderFeatures.AdditionalLights;
shaderFeatures |= ShaderFeatures.MixedLighting;
// As this is settable per-camera (and the graphics settings UI depends on a camera being marked "main camera"),
// we assume it's on (and strip if the shader doesn't have a deferred pass)
shaderFeatures |= ShaderFeatures.DeferredShading;
// Built-in doesn't throw this switch, but the shader library has it, so set it here
shaderFeatures |= ShaderFeatures.DeferredWithoutAccurateGbufferNormals;
return shaderFeatures;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6beb50d076c894d12a3a5fca04d4cd4b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,57 @@
using UnityEditor.Rendering.BuiltIn.ShaderGraph;
using UnityEditor.ShaderGraph;
using UnityEngine;
namespace UnityEditor.Rendering.BuiltIn
{
public static class ShaderUtils
{
internal enum ShaderID
{
Unknown = -1,
// ShaderGraph IDs start at 1000, correspond to subtargets
SG_Start = 1000,
SG_Unlit = SG_Start, // BuiltInUnlitSubTarget
SG_Lit, // BuiltInLitSubTarget
}
internal static bool IsShaderGraph(this ShaderID id)
{
return (id >= ShaderID.SG_Start);
}
internal static ShaderID GetShaderID(Shader shader)
{
if (shader.IsShaderGraphAsset())
{
BuiltInMetadata meta;
if (!shader.TryGetMetadataOfType<BuiltInMetadata>(out meta))
return ShaderID.Unknown;
return meta.shaderID;
}
else
{
return ShaderID.Unknown;
}
}
internal static void ResetMaterialKeywords(Material material, ShaderID shaderID = ShaderID.Unknown)
{
// if unknown, look it up from the material's shader
// NOTE: this will only work for asset-based shaders..
if (shaderID == ShaderID.Unknown)
shaderID = GetShaderID(material.shader);
switch (shaderID)
{
case ShaderID.SG_Lit:
BuiltInLitGUI.UpdateMaterial(material);
break;
case ShaderID.SG_Unlit:
BuiltInUnlitGUI.UpdateMaterial(material);
break;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 01fb2e405de427a47bbd366ee75d1772
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6dc0256bde5256e40b2e4aa65249dd1e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,117 @@
#ifndef BUILTIN_PIPELINE_CORE_INCLUDED
#define BUILTIN_PIPELINE_CORE_INCLUDED
// VT is not supported in URP (for now) this ensures any shaders using the VT
// node work by falling to regular texture sampling.
#define FORCE_VIRTUAL_TEXTURING_OFF 1
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Input.hlsl"
#if !defined(SHADER_HINT_NICE_QUALITY)
#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH)
#define SHADER_HINT_NICE_QUALITY 0
#else
#define SHADER_HINT_NICE_QUALITY 1
#endif
#endif
// Shader Quality Tiers in BuiltIn.
// SRP doesn't use Graphics Settings Quality Tiers.
// We should expose shader quality tiers in the pipeline asset.
// Meanwhile, it's forced to be:
// High Quality: Non-mobile platforms or shader explicit defined SHADER_HINT_NICE_QUALITY
// Medium: Mobile aside from GLES2
// Low: GLES2
#if SHADER_HINT_NICE_QUALITY
#define SHADER_QUALITY_HIGH
#elif defined(SHADER_API_GLES)
#define SHADER_QUALITY_LOW
#else
#define SHADER_QUALITY_MEDIUM
#endif
#ifndef BUMP_SCALE_NOT_SUPPORTED
#define BUMP_SCALE_NOT_SUPPORTED !SHADER_HINT_NICE_QUALITY
#endif
#if UNITY_REVERSED_Z
// TODO: workaround. There's a bug where SHADER_API_GL_CORE gets erroneously defined on switch.
#if (defined(SHADER_API_GLCORE) && !defined(SHADER_API_SWITCH)) || defined(SHADER_API_GLES) || defined(SHADER_API_GLES3)
//GL with reversed z => z clip range is [near, -far] -> should remap in theory but dont do it in practice to save some perf (range is close enough)
#define UNITY_Z_0_FAR_FROM_CLIPSPACE(coord) max(-(coord), 0)
#else
//D3d with reversed Z => z clip range is [near, 0] -> remapping to [0, far]
//max is required to protect ourselves from near plane not being correct/meaningfull in case of oblique matrices.
#define UNITY_Z_0_FAR_FROM_CLIPSPACE(coord) max(((1.0-(coord)/_ProjectionParams.y)*_ProjectionParams.z),0)
#endif
#elif UNITY_UV_STARTS_AT_TOP
//D3d without reversed z => z clip range is [0, far] -> nothing to do
#define UNITY_Z_0_FAR_FROM_CLIPSPACE(coord) (coord)
#else
//Opengl => z clip range is [-near, far] -> should remap in theory but dont do it in practice to save some perf (range is close enough)
#define UNITY_Z_0_FAR_FROM_CLIPSPACE(coord) (coord)
#endif
// Stereo-related bits
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define SLICE_ARRAY_INDEX unity_StereoEyeIndex
#define TEXTURE2D_X(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURE2D_X_PARAM(textureName, samplerName) TEXTURE2D_ARRAY_PARAM(textureName, samplerName)
#define TEXTURE2D_X_ARGS(textureName, samplerName) TEXTURE2D_ARRAY_ARGS(textureName, samplerName)
#define TEXTURE2D_X_HALF(textureName) TEXTURE2D_ARRAY_HALF(textureName)
#define TEXTURE2D_X_FLOAT(textureName) TEXTURE2D_ARRAY_FLOAT(textureName)
#define LOAD_TEXTURE2D_X(textureName, unCoord2) LOAD_TEXTURE2D_ARRAY(textureName, unCoord2, SLICE_ARRAY_INDEX)
#define LOAD_TEXTURE2D_X_LOD(textureName, unCoord2, lod) LOAD_TEXTURE2D_ARRAY_LOD(textureName, unCoord2, SLICE_ARRAY_INDEX, lod)
#define SAMPLE_TEXTURE2D_X(textureName, samplerName, coord2) SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, coord2, SLICE_ARRAY_INDEX)
#define SAMPLE_TEXTURE2D_X_LOD(textureName, samplerName, coord2, lod) SAMPLE_TEXTURE2D_ARRAY_LOD(textureName, samplerName, coord2, SLICE_ARRAY_INDEX, lod)
#define GATHER_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_TEXTURE2D_ARRAY(textureName, samplerName, coord2, SLICE_ARRAY_INDEX)
#define GATHER_RED_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_RED_TEXTURE2D(textureName, samplerName, float3(coord2, SLICE_ARRAY_INDEX))
#define GATHER_GREEN_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_GREEN_TEXTURE2D(textureName, samplerName, float3(coord2, SLICE_ARRAY_INDEX))
#define GATHER_BLUE_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_BLUE_TEXTURE2D(textureName, samplerName, float3(coord2, SLICE_ARRAY_INDEX))
#else
#define SLICE_ARRAY_INDEX 0
#define TEXTURE2D_X(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_X_PARAM(textureName, samplerName) TEXTURE2D_PARAM(textureName, samplerName)
#define TEXTURE2D_X_ARGS(textureName, samplerName) TEXTURE2D_ARGS(textureName, samplerName)
#define TEXTURE2D_X_HALF(textureName) TEXTURE2D_HALF(textureName)
#define TEXTURE2D_X_FLOAT(textureName) TEXTURE2D_FLOAT(textureName)
#define LOAD_TEXTURE2D_X(textureName, unCoord2) LOAD_TEXTURE2D(textureName, unCoord2)
#define LOAD_TEXTURE2D_X_LOD(textureName, unCoord2, lod) LOAD_TEXTURE2D_LOD(textureName, unCoord2, lod)
#define SAMPLE_TEXTURE2D_X(textureName, samplerName, coord2) SAMPLE_TEXTURE2D(textureName, samplerName, coord2)
#define SAMPLE_TEXTURE2D_X_LOD(textureName, samplerName, coord2, lod) SAMPLE_TEXTURE2D_LOD(textureName, samplerName, coord2, lod)
#define GATHER_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_TEXTURE2D(textureName, samplerName, coord2)
#define GATHER_RED_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_RED_TEXTURE2D(textureName, samplerName, coord2)
#define GATHER_GREEN_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_GREEN_TEXTURE2D(textureName, samplerName, coord2)
#define GATHER_BLUE_TEXTURE2D_X(textureName, samplerName, coord2) GATHER_BLUE_TEXTURE2D(textureName, samplerName, coord2)
#endif
// Structs
struct VertexPositionInputs
{
float3 positionWS; // World space position
float3 positionVS; // View space position
float4 positionCS; // Homogeneous clip space position
float4 positionNDC;// Homogeneous normalized device coordinates
};
struct VertexNormalInputs
{
real3 tangentWS;
real3 bitangentWS;
float3 normalWS;
};
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/ShaderVariablesFunctions.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Deprecated.hlsl"
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: e01bb373f731e2946bb996c6b980c1ab
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,17 @@
#ifndef UNITY_DECLARE_DEPTH_TEXTURE_INCLUDED
#define UNITY_DECLARE_DEPTH_TEXTURE_INCLUDED
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Core.hlsl"
TEXTURE2D_X_FLOAT(_CameraDepthTexture);
SAMPLER(sampler_CameraDepthTexture);
float SampleSceneDepth(float2 uv)
{
return SAMPLE_TEXTURE2D_X(_CameraDepthTexture, sampler_CameraDepthTexture, UnityStereoTransformScreenSpaceTex(uv)).r;
}
float LoadSceneDepth(uint2 uv)
{
return LOAD_TEXTURE2D_X(_CameraDepthTexture, uv).r;
}
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 5080cbd4eecd4a74b849da7f9b53632b
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,33 @@
#ifndef UNITY_DECLARE_NORMALS_TEXTURE_INCLUDED
#define UNITY_DECLARE_NORMALS_TEXTURE_INCLUDED
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Core.hlsl"
TEXTURE2D_X_FLOAT(_CameraNormalsTexture);
SAMPLER(sampler_CameraNormalsTexture);
float3 SampleSceneNormals(float2 uv)
{
float3 normal = SAMPLE_TEXTURE2D_X(_CameraNormalsTexture, sampler_CameraNormalsTexture, UnityStereoTransformScreenSpaceTex(uv)).xyz;
#if defined(_GBUFFER_NORMALS_OCT)
half2 remappedOctNormalWS = Unpack888ToFloat2(normal); // values between [ 0, 1]
half2 octNormalWS = remappedOctNormalWS.xy * 2.0h - 1.0h; // values between [-1, +1]
normal = UnpackNormalOctQuadEncode(octNormalWS);
#endif
return normal;
}
float3 LoadSceneNormals(uint2 uv)
{
float3 normal = LOAD_TEXTURE2D_X(_CameraNormalsTexture, uv).xyz;
#if defined(_GBUFFER_NORMALS_OCT)
half2 remappedOctNormalWS = Unpack888ToFloat2(normal); // values between [ 0, 1]
half2 octNormalWS = remappedOctNormalWS.xy * 2.0h - 1.0h; // values between [-1, +1]
normal = UnpackNormalOctQuadEncode(octNormalWS);
#endif
return normal;
}
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 8e70e91938193854da65cb4c9d09b99b
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,17 @@
#ifndef UNITY_DECLARE_OPAQUE_TEXTURE_INCLUDED
#define UNITY_DECLARE_OPAQUE_TEXTURE_INCLUDED
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Core.hlsl"
TEXTURE2D_X(_CameraOpaqueTexture);
SAMPLER(sampler_CameraOpaqueTexture);
float3 SampleSceneColor(float2 uv)
{
return SAMPLE_TEXTURE2D_X(_CameraOpaqueTexture, sampler_CameraOpaqueTexture, UnityStereoTransformScreenSpaceTex(uv)).rgb;
}
float3 LoadSceneColor(uint2 uv)
{
return LOAD_TEXTURE2D_X(_CameraOpaqueTexture, uv).rgb;
}
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 8f04f9a51bb7cae408ba6b74194f84f7
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,41 @@
#ifndef BUILTIN_DEPRECATED_INCLUDED
#define BUILTIN_DEPRECATED_INCLUDED
// Stereo-related bits
#define SCREENSPACE_TEXTURE TEXTURE2D_X
#define SCREENSPACE_TEXTURE_FLOAT TEXTURE2D_X_FLOAT
#define SCREENSPACE_TEXTURE_HALF TEXTURE2D_X_HALF
// Typo-fixes, re-route to new name for backwards compatiblity (if there are external dependencies).
#define kDieletricSpec kDielectricSpec
#define DirectBDRF DirectBRDF
// Deprecated: not using consistent naming convention
#if defined(USING_STEREO_MATRICES)
#define unity_StereoMatrixIP unity_StereoMatrixInvP
#define unity_StereoMatrixIVP unity_StereoMatrixInvVP
#endif
// Previously used when rendering with DrawObjectsPass.
// Global object render pass data containing various settings.
// x,y,z are currently unused
// w is used for knowing whether the object is opaque(1) or alpha blended(0)
half4 _DrawObjectPassData;
#if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA
// _AdditionalShadowsIndices was deprecated - To get the first shadow slice index for a light, use GetAdditionalLightShadowParams(lightIndex).w [see Shadows.hlsl]
#define _AdditionalShadowsIndices _AdditionalShadowParams_SSBO
// _AdditionalShadowsBuffer was deprecated - To access a shadow slice's matrix, use _AdditionalLightsWorldToShadow_SSBO[shadowSliceIndex] - To access other shadow parameters, use GetAdditionalLightShadowParams(int lightIndex) [see Shadows.hlsl]
#define _AdditionalShadowsBuffer _AdditionalLightsWorldToShadow_SSBO
#endif
// Deprecated: even when USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA is defined we do not this structure anymore, because worldToShadowMatrix and shadowParams must be stored in arrays of different sizes
// To get the first shadow slice index for a light, use GetAdditionalLightShadowParams(lightIndex).w [see Shadows.hlsl]
// To access other shadow parameters, use GetAdditionalLightShadowParams(int lightIndex)[see Shadows.hlsl]
struct ShadowData
{
float4x4 worldToShadowMatrix; // per-shadow-slice
float4 shadowParams; // per-casting-light
};
#endif // BUILTIN_DEPRECATED_INCLUDED

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 8ac4c7f9b9937b64885ce949fc6d6525
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,105 @@
#ifndef BUILTIN_INPUT_INCLUDED
#define BUILTIN_INPUT_INCLUDED
#define MAX_VISIBLE_LIGHTS_UBO 32
#define MAX_VISIBLE_LIGHTS_SSBO 256
// Keep in sync with RenderingUtils.useStructuredBuffer
#define USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA 0
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/ShaderTypes.cs.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Deprecated.hlsl"
#if defined(SHADER_API_MOBILE) && (defined(SHADER_API_GLES) || defined(SHADER_API_GLES30))
#define MAX_VISIBLE_LIGHTS 16
#elif defined(SHADER_API_MOBILE) || (defined(SHADER_API_GLCORE) && !defined(SHADER_API_SWITCH)) || defined(SHADER_API_GLES) || defined(SHADER_API_GLES3) // Workaround because SHADER_API_GLCORE is also defined when SHADER_API_SWITCH is
#define MAX_VISIBLE_LIGHTS 32
#else
#define MAX_VISIBLE_LIGHTS 256
#endif
struct InputData
{
float3 positionWS;
half3 normalWS;
half3 viewDirectionWS;
float4 shadowCoord;
half fogCoord;
half3 vertexLighting;
half3 bakedGI;
float2 normalizedScreenSpaceUV;
half4 shadowMask;
};
///////////////////////////////////////////////////////////////////////////////
// Constant Buffers //
///////////////////////////////////////////////////////////////////////////////
half4 _GlossyEnvironmentColor;
half4 _SubtractiveShadowColor;
#define _InvCameraViewProj unity_MatrixInvVP
float4 _ScaledScreenParams;
float4 _MainLightPosition;
half4 _MainLightColor;
half4 _MainLightOcclusionProbes;
// xyz are currently unused
// w: directLightStrength
half4 _AmbientOcclusionParam;
half4 _AdditionalLightsCount;
#if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA
StructuredBuffer<LightData> _AdditionalLightsBuffer;
StructuredBuffer<int> _AdditionalLightsIndices;
#else
// GLES3 causes a performance regression in some devices when using CBUFFER.
#ifndef SHADER_API_GLES3
CBUFFER_START(AdditionalLights)
#endif
float4 _AdditionalLightsPosition[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightsColor[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightsAttenuation[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightsSpotDir[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightsOcclusionProbes[MAX_VISIBLE_LIGHTS];
#ifndef SHADER_API_GLES3
CBUFFER_END
#endif
#endif
// Duplicate defined symbols in built-in target
#ifndef BUILTIN_TARGET_API
#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 (float4x4)0
#define UNITY_MATRIX_VP unity_MatrixVP
#define UNITY_MATRIX_I_VP (float4x4)0
#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)
#define UNITY_PREV_MATRIX_M unity_MatrixPreviousM
#define UNITY_PREV_MATRIX_I_M unity_MatrixPreviousMI
#else
// Not defined already by built-in
#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_I_P (float4x4)0
#define UNITY_MATRIX_I_VP (float4x4)0
#define UNITY_PREV_MATRIX_M (float4x4)0
#define UNITY_PREV_MATRIX_I_M (float4x4)0
#endif
// Note: #include order is important here.
// UnityInput.hlsl must be included before UnityInstancing.hlsl, so constant buffer
// declarations don't fail because of instancing macros.
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/UnityInput.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl"
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 1a6eb37d2c834244cbdd9d92ce6a52ed
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,986 @@
#ifndef BUILTIN_LIGHTING_INCLUDED
#define BUILTIN_LIGHTING_INCLUDED
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Deprecated.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/SurfaceData.hlsl"
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Shadows.hlsl"
// If lightmap is not defined than we evaluate GI (ambient + probes) from SH
// We might do it fully or partially in vertex to save shader ALU
#if !defined(LIGHTMAP_ON)
// TODO: Controls things like these by exposing SHADER_QUALITY levels (low, medium, high)
#if defined(SHADER_API_GLES) || !defined(_NORMALMAP)
// Evaluates SH fully in vertex
#define EVALUATE_SH_VERTEX
#elif !SHADER_HINT_NICE_QUALITY
// Evaluates L2 SH in vertex and L0L1 in pixel
#define EVALUATE_SH_MIXED
#endif
// Otherwise evaluate SH fully per-pixel
#endif
#ifdef LIGHTMAP_ON
#define DECLARE_LIGHTMAP_OR_SH(lmName, shName, index) float2 lmName : TEXCOORD##index
#define OUTPUT_LIGHTMAP_UV(lightmapUV, lightmapScaleOffset, OUT) OUT.xy = lightmapUV.xy * lightmapScaleOffset.xy + lightmapScaleOffset.zw;
#define OUTPUT_SH(normalWS, OUT)
#else
#define DECLARE_LIGHTMAP_OR_SH(lmName, shName, index) half3 shName : TEXCOORD##index
#define OUTPUT_LIGHTMAP_UV(lightmapUV, lightmapScaleOffset, OUT)
#define OUTPUT_SH(normalWS, OUT) OUT.xyz = SampleSHVertex(normalWS)
#endif
// Renamed -> LIGHTMAP_SHADOW_MIXING
#if !defined(_MIXED_LIGHTING_SUBTRACTIVE) && defined(LIGHTMAP_SHADOW_MIXING) && !defined(SHADOWS_SHADOWMASK)
#define _MIXED_LIGHTING_SUBTRACTIVE
#endif
///////////////////////////////////////////////////////////////////////////////
// Light Helpers //
///////////////////////////////////////////////////////////////////////////////
// Abstraction over Light shading data.
struct Light
{
half3 direction;
half3 color;
half distanceAttenuation;
half shadowAttenuation;
};
// WebGL1 does not support the variable conditioned for loops used for additional lights
#if !defined(_USE_WEBGL1_LIGHTS) && defined(UNITY_PLATFORM_WEBGL) && !defined(SHADER_API_GLES3)
#define _USE_WEBGL1_LIGHTS 1
#define _WEBGL1_MAX_LIGHTS 8
#else
#define _USE_WEBGL1_LIGHTS 0
#endif
#if !_USE_WEBGL1_LIGHTS
#define LIGHT_LOOP_BEGIN(lightCount) \
for (uint lightIndex = 0u; lightIndex < lightCount; ++lightIndex) {
#define LIGHT_LOOP_END }
#else
// WebGL 1 doesn't support variable for loop conditions
#define LIGHT_LOOP_BEGIN(lightCount) \
for (int lightIndex = 0; lightIndex < _WEBGL1_MAX_LIGHTS; ++lightIndex) { \
if (lightIndex >= (int)lightCount) break;
#define LIGHT_LOOP_END }
#endif
///////////////////////////////////////////////////////////////////////////////
// Attenuation Functions /
///////////////////////////////////////////////////////////////////////////////
// Matches Unity Vanila attenuation
// Attenuation smoothly decreases to light range.
float DistanceAttenuation(float distanceSqr, half2 distanceAttenuation)
{
// We use a shared distance attenuation for additional directional and puctual lights
// for directional lights attenuation will be 1
float lightAtten = rcp(distanceSqr);
#if SHADER_HINT_NICE_QUALITY
// Use the smoothing factor also used in the Unity lightmapper.
half factor = distanceSqr * distanceAttenuation.x;
half smoothFactor = saturate(1.0h - factor * factor);
smoothFactor = smoothFactor * smoothFactor;
#else
// We need to smoothly fade attenuation to light range. We start fading linearly at 80% of light range
// Therefore:
// fadeDistance = (0.8 * 0.8 * lightRangeSq)
// smoothFactor = (lightRangeSqr - distanceSqr) / (lightRangeSqr - fadeDistance)
// We can rewrite that to fit a MAD by doing
// distanceSqr * (1.0 / (fadeDistanceSqr - lightRangeSqr)) + (-lightRangeSqr / (fadeDistanceSqr - lightRangeSqr)
// distanceSqr * distanceAttenuation.y + distanceAttenuation.z
half smoothFactor = saturate(distanceSqr * distanceAttenuation.x + distanceAttenuation.y);
#endif
return lightAtten * smoothFactor;
}
half AngleAttenuation(half3 spotDirection, half3 lightDirection, half2 spotAttenuation)
{
// Spot Attenuation with a linear falloff can be defined as
// (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)
// This can be rewritten as
// invAngleRange = 1.0 / (cosInnerAngle - cosOuterAngle)
// SdotL * invAngleRange + (-cosOuterAngle * invAngleRange)
// SdotL * spotAttenuation.x + spotAttenuation.y
// If we precompute the terms in a MAD instruction
half SdotL = dot(spotDirection, lightDirection);
half atten = saturate(SdotL * spotAttenuation.x + spotAttenuation.y);
return atten * atten;
}
///////////////////////////////////////////////////////////////////////////////
// Light Abstraction //
///////////////////////////////////////////////////////////////////////////////
Light GetMainLight()
{
Light light;
#ifndef BUILTIN_TARGET_API
light.direction = _MainLightPosition.xyz;
light.distanceAttenuation = unity_LightData.z; // unity_LightData.z is 1 when not culled by the culling mask, otherwise 0.
light.shadowAttenuation = 1.0;
light.color = _MainLightColor.rgb;
#endif
return light;
}
Light GetMainLight(float4 shadowCoord)
{
Light light = GetMainLight();
light.shadowAttenuation = MainLightRealtimeShadow(shadowCoord);
return light;
}
Light GetMainLight(float4 shadowCoord, float3 positionWS, half4 shadowMask)
{
Light light = GetMainLight();
light.shadowAttenuation = MainLightShadow(shadowCoord, positionWS, shadowMask, _MainLightOcclusionProbes);
return light;
}
// Fills a light struct given a perObjectLightIndex
Light GetAdditionalPerObjectLight(int perObjectLightIndex, float3 positionWS)
{
// Abstraction over Light input constants
#if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA
float4 lightPositionWS = _AdditionalLightsBuffer[perObjectLightIndex].position;
half3 color = _AdditionalLightsBuffer[perObjectLightIndex].color.rgb;
half4 distanceAndSpotAttenuation = _AdditionalLightsBuffer[perObjectLightIndex].attenuation;
half4 spotDirection = _AdditionalLightsBuffer[perObjectLightIndex].spotDirection;
#else
float4 lightPositionWS = _AdditionalLightsPosition[perObjectLightIndex];
half3 color = _AdditionalLightsColor[perObjectLightIndex].rgb;
half4 distanceAndSpotAttenuation = _AdditionalLightsAttenuation[perObjectLightIndex];
half4 spotDirection = _AdditionalLightsSpotDir[perObjectLightIndex];
#endif
// Directional lights store direction in lightPosition.xyz and have .w set to 0.0.
// This way the following code will work for both directional and punctual lights.
float3 lightVector = lightPositionWS.xyz - positionWS * lightPositionWS.w;
float distanceSqr = max(dot(lightVector, lightVector), HALF_MIN);
half3 lightDirection = half3(lightVector * rsqrt(distanceSqr));
half attenuation = DistanceAttenuation(distanceSqr, distanceAndSpotAttenuation.xy) * AngleAttenuation(spotDirection.xyz, lightDirection, distanceAndSpotAttenuation.zw);
Light light;
light.direction = lightDirection;
light.distanceAttenuation = attenuation;
light.shadowAttenuation = 1.0; // This value can later be overridden in GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask)
light.color = color;
return light;
}
uint GetPerObjectLightIndexOffset()
{
#if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA
return unity_LightData.x;
#else
return 0;
#endif
}
// Returns a per-object index given a loop index.
// This abstract the underlying data implementation for storing lights/light indices
int GetPerObjectLightIndex(uint index)
{
#ifndef BUILTIN_TARGET_API
/////////////////////////////////////////////////////////////////////////////////////////////
// Structured Buffer Path /
// /
// Lights and light indices are stored in StructuredBuffer. We can just index them. /
// Currently all non-mobile platforms take this path :( /
// There are limitation in mobile GPUs to use SSBO (performance / no vertex shader support) /
/////////////////////////////////////////////////////////////////////////////////////////////
#if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA
uint offset = unity_LightData.x;
return _AdditionalLightsIndices[offset + index];
/////////////////////////////////////////////////////////////////////////////////////////////
// UBO path /
// /
// We store 8 light indices in float4 unity_LightIndices[2]; /
// Due to memory alignment unity doesn't support int[] or float[] /
// Even trying to reinterpret cast the unity_LightIndices to float[] won't work /
// it will cast to float4[] and create extra register pressure. :( /
/////////////////////////////////////////////////////////////////////////////////////////////
#elif !defined(SHADER_API_GLES)
// since index is uint shader compiler will implement
// div & mod as bitfield ops (shift and mask).
// TODO: Can we index a float4? Currently compiler is
// replacing unity_LightIndicesX[i] with a dp4 with identity matrix.
// u_xlat16_40 = dot(unity_LightIndices[int(u_xlatu13)], ImmCB_0_0_0[u_xlati1]);
// This increases both arithmetic and register pressure.
return unity_LightIndices[index / 4][index % 4];
#else
// Fallback to GLES2. No bitfield magic here :(.
// We limit to 4 indices per object and only sample unity_4LightIndices0.
// Conditional moves are branch free even on mali-400
// small arithmetic cost but no extra register pressure from ImmCB_0_0_0 matrix.
half2 lightIndex2 = (index < 2.0h) ? unity_LightIndices[0].xy : unity_LightIndices[0].zw;
half i_rem = (index < 2.0h) ? index : index - 2.0h;
return (i_rem < 1.0h) ? lightIndex2.x : lightIndex2.y;
#endif
#else
return 0;
#endif
}
// Fills a light struct given a loop i index. This will convert the i
// index to a perObjectLightIndex
Light GetAdditionalLight(uint i, float3 positionWS)
{
int perObjectLightIndex = GetPerObjectLightIndex(i);
return GetAdditionalPerObjectLight(perObjectLightIndex, positionWS);
}
Light GetAdditionalLight(uint i, float3 positionWS, half4 shadowMask)
{
int perObjectLightIndex = GetPerObjectLightIndex(i);
Light light = GetAdditionalPerObjectLight(perObjectLightIndex, positionWS);
#if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA
half4 occlusionProbeChannels = _AdditionalLightsBuffer[perObjectLightIndex].occlusionProbeChannels;
#else
half4 occlusionProbeChannels = _AdditionalLightsOcclusionProbes[perObjectLightIndex];
#endif
light.shadowAttenuation = AdditionalLightShadow(perObjectLightIndex, positionWS, light.direction, shadowMask, occlusionProbeChannels);
return light;
}
int GetAdditionalLightsCount()
{
#ifndef BUILTIN_TARGET_API
// TODO: we need to expose in SRP api an ability for the pipeline cap the amount of lights
// in the culling. This way we could do the loop branch with an uniform
// This would be helpful to support baking exceeding lights in SH as well
return min(_AdditionalLightsCount.x, unity_LightData.y);
#else
return 0;
#endif
}
///////////////////////////////////////////////////////////////////////////////
// BRDF Functions //
///////////////////////////////////////////////////////////////////////////////
#define kDielectricSpec half4(0.04, 0.04, 0.04, 1.0 - 0.04) // standard dielectric reflectivity coef at incident angle (= 4%)
struct BRDFData
{
half3 albedo;
half3 diffuse;
half3 specular;
half reflectivity;
half perceptualRoughness;
half roughness;
half roughness2;
half grazingTerm;
// We save some light invariant BRDF terms so we don't have to recompute
// them in the light loop. Take a look at DirectBRDF function for detailed explaination.
half normalizationTerm; // roughness * 4.0 + 2.0
half roughness2MinusOne; // roughness^2 - 1.0
};
half ReflectivitySpecular(half3 specular)
{
#if defined(SHADER_API_GLES)
return specular.r; // Red channel - because most metals are either monocrhome or with redish/yellowish tint
#else
return Max3(specular.r, specular.g, specular.b);
#endif
}
half OneMinusReflectivityMetallic(half metallic)
{
// We'll need oneMinusReflectivity, so
// 1-reflectivity = 1-lerp(dielectricSpec, 1, metallic) = lerp(1-dielectricSpec, 0, metallic)
// store (1-dielectricSpec) in kDielectricSpec.a, then
// 1-reflectivity = lerp(alpha, 0, metallic) = alpha + metallic*(0 - alpha) =
// = alpha - metallic * alpha
half oneMinusDielectricSpec = kDielectricSpec.a;
return oneMinusDielectricSpec - metallic * oneMinusDielectricSpec;
}
half MetallicFromReflectivity(half reflectivity)
{
half oneMinusDielectricSpec = kDielectricSpec.a;
return (reflectivity - kDielectricSpec.r) / oneMinusDielectricSpec;
}
inline void InitializeBRDFDataDirect(half3 albedo, half3 diffuse, half3 specular, half reflectivity, half oneMinusReflectivity, half smoothness, inout half alpha, out BRDFData outBRDFData)
{
outBRDFData = (BRDFData)0;
outBRDFData.albedo = albedo;
outBRDFData.diffuse = diffuse;
outBRDFData.specular = specular;
outBRDFData.reflectivity = reflectivity;
outBRDFData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(smoothness);
outBRDFData.roughness = max(PerceptualRoughnessToRoughness(outBRDFData.perceptualRoughness), HALF_MIN_SQRT);
outBRDFData.roughness2 = max(outBRDFData.roughness * outBRDFData.roughness, HALF_MIN);
outBRDFData.grazingTerm = saturate(smoothness + reflectivity);
outBRDFData.normalizationTerm = outBRDFData.roughness * 4.0h + 2.0h;
outBRDFData.roughness2MinusOne = outBRDFData.roughness2 - 1.0h;
#ifdef _ALPHAPREMULTIPLY_ON
outBRDFData.diffuse *= alpha;
alpha = alpha * oneMinusReflectivity + reflectivity; // NOTE: alpha modified and propagated up.
#endif
}
// Legacy: do not call, will not correctly initialize albedo property.
inline void InitializeBRDFDataDirect(half3 diffuse, half3 specular, half reflectivity, half oneMinusReflectivity, half smoothness, inout half alpha, out BRDFData outBRDFData)
{
InitializeBRDFDataDirect(half3(0.0, 0.0, 0.0), diffuse, specular, reflectivity, oneMinusReflectivity, smoothness, alpha, outBRDFData);
}
// Initialize BRDFData for material, managing both specular and metallic setup using shader keyword _SPECULAR_SETUP.
inline void InitializeBRDFData(half3 albedo, half metallic, half3 specular, half smoothness, inout half alpha, out BRDFData outBRDFData)
{
#ifdef _SPECULAR_SETUP
half reflectivity = ReflectivitySpecular(specular);
half oneMinusReflectivity = 1.0 - reflectivity;
half3 brdfDiffuse = albedo * oneMinusReflectivity;
half3 brdfSpecular = specular;
#else
half oneMinusReflectivity = OneMinusReflectivityMetallic(metallic);
half reflectivity = 1.0 - oneMinusReflectivity;
half3 brdfDiffuse = albedo * oneMinusReflectivity;
half3 brdfSpecular = lerp(kDieletricSpec.rgb, albedo, metallic);
#endif
InitializeBRDFDataDirect(albedo, brdfDiffuse, brdfSpecular, reflectivity, oneMinusReflectivity, smoothness, alpha, outBRDFData);
}
half3 ConvertF0ForClearCoat15(half3 f0)
{
#if defined(SHADER_API_MOBILE)
return ConvertF0ForAirInterfaceToF0ForClearCoat15Fast(f0);
#else
return ConvertF0ForAirInterfaceToF0ForClearCoat15(f0);
#endif
}
inline void InitializeBRDFDataClearCoat(half clearCoatMask, half clearCoatSmoothness, inout BRDFData baseBRDFData, out BRDFData outBRDFData)
{
outBRDFData = (BRDFData)0;
outBRDFData.albedo = 1.0h;
// Calculate Roughness of Clear Coat layer
outBRDFData.diffuse = kDielectricSpec.aaa; // 1 - kDielectricSpec
outBRDFData.specular = kDielectricSpec.rgb;
outBRDFData.reflectivity = kDielectricSpec.r;
outBRDFData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(clearCoatSmoothness);
outBRDFData.roughness = max(PerceptualRoughnessToRoughness(outBRDFData.perceptualRoughness), HALF_MIN_SQRT);
outBRDFData.roughness2 = max(outBRDFData.roughness * outBRDFData.roughness, HALF_MIN);
outBRDFData.normalizationTerm = outBRDFData.roughness * 4.0h + 2.0h;
outBRDFData.roughness2MinusOne = outBRDFData.roughness2 - 1.0h;
outBRDFData.grazingTerm = saturate(clearCoatSmoothness + kDielectricSpec.x);
// Relatively small effect, cut it for lower quality
#if !defined(SHADER_API_MOBILE)
// Modify Roughness of base layer using coat IOR
half ieta = lerp(1.0h, CLEAR_COAT_IETA, clearCoatMask);
half coatRoughnessScale = Sq(ieta);
half sigma = RoughnessToVariance(PerceptualRoughnessToRoughness(baseBRDFData.perceptualRoughness));
baseBRDFData.perceptualRoughness = RoughnessToPerceptualRoughness(VarianceToRoughness(sigma * coatRoughnessScale));
// Recompute base material for new roughness, previous computation should be eliminated by the compiler (as it's unused)
baseBRDFData.roughness = max(PerceptualRoughnessToRoughness(baseBRDFData.perceptualRoughness), HALF_MIN_SQRT);
baseBRDFData.roughness2 = max(baseBRDFData.roughness * baseBRDFData.roughness, HALF_MIN);
baseBRDFData.normalizationTerm = baseBRDFData.roughness * 4.0h + 2.0h;
baseBRDFData.roughness2MinusOne = baseBRDFData.roughness2 - 1.0h;
#endif
// Darken/saturate base layer using coat to surface reflectance (vs. air to surface)
baseBRDFData.specular = lerp(baseBRDFData.specular, ConvertF0ForClearCoat15(baseBRDFData.specular), clearCoatMask);
// TODO: what about diffuse? at least in specular workflow diffuse should be recalculated as it directly depends on it.
}
// Computes the specular term for EnvironmentBRDF
half3 EnvironmentBRDFSpecular(BRDFData brdfData, half fresnelTerm)
{
float surfaceReduction = 1.0 / (brdfData.roughness2 + 1.0);
return surfaceReduction * lerp(brdfData.specular, brdfData.grazingTerm, fresnelTerm);
}
half3 EnvironmentBRDF(BRDFData brdfData, half3 indirectDiffuse, half3 indirectSpecular, half fresnelTerm)
{
half3 c = indirectDiffuse * brdfData.diffuse;
c += indirectSpecular * EnvironmentBRDFSpecular(brdfData, fresnelTerm);
return c;
}
// Environment BRDF without diffuse for clear coat
half3 EnvironmentBRDFClearCoat(BRDFData brdfData, half clearCoatMask, half3 indirectSpecular, half fresnelTerm)
{
float surfaceReduction = 1.0 / (brdfData.roughness2 + 1.0);
return indirectSpecular * EnvironmentBRDFSpecular(brdfData, fresnelTerm) * clearCoatMask;
}
// Computes the scalar specular term for Minimalist CookTorrance BRDF
// NOTE: needs to be multiplied with reflectance f0, i.e. specular color to complete
half DirectBRDFSpecular(BRDFData brdfData, half3 normalWS, half3 lightDirectionWS, half3 viewDirectionWS)
{
float3 halfDir = SafeNormalize(float3(lightDirectionWS) + float3(viewDirectionWS));
float NoH = saturate(dot(normalWS, halfDir));
half LoH = saturate(dot(lightDirectionWS, halfDir));
// GGX Distribution multiplied by combined approximation of Visibility and Fresnel
// BRDFspec = (D * V * F) / 4.0
// D = roughness^2 / ( NoH^2 * (roughness^2 - 1) + 1 )^2
// V * F = 1.0 / ( LoH^2 * (roughness + 0.5) )
// See "Optimizing PBR for Mobile" from Siggraph 2015 moving mobile graphics course
// https://community.arm.com/events/1155
// Final BRDFspec = roughness^2 / ( NoH^2 * (roughness^2 - 1) + 1 )^2 * (LoH^2 * (roughness + 0.5) * 4.0)
// We further optimize a few light invariant terms
// brdfData.normalizationTerm = (roughness + 0.5) * 4.0 rewritten as roughness * 4.0 + 2.0 to a fit a MAD.
float d = NoH * NoH * brdfData.roughness2MinusOne + 1.00001f;
half LoH2 = LoH * LoH;
half specularTerm = brdfData.roughness2 / ((d * d) * max(0.1h, LoH2) * brdfData.normalizationTerm);
// On platforms where half actually means something, the denominator has a risk of overflow
// clamp below was added specifically to "fix" that, but dx compiler (we convert bytecode to metal/gles)
// sees that specularTerm have only non-negative terms, so it skips max(0,..) in clamp (leaving only min(100,...))
#if defined (SHADER_API_MOBILE) || defined (SHADER_API_SWITCH)
specularTerm = specularTerm - HALF_MIN;
specularTerm = clamp(specularTerm, 0.0, 100.0); // Prevent FP16 overflow on mobiles
#endif
return specularTerm;
}
// Based on Minimalist CookTorrance BRDF
// Implementation is slightly different from original derivation: http://www.thetenthplanet.de/archives/255
//
// * NDF [Modified] GGX
// * Modified Kelemen and Szirmay-Kalos for Visibility term
// * Fresnel approximated with 1/LdotH
half3 DirectBDRF(BRDFData brdfData, half3 normalWS, half3 lightDirectionWS, half3 viewDirectionWS, bool specularHighlightsOff)
{
// Can still do compile-time optimisation.
// If no compile-time optimized, extra overhead if branch taken is around +2.5% on some untethered platforms, -10% if not taken.
[branch] if (!specularHighlightsOff)
{
half specularTerm = DirectBRDFSpecular(brdfData, normalWS, lightDirectionWS, viewDirectionWS);
half3 color = brdfData.diffuse + specularTerm * brdfData.specular;
return color;
}
else
return brdfData.diffuse;
}
// Based on Minimalist CookTorrance BRDF
// Implementation is slightly different from original derivation: http://www.thetenthplanet.de/archives/255
//
// * NDF [Modified] GGX
// * Modified Kelemen and Szirmay-Kalos for Visibility term
// * Fresnel approximated with 1/LdotH
half3 DirectBRDF(BRDFData brdfData, half3 normalWS, half3 lightDirectionWS, half3 viewDirectionWS)
{
#ifndef _SPECULARHIGHLIGHTS_OFF
return brdfData.diffuse + DirectBRDFSpecular(brdfData, normalWS, lightDirectionWS, viewDirectionWS) * brdfData.specular;
#else
return brdfData.diffuse;
#endif
}
///////////////////////////////////////////////////////////////////////////////
// Global Illumination //
///////////////////////////////////////////////////////////////////////////////
// Ambient occlusion
TEXTURE2D_X(_ScreenSpaceOcclusionTexture);
SAMPLER(sampler_ScreenSpaceOcclusionTexture);
struct AmbientOcclusionFactor
{
half indirectAmbientOcclusion;
half directAmbientOcclusion;
};
half SampleAmbientOcclusion(float2 normalizedScreenSpaceUV)
{
float2 uv = UnityStereoTransformScreenSpaceTex(normalizedScreenSpaceUV);
return SAMPLE_TEXTURE2D_X(_ScreenSpaceOcclusionTexture, sampler_ScreenSpaceOcclusionTexture, uv).x;
}
AmbientOcclusionFactor GetScreenSpaceAmbientOcclusion(float2 normalizedScreenSpaceUV)
{
AmbientOcclusionFactor aoFactor;
aoFactor.indirectAmbientOcclusion = SampleAmbientOcclusion(normalizedScreenSpaceUV);
aoFactor.directAmbientOcclusion = lerp(1.0, aoFactor.indirectAmbientOcclusion, _AmbientOcclusionParam.w);
return aoFactor;
}
// Samples SH L0, L1 and L2 terms
half3 SampleSH(half3 normalWS)
{
// LPPV is not supported in Ligthweight Pipeline
real4 SHCoefficients[7];
SHCoefficients[0] = unity_SHAr;
SHCoefficients[1] = unity_SHAg;
SHCoefficients[2] = unity_SHAb;
SHCoefficients[3] = unity_SHBr;
SHCoefficients[4] = unity_SHBg;
SHCoefficients[5] = unity_SHBb;
SHCoefficients[6] = unity_SHC;
return max(half3(0, 0, 0), SampleSH9(SHCoefficients, normalWS));
}
// SH Vertex Evaluation. Depending on target SH sampling might be
// done completely per vertex or mixed with L2 term per vertex and L0, L1
// per pixel. See SampleSHPixel
half3 SampleSHVertex(half3 normalWS)
{
#if defined(EVALUATE_SH_VERTEX)
return SampleSH(normalWS);
#elif defined(EVALUATE_SH_MIXED)
// no max since this is only L2 contribution
return SHEvalLinearL2(normalWS, unity_SHBr, unity_SHBg, unity_SHBb, unity_SHC);
#endif
// Fully per-pixel. Nothing to compute.
return half3(0.0, 0.0, 0.0);
}
// SH Pixel Evaluation. Depending on target SH sampling might be done
// mixed or fully in pixel. See SampleSHVertex
half3 SampleSHPixel(half3 L2Term, half3 normalWS)
{
#if defined(EVALUATE_SH_VERTEX)
return L2Term;
#elif defined(EVALUATE_SH_MIXED)
half3 L0L1Term = SHEvalLinearL0L1(normalWS, unity_SHAr, unity_SHAg, unity_SHAb);
half3 res = L2Term + L0L1Term;
#ifdef UNITY_COLORSPACE_GAMMA
res = LinearToSRGB(res);
#endif
return max(half3(0, 0, 0), res);
#endif
// Default: Evaluate SH fully per-pixel
return SampleSH(normalWS);
}
#define LIGHTMAP_NAME unity_Lightmap
#define LIGHTMAP_INDIRECTION_NAME unity_LightmapInd
#define LIGHTMAP_SAMPLER_NAME samplerunity_Lightmap
#define LIGHTMAP_SAMPLE_EXTRA_ARGS lightmapUV
// Sample baked lightmap. Non-Direction and Directional if available.
// Realtime GI is not supported.
half3 SampleLightmap(float2 lightmapUV, half3 normalWS)
{
#ifdef UNITY_LIGHTMAP_FULL_HDR
bool encodedLightmap = false;
#else
bool encodedLightmap = true;
#endif
half4 decodeInstructions = half4(LIGHTMAP_HDR_MULTIPLIER, LIGHTMAP_HDR_EXPONENT, 0.0h, 0.0h);
// The shader library sample lightmap functions transform the lightmap uv coords to apply bias and scale.
// However, builtin pipeline already transformed those coords in vertex. We pass half4(1, 1, 0, 0) and
// the compiler will optimize the transform away.
half4 transformCoords = half4(1, 1, 0, 0);
#if defined(LIGHTMAP_ON) && defined(DIRLIGHTMAP_COMBINED)
return SampleDirectionalLightmap(TEXTURE2D_LIGHTMAP_ARGS(LIGHTMAP_NAME, LIGHTMAP_SAMPLER_NAME),
TEXTURE2D_LIGHTMAP_ARGS(LIGHTMAP_INDIRECTION_NAME, LIGHTMAP_SAMPLER_NAME),
LIGHTMAP_SAMPLE_EXTRA_ARGS, transformCoords, normalWS, encodedLightmap, decodeInstructions);
#elif defined(LIGHTMAP_ON)
return SampleSingleLightmap(TEXTURE2D_LIGHTMAP_ARGS(LIGHTMAP_NAME, LIGHTMAP_SAMPLER_NAME), LIGHTMAP_SAMPLE_EXTRA_ARGS, transformCoords, encodedLightmap, decodeInstructions);
#else
return half3(0.0, 0.0, 0.0);
#endif
}
// We either sample GI from baked lightmap or from probes.
// If lightmap: sampleData.xy = lightmapUV
// If probe: sampleData.xyz = L2 SH terms
#if defined(LIGHTMAP_ON)
#define SAMPLE_GI(lmName, shName, normalWSName) SampleLightmap(lmName, normalWSName)
#else
#define SAMPLE_GI(lmName, shName, normalWSName) SampleSHPixel(shName, normalWSName)
#endif
half3 GlossyEnvironmentReflection(half3 reflectVector, half perceptualRoughness, half occlusion)
{
#if !defined(_ENVIRONMENTREFLECTIONS_OFF)
half mip = PerceptualRoughnessToMipmapLevel(perceptualRoughness);
half4 encodedIrradiance = SAMPLE_TEXTURECUBE_LOD(unity_SpecCube0, samplerunity_SpecCube0, reflectVector, mip);
half3 irradiance = DecodeHDREnvironment(encodedIrradiance, unity_SpecCube0_HDR);
return irradiance * occlusion;
#endif // GLOSSY_REFLECTIONS
return _GlossyEnvironmentColor.rgb * occlusion;
}
half3 SubtractDirectMainLightFromLightmap(Light mainLight, half3 normalWS, half3 bakedGI)
{
// Let's try to make realtime shadows work on a surface, which already contains
// baked lighting and shadowing from the main sun light.
// Summary:
// 1) Calculate possible value in the shadow by subtracting estimated light contribution from the places occluded by realtime shadow:
// a) preserves other baked lights and light bounces
// b) eliminates shadows on the geometry facing away from the light
// 2) Clamp against user defined ShadowColor.
// 3) Pick original lightmap value, if it is the darkest one.
// 1) Gives good estimate of illumination as if light would've been shadowed during the bake.
// We only subtract the main direction light. This is accounted in the contribution term below.
half shadowStrength = GetMainLightShadowStrength();
half contributionTerm = saturate(dot(mainLight.direction, normalWS));
half3 lambert = mainLight.color * contributionTerm;
half3 estimatedLightContributionMaskedByInverseOfShadow = lambert * (1.0 - mainLight.shadowAttenuation);
half3 subtractedLightmap = bakedGI - estimatedLightContributionMaskedByInverseOfShadow;
// 2) Allows user to define overall ambient of the scene and control situation when realtime shadow becomes too dark.
half3 realtimeShadow = max(subtractedLightmap, _SubtractiveShadowColor.xyz);
realtimeShadow = lerp(bakedGI, realtimeShadow, shadowStrength);
// 3) Pick darkest color
return min(bakedGI, realtimeShadow);
}
half3 GlobalIllumination(BRDFData brdfData, BRDFData brdfDataClearCoat, float clearCoatMask,
half3 bakedGI, half occlusion,
half3 normalWS, half3 viewDirectionWS)
{
half3 reflectVector = reflect(-viewDirectionWS, normalWS);
half NoV = saturate(dot(normalWS, viewDirectionWS));
half fresnelTerm = Pow4(1.0 - NoV);
half3 indirectDiffuse = bakedGI;
half3 indirectSpecular = GlossyEnvironmentReflection(reflectVector, brdfData.perceptualRoughness, 1.0h);
half3 color = EnvironmentBRDF(brdfData, indirectDiffuse, indirectSpecular, fresnelTerm);
#if defined(_CLEARCOAT) || defined(_CLEARCOATMAP)
half3 coatIndirectSpecular = GlossyEnvironmentReflection(reflectVector, brdfDataClearCoat.perceptualRoughness, 1.0h);
// TODO: "grazing term" causes problems on full roughness
half3 coatColor = EnvironmentBRDFClearCoat(brdfDataClearCoat, clearCoatMask, coatIndirectSpecular, fresnelTerm);
// Blend with base layer using khronos glTF recommended way using NoV
// Smooth surface & "ambiguous" lighting
// NOTE: fresnelTerm (above) is pow4 instead of pow5, but should be ok as blend weight.
half coatFresnel = kDielectricSpec.x + kDielectricSpec.a * fresnelTerm;
return (color * (1.0 - coatFresnel * clearCoatMask) + coatColor) * occlusion;
#else
return color * occlusion;
#endif
}
// Backwards compatiblity
half3 GlobalIllumination(BRDFData brdfData, half3 bakedGI, half occlusion, half3 normalWS, half3 viewDirectionWS)
{
const BRDFData noClearCoat = (BRDFData)0;
return GlobalIllumination(brdfData, noClearCoat, 0.0, bakedGI, occlusion, normalWS, viewDirectionWS);
}
void MixRealtimeAndBakedGI(Light light, half3 normalWS, inout half3 bakedGI)
{
#if defined(LIGHTMAP_ON) && defined(_MIXED_LIGHTING_SUBTRACTIVE)
bakedGI = SubtractDirectMainLightFromLightmap(light, normalWS, bakedGI);
#endif
}
// Backwards compatiblity
void MixRealtimeAndBakedGI(Light light, half3 normalWS, inout half3 bakedGI, half4 shadowMask)
{
MixRealtimeAndBakedGI(light, normalWS, bakedGI);
}
///////////////////////////////////////////////////////////////////////////////
// Lighting Functions //
///////////////////////////////////////////////////////////////////////////////
half3 LightingLambert(half3 lightColor, half3 lightDir, half3 normal)
{
half NdotL = saturate(dot(normal, lightDir));
return lightColor * NdotL;
}
half3 LightingSpecular(half3 lightColor, half3 lightDir, half3 normal, half3 viewDir, half4 specular, half smoothness)
{
float3 halfVec = SafeNormalize(float3(lightDir) + float3(viewDir));
half NdotH = saturate(dot(normal, halfVec));
half modifier = pow(NdotH, smoothness);
half3 specularReflection = specular.rgb * modifier;
return lightColor * specularReflection;
}
half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat,
half3 lightColor, half3 lightDirectionWS, half lightAttenuation,
half3 normalWS, half3 viewDirectionWS,
half clearCoatMask, bool specularHighlightsOff)
{
half NdotL = saturate(dot(normalWS, lightDirectionWS));
half3 radiance = lightColor * (lightAttenuation * NdotL);
half3 brdf = brdfData.diffuse;
#ifndef _SPECULARHIGHLIGHTS_OFF
[branch] if (!specularHighlightsOff)
{
brdf += brdfData.specular * DirectBRDFSpecular(brdfData, normalWS, lightDirectionWS, viewDirectionWS);
#if defined(_CLEARCOAT) || defined(_CLEARCOATMAP)
// Clear coat evaluates the specular a second timw and has some common terms with the base specular.
// We rely on the compiler to merge these and compute them only once.
half brdfCoat = kDielectricSpec.r * DirectBRDFSpecular(brdfDataClearCoat, normalWS, lightDirectionWS, viewDirectionWS);
// Mix clear coat and base layer using khronos glTF recommended formula
// https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md
// Use NoV for direct too instead of LoH as an optimization (NoV is light invariant).
half NoV = saturate(dot(normalWS, viewDirectionWS));
// Use slightly simpler fresnelTerm (Pow4 vs Pow5) as a small optimization.
// It is matching fresnel used in the GI/Env, so should produce a consistent clear coat blend (env vs. direct)
half coatFresnel = kDielectricSpec.x + kDielectricSpec.a * Pow4(1.0 - NoV);
brdf = brdf * (1.0 - clearCoatMask * coatFresnel) + brdfCoat * clearCoatMask;
#endif // _CLEARCOAT
}
#endif // _SPECULARHIGHLIGHTS_OFF
return brdf * radiance;
}
half3 LightingPhysicallyBased(BRDFData brdfData, BRDFData brdfDataClearCoat, Light light, half3 normalWS, half3 viewDirectionWS, half clearCoatMask, bool specularHighlightsOff)
{
return LightingPhysicallyBased(brdfData, brdfDataClearCoat, light.color, light.direction, light.distanceAttenuation * light.shadowAttenuation, normalWS, viewDirectionWS, clearCoatMask, specularHighlightsOff);
}
// Backwards compatibility
half3 LightingPhysicallyBased(BRDFData brdfData, Light light, half3 normalWS, half3 viewDirectionWS)
{
#ifdef _SPECULARHIGHLIGHTS_OFF
bool specularHighlightsOff = true;
#else
bool specularHighlightsOff = false;
#endif
const BRDFData noClearCoat = (BRDFData)0;
return LightingPhysicallyBased(brdfData, noClearCoat, light, normalWS, viewDirectionWS, 0.0, specularHighlightsOff);
}
half3 LightingPhysicallyBased(BRDFData brdfData, half3 lightColor, half3 lightDirectionWS, half lightAttenuation, half3 normalWS, half3 viewDirectionWS)
{
Light light;
light.color = lightColor;
light.direction = lightDirectionWS;
light.distanceAttenuation = lightAttenuation;
light.shadowAttenuation = 1;
return LightingPhysicallyBased(brdfData, light, normalWS, viewDirectionWS);
}
half3 LightingPhysicallyBased(BRDFData brdfData, Light light, half3 normalWS, half3 viewDirectionWS, bool specularHighlightsOff)
{
const BRDFData noClearCoat = (BRDFData)0;
return LightingPhysicallyBased(brdfData, noClearCoat, light, normalWS, viewDirectionWS, 0.0, specularHighlightsOff);
}
half3 LightingPhysicallyBased(BRDFData brdfData, half3 lightColor, half3 lightDirectionWS, half lightAttenuation, half3 normalWS, half3 viewDirectionWS, bool specularHighlightsOff)
{
Light light;
light.color = lightColor;
light.direction = lightDirectionWS;
light.distanceAttenuation = lightAttenuation;
light.shadowAttenuation = 1;
return LightingPhysicallyBased(brdfData, light, viewDirectionWS, specularHighlightsOff, specularHighlightsOff);
}
half3 VertexLighting(float3 positionWS, half3 normalWS)
{
half3 vertexLightColor = half3(0.0, 0.0, 0.0);
#ifdef _ADDITIONAL_LIGHTS_VERTEX
uint lightsCount = GetAdditionalLightsCount();
LIGHT_LOOP_BEGIN(lightsCount)
Light light = GetAdditionalLight(lightIndex, positionWS);
half3 lightColor = light.color * light.distanceAttenuation;
vertexLightColor += LightingLambert(lightColor, light.direction, normalWS);
LIGHT_LOOP_END
#endif
return vertexLightColor;
}
///////////////////////////////////////////////////////////////////////////////
// Fragment Functions //
// Used by ShaderGraph and others builtin renderers //
///////////////////////////////////////////////////////////////////////////////
half4 BuiltInFragmentPBR(InputData inputData, SurfaceData surfaceData)
{
#ifdef _SPECULARHIGHLIGHTS_OFF
bool specularHighlightsOff = true;
#else
bool specularHighlightsOff = false;
#endif
BRDFData brdfData;
// NOTE: can modify alpha
InitializeBRDFData(surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.alpha, brdfData);
BRDFData brdfDataClearCoat = (BRDFData)0;
#if defined(_CLEARCOAT) || defined(_CLEARCOATMAP)
// base brdfData is modified here, rely on the compiler to eliminate dead computation by InitializeBRDFData()
InitializeBRDFDataClearCoat(surfaceData.clearCoatMask, surfaceData.clearCoatSmoothness, brdfData, brdfDataClearCoat);
#endif
// To ensure backward compatibility we have to avoid using shadowMask input, as it is not present in older shaders
#if defined(SHADOWS_SHADOWMASK) && defined(LIGHTMAP_ON)
half4 shadowMask = inputData.shadowMask;
#elif !defined (LIGHTMAP_ON)
half4 shadowMask = unity_ProbesOcclusion;
#else
half4 shadowMask = half4(1, 1, 1, 1);
#endif
Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, shadowMask);
#if defined(_SCREEN_SPACE_OCCLUSION)
AmbientOcclusionFactor aoFactor = GetScreenSpaceAmbientOcclusion(inputData.normalizedScreenSpaceUV);
mainLight.color *= aoFactor.directAmbientOcclusion;
surfaceData.occlusion = min(surfaceData.occlusion, aoFactor.indirectAmbientOcclusion);
#endif
MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI);
half3 color = GlobalIllumination(brdfData, brdfDataClearCoat, surfaceData.clearCoatMask,
inputData.bakedGI, surfaceData.occlusion,
inputData.normalWS, inputData.viewDirectionWS);
color += LightingPhysicallyBased(brdfData, brdfDataClearCoat,
mainLight,
inputData.normalWS, inputData.viewDirectionWS,
surfaceData.clearCoatMask, specularHighlightsOff);
#ifdef _ADDITIONAL_LIGHTS
uint pixelLightCount = GetAdditionalLightsCount();
LIGHT_LOOP_BEGIN(pixelLightCount)
Light light = GetAdditionalLight(lightIndex, inputData.positionWS, shadowMask);
#if defined(_SCREEN_SPACE_OCCLUSION)
light.color *= aoFactor.directAmbientOcclusion;
#endif
color += LightingPhysicallyBased(brdfData, brdfDataClearCoat,
light,
inputData.normalWS, inputData.viewDirectionWS,
surfaceData.clearCoatMask, specularHighlightsOff);
LIGHT_LOOP_END
#endif
#ifdef _ADDITIONAL_LIGHTS_VERTEX
color += inputData.vertexLighting * brdfData.diffuse;
#endif
color += surfaceData.emission;
return half4(color, surfaceData.alpha);
}
half4 BuiltInFragmentPBR(InputData inputData, half3 albedo, half metallic, half3 specular,
half smoothness, half occlusion, half3 emission, half alpha)
{
SurfaceData s;
s.albedo = albedo;
s.metallic = metallic;
s.specular = specular;
s.smoothness = smoothness;
s.occlusion = occlusion;
s.emission = emission;
s.alpha = alpha;
s.clearCoatMask = 0.0;
s.clearCoatSmoothness = 1.0;
return BuiltInFragmentPBR(inputData, s);
}
half4 BuiltInFragmentBlinnPhong(InputData inputData, half3 diffuse, half4 specularGloss, half smoothness, half3 emission, half alpha)
{
// To ensure backward compatibility we have to avoid using shadowMask input, as it is not present in older shaders
#if defined(SHADOWS_SHADOWMASK) && defined(LIGHTMAP_ON)
half4 shadowMask = inputData.shadowMask;
#elif !defined (LIGHTMAP_ON)
half4 shadowMask = unity_ProbesOcclusion;
#else
half4 shadowMask = half4(1, 1, 1, 1);
#endif
Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, shadowMask);
#if defined(_SCREEN_SPACE_OCCLUSION)
AmbientOcclusionFactor aoFactor = GetScreenSpaceAmbientOcclusion(inputData.normalizedScreenSpaceUV);
mainLight.color *= aoFactor.directAmbientOcclusion;
inputData.bakedGI *= aoFactor.indirectAmbientOcclusion;
#endif
MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI);
half3 attenuatedLightColor = mainLight.color * (mainLight.distanceAttenuation * mainLight.shadowAttenuation);
half3 diffuseColor = inputData.bakedGI + LightingLambert(attenuatedLightColor, mainLight.direction, inputData.normalWS);
half3 specularColor = LightingSpecular(attenuatedLightColor, mainLight.direction, inputData.normalWS, inputData.viewDirectionWS, specularGloss, smoothness);
#ifdef _ADDITIONAL_LIGHTS
uint pixelLightCount = GetAdditionalLightsCount();
LIGHT_LOOP_BEGIN(pixelLightCount)
Light light = GetAdditionalLight(lightIndex, inputData.positionWS, shadowMask);
#if defined(_SCREEN_SPACE_OCCLUSION)
light.color *= aoFactor.directAmbientOcclusion;
#endif
half3 attenuatedLightColor = light.color * (light.distanceAttenuation * light.shadowAttenuation);
diffuseColor += LightingLambert(attenuatedLightColor, light.direction, inputData.normalWS);
specularColor += LightingSpecular(attenuatedLightColor, light.direction, inputData.normalWS, inputData.viewDirectionWS, specularGloss, smoothness);
LIGHT_LOOP_END
#endif
#ifdef _ADDITIONAL_LIGHTS_VERTEX
diffuseColor += inputData.vertexLighting;
#endif
half3 finalColor = diffuseColor * diffuse + emission;
#if defined(_SPECGLOSSMAP) || defined(_SPECULAR_COLOR)
finalColor += specularColor;
#endif
return half4(finalColor, alpha);
}
//LWRP -> BuiltIn Backwards Compatibility
half4 LightweightFragmentPBR(InputData inputData, half3 albedo, half metallic, half3 specular,
half smoothness, half occlusion, half3 emission, half alpha)
{
return BuiltInFragmentPBR(inputData, albedo, metallic, specular, smoothness, occlusion, emission, alpha);
}
half4 LightweightFragmentBlinnPhong(InputData inputData, half3 diffuse, half4 specularGloss, half smoothness, half3 emission, half alpha)
{
return BuiltInFragmentBlinnPhong(inputData, diffuse, specularGloss, smoothness, emission, alpha);
}
#endif

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 14bcae32932007341a82b552c24738fd
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,70 @@
#ifndef BUILTIN_META_PASS_INCLUDED
#define BUILTIN_META_PASS_INCLUDED
#include "Packages/com.unity.shadergraph/Editor/Generation/Targets/BuiltIn/ShaderLibrary/Lighting.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
CBUFFER_START(UnityMetaPass)
// x = use uv1 as raster position
// y = use uv2 as raster position
bool4 unity_MetaVertexControl;
// x = return albedo
// y = return normal
bool4 unity_MetaFragmentControl;
CBUFFER_END
float unity_OneOverOutputBoost;
float unity_MaxOutputValue;
float unity_UseLinearSpace;
struct MetaInput
{
half3 Albedo;
half3 Emission;
half3 SpecularColor;
};
float4 MetaVertexPosition(float4 positionOS, float2 uv1, float2 uv2, float4 uv1ST, float4 uv2ST)
{
if (unity_MetaVertexControl.x)
{
positionOS.xy = uv1 * uv1ST.xy + uv1ST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
positionOS.z = positionOS.z > 0 ? REAL_MIN : 0.0f;
}
if (unity_MetaVertexControl.y)
{
positionOS.xy = uv2 * uv2ST.xy + uv2ST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
positionOS.z = positionOS.z > 0 ? REAL_MIN : 0.0f;
}
return TransformWorldToHClip(positionOS.xyz);
}
half4 MetaFragment(MetaInput input)
{
half4 res = 0;
if (unity_MetaFragmentControl.x)
{
res = half4(input.Albedo, 1.0);
// Apply Albedo Boost from LightmapSettings.
res.rgb = clamp(PositivePow(res.rgb, saturate(unity_OneOverOutputBoost)), 0, unity_MaxOutputValue);
}
if (unity_MetaFragmentControl.y)
{
half3 emission;
if (unity_UseLinearSpace)
emission = input.Emission;
else
emission = LinearToSRGB(input.Emission);
res = half4(emission, 1.0);
}
return res;
}
#endif

Some files were not shown because too many files have changed in this diff Show More