Initial project commit

This commit is contained in:
2026-01-08 16:50:20 +00:00
commit f0c5a8b267
29596 changed files with 4861782 additions and 0 deletions

View File

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

View File

@@ -0,0 +1,27 @@
using System;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
using UnityEditor.Rendering.Fullscreen.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
static class CreateCanvasShaderGraph
{
[MenuItem("Assets/Create/Shader Graph/URP/Canvas Shader Graph", priority = CoreUtils.Sections.section5 + CoreUtils.Priorities.assetsCreateShaderMenuPriority)]
public static void CreateCanvasGraph()
{
var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget));
target.TrySetActiveSubTarget(typeof(UniversalCanvasSubTarget));
var blockDescriptors = new[]
{
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.Emission,
BlockFields.SurfaceDescription.Alpha,
BlockFields.SurfaceDescription.AlphaClipThreshold,
};
GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors);
}
}
}

View File

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

View File

@@ -0,0 +1,25 @@
using System;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
using UnityEditor.Rendering.Fullscreen.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
static class CreateFullscreenShaderGraph
{
[MenuItem("Assets/Create/Shader Graph/URP/Fullscreen Shader Graph", priority = CoreUtils.Sections.section5 + CoreUtils.Priorities.assetsCreateShaderMenuPriority)]
public static void CreateFullscreenGraph()
{
var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget));
target.TrySetActiveSubTarget(typeof(UniversalFullscreenSubTarget));
var blockDescriptors = new[]
{
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.Alpha,
};
GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors);
}
}
}

View File

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

View File

@@ -0,0 +1,31 @@
using System;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
static class CreateLitShaderGraph
{
[MenuItem("Assets/Create/Shader Graph/URP/Lit Shader Graph", priority = CoreUtils.Priorities.assetsCreateShaderMenuPriority)]
public static void CreateLitGraph()
{
var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget));
target.TrySetActiveSubTarget(typeof(UniversalLitSubTarget));
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: aab9add076be9364aaee067b3c0e3910
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,32 @@
using System;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
internal static class CreateSixWayShaderGraph
{
[MenuItem("Assets/Create/Shader Graph/URP/Six Way Shader Graph", priority = CoreUtils.Sections.section6 + CoreUtils.Priorities.assetsCreateShaderMenuPriority)]
public static void CreateLitGraph()
{
var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget));
target.TrySetActiveSubTarget(typeof(UniversalSixWaySubTarget));
var blockDescriptors = new[]
{
BlockFields.VertexDescription.Position,
BlockFields.VertexDescription.Normal,
BlockFields.VertexDescription.Tangent,
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.MapRightTopBack,
BlockFields.SurfaceDescription.MapLeftBottomFront,
BlockFields.SurfaceDescription.AbsorptionStrength,
BlockFields.SurfaceDescription.Emission,
BlockFields.SurfaceDescription.Occlusion,
BlockFields.SurfaceDescription.Alpha,
};
GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: edb0ac362a4849488bbf53e05e67bb8a
timeCreated: 1684766616

View File

@@ -0,0 +1,26 @@
using System;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
static class CreateUnlitShaderGraph
{
[MenuItem("Assets/Create/Shader Graph/URP/Unlit Shader Graph", priority = CoreUtils.Priorities.assetsCreateShaderMenuPriority + 1)]
public static void CreateUnlitGraph()
{
var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget));
target.TrySetActiveSubTarget(typeof(UniversalUnlitSubTarget));
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: 6120e053fa5537949a54c661e2a57a39
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@@ -0,0 +1,150 @@
#if SHADERPASS != SHADERPASS_CUSTOM_UI
#error SHADERPASS_CUSTOM_UI_is_not_correctly_defined
#endif
// Get Homogeneous normalized device coordinates
float4 GetVertexPositionNDC(float3 positionCS)
{
float3 ndc = positionCS * 0.5f;
float4 positionNDC;
positionNDC.xy = float2(ndc.x, ndc.y * _ProjectionParams.x);// + ndc.w;
positionNDC.zw = float2(positionCS.z, 1.0);
return positionNDC;
}
// Transforms position from object space to homogenous space
float4 TransformModelToHClip(float3 positionOS)
{
return mul(unity_MatrixVP, mul(unity_ObjectToWorld, float4(positionOS, 1.0)));
}
Varyings BuildVaryings(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
// Returns the camera relative position (if enabled)
float3 positionWS = TransformObjectToWorld(input.positionOS);
output.positionCS = TransformWorldToHClip(positionWS);
#if UNITY_UV_STARTS_AT_TOP
//When UI is set to render in Overlay it writes to GFXdevice
//the same as if it was writing to a full screen back buffer
//Work around to catch Matrices not supplied by Camera,
//So Clipspace is recalculated, using raw unity_ObjectToWorld & unity_MatrixVP
output.positionCS = TransformModelToHClip(input.positionOS);
output.texCoord0.y = 1.0 - output.texCoord0.y;
#endif
#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
#if defined(VARYINGS_NEED_TEXCOORD0) || defined(VARYINGS_DS_NEED_TEXCOORD0)
output.texCoord0 = input.uv0;
#endif
//UI "Mask"
#if defined(VARYINGS_NEED_TEXCOORD1) || defined(VARYINGS_DS_NEED_TEXCOORD1)
#ifdef UNITY_UI_CLIP_RECT
float2 pixelSize = output.positionCS.w;
pixelSize /= float2(1, 1) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy));
float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
float2 maskUV = (input.positionOS.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy);
output.texCoord1 = float4(input.positionOS.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * half2(_UIMaskSoftnessX, _UIMaskSoftnessY) + abs(pixelSize.xy)));
#endif
#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 = GetVertexPositionNDC(output.positionCS); // vertexInput.positionNDC;
#endif
return output;
}
PackedVaryings vert(Attributes input)
{
Varyings 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);
//Round up the alpha color coming from the interpolator (to 1.0/256.0 steps)
//The incoming alpha could have numerical instability, which makes it very sensible to
//HDR color transparency blend, when it blends with the world's texture.
const half alphaPrecision = half(0xff);
const half invAlphaPrecision = half(1.0/alphaPrecision);
unpacked.color.a = round(unpacked.color.a * alphaPrecision)*invAlphaPrecision;
half alpha = surfaceDescription.Alpha;
half4 color = half4(surfaceDescription.BaseColor + surfaceDescription.Emission, alpha) ;
#if !defined(HAVE_VFX_MODIFICATION) && !defined(_DISABLE_COLOR_TINT)
color *= unpacked.color;
#endif
#ifdef UNITY_UI_CLIP_RECT
//mask = Uv2
half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(unpacked.texCoord1.xy)) * unpacked.texCoord1.zw);
color.a *= m.x * m.y;
#endif
#if _ALPHATEST_ON
clip(alpha - surfaceDescription.AlphaClipThreshold);
#endif
color.rgb *= color.a;
return color;
}

View File

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

View File

@@ -0,0 +1,28 @@
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.Universal
{
/// <summary>
/// Options for mesh bias type.
/// The Mesh bias lets you prevent z-fighting between the Decal GameObject and the GameObject it overlaps.
/// This property is only applicable for GameObjects with a Decal Material type assigned directly.
/// </summary>
[GenerateHLSL]
public enum DecalMeshDepthBiasType
{
/// <summary>
/// When drawing the decal gameObject, Unity changes the depth value of each pixel of the GameObject by this value.
/// A negative value shifts pixels closer to the Camera, so that Unity draws the Decal GameObject on top of the overlapping Mesh, which prevents z-fighting.
/// Decal projectors ignore this property.
/// </summary>
DepthBias = 0,
/// <summary>
/// A world-space bias (in meters).
/// When drawing the Decal GameObject, Unity shifts each pixel of the GameObject by this value along the view vector.
/// A positive value shifts pixels closer to the Camera, so that Unity draws the decal GameObject on top of the overlapping mesh, which prevents z-fighting.
/// Decal projectors ignore this property.
/// </summary>
ViewBias = 1
}
}

View File

@@ -0,0 +1,14 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef DECALMESHBIASTYPEENUM_CS_HLSL
#define DECALMESHBIASTYPEENUM_CS_HLSL
//
// UnityEditor.Rendering.Universal.DecalMeshDepthBiasType: static fields
//
#define DECALMESHDEPTHBIASTYPE_DEPTH_BIAS (0)
#define DECALMESHDEPTHBIASTYPE_VIEW_BIAS (1)
#endif

View File

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

View File

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

View File

@@ -0,0 +1,65 @@
#ifndef SG_DEPTH_NORMALS_PASS_INCLUDED
#define SG_DEPTH_NORMALS_PASS_INCLUDED
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
void frag(
PackedVaryings packedInput
, out half4 outNormalWS : SV_Target0
#ifdef _WRITE_RENDERING_LAYERS
, out uint outRenderingLayers : SV_Target1
#endif
)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if defined(_ALPHATEST_ON)
clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
#if defined(_GBUFFER_NORMALS_OCT)
float3 normalWS = normalize(unpacked.normalWS);
float2 octNormalWS = PackNormalOctQuadEncode(normalWS); // values between [-1, +1], must use fp32 on some platforms
float2 remappedOctNormalWS = saturate(octNormalWS * 0.5 + 0.5); // values between [ 0, 1]
half3 packedNormalWS = PackFloat2To888(remappedOctNormalWS); // values between [ 0, 1]
outNormalWS = half4(packedNormalWS, 0.0);
#else
// Retrieve the normal from the bump map or mesh normal
#if defined(_NORMALMAP)
#if _NORMAL_DROPOFF_TS
// IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped.
float crossSign = (unpacked.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale();
float3 bitangent = crossSign * cross(unpacked.normalWS.xyz, unpacked.tangentWS.xyz);
float3 normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, half3x3(unpacked.tangentWS.xyz, bitangent, unpacked.normalWS.xyz));
#elif _NORMAL_DROPOFF_OS
float3 normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS);
#elif _NORMAL_DROPOFF_WS
float3 normalWS = surfaceDescription.NormalWS;
#endif
#else
float3 normalWS = unpacked.normalWS;
#endif
outNormalWS = half4(NormalizeNormalPerPixel(normalWS), 0.0);
#endif
#ifdef _WRITE_RENDERING_LAYERS
outRenderingLayers = EncodeMeshRenderingLayer();
#endif
}
#endif

View File

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

View File

@@ -0,0 +1,31 @@
#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);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if defined(_ALPHATEST_ON)
clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
return packedInput.positionCS.z;
}
#endif

View File

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

View File

@@ -0,0 +1,34 @@
#ifndef SG_LIT_META_INCLUDED
#define SG_LIT_META_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);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if _ALPHATEST_ON
clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold);
#endif
MetaInput metaInput = (MetaInput)0;
metaInput.Albedo = surfaceDescription.BaseColor;
metaInput.Emission = surfaceDescription.Emission;
#ifdef EDITOR_VISUALIZATION
metaInput.VizUV = unpacked.texCoord1.xy;
metaInput.LightCoord = unpacked.texCoord2;
#endif
return UnityMetaFragment(metaInput);
}
#endif

View File

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

View File

@@ -0,0 +1,180 @@
#ifndef SG_MOTION_VECTORS_PASS_INCLUDED
#define SG_MOTION_VECTORS_PASS_INCLUDED
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/MotionVectorsCommon.hlsl"
struct MotionVectorPassAttributes
{
float3 previousPositionOS : TEXCOORD4; // Contains previous frame local vertex position (for skinned meshes)
#if defined (_ADD_PRECOMPUTED_VELOCITY)
float3 alembicMotionVectorOS : TEXCOORD5; // Alembic precomputed object space motion vector (offset from last frame's position)
#endif
};
// Note: these will have z == 0.0f in the pixel shader to save on bandwidth
struct MotionVectorPassVaryings
{
float4 positionCSNoJitter;
float4 previousPositionCSNoJitter;
};
struct PackedMotionVectorPassVaryings
{
float3 positionCSNoJitter : CLIP_POSITION_NO_JITTER;
float3 previousPositionCSNoJitter : PREVIOUS_CLIP_POSITION_NO_JITTER;
};
PackedMotionVectorPassVaryings PackMotionVectorVaryings(MotionVectorPassVaryings regularVaryings)
{
PackedMotionVectorPassVaryings packedVaryings;
packedVaryings.positionCSNoJitter = regularVaryings.positionCSNoJitter.xyw;
packedVaryings.previousPositionCSNoJitter = regularVaryings.previousPositionCSNoJitter.xyw;
return packedVaryings;
}
MotionVectorPassVaryings UnpackMotionVectorVaryings(PackedMotionVectorPassVaryings packedVaryings)
{
MotionVectorPassVaryings regularVaryings;
regularVaryings.positionCSNoJitter = float4(packedVaryings.positionCSNoJitter.xy, 0, packedVaryings.positionCSNoJitter.z);
regularVaryings.previousPositionCSNoJitter = float4(packedVaryings.previousPositionCSNoJitter.xy, 0, packedVaryings.previousPositionCSNoJitter.z);
return regularVaryings;
}
float3 GetLastFrameDeformedPosition(Attributes input, MotionVectorPassOutput currentFrameMvData, float3 previousPositionOS)
{
Attributes lastFrameInputAttributes = input;
lastFrameInputAttributes.positionOS = previousPositionOS;
VertexDescriptionInputs lastFrameVertexDescriptionInputs = BuildVertexDescriptionInputs(lastFrameInputAttributes);
#if defined(AUTOMATIC_TIME_BASED_MOTION_VECTORS) && defined(GRAPH_VERTEX_USES_TIME_PARAMETERS_INPUT)
lastFrameVertexDescriptionInputs.TimeParameters = _LastTimeParameters.xyz;
#endif
VertexDescription lastFrameVertexDescription = VertexDescriptionFunction(lastFrameVertexDescriptionInputs
#if defined(HAVE_VFX_MODIFICATION)
, currentFrameMvData.vfxGraphProperties
#endif
);
#if defined(HAVE_VFX_MODIFICATION)
lastFrameInputAttributes.positionOS = lastFrameVertexDescription.Position.xyz;
lastFrameInputAttributes = VFXTransformMeshToPreviousElement(lastFrameInputAttributes, currentFrameMvData.vfxElementAttributes);
previousPositionOS = lastFrameInputAttributes.positionOS;
#else
previousPositionOS = lastFrameVertexDescription.Position.xyz;
#endif
return previousPositionOS;
}
// -------------------------------------
// Vertex
void vert(
Attributes input,
MotionVectorPassAttributes passInput,
out PackedMotionVectorPassVaryings packedMvOutput,
out PackedVaryings packedOutput)
{
Varyings output = (Varyings)0;
MotionVectorPassVaryings mvOutput = (MotionVectorPassVaryings)0;
MotionVectorPassOutput currentFrameMvData = (MotionVectorPassOutput)0;
output = BuildVaryings(input, currentFrameMvData);
packedOutput = PackVaryings(output);
#if defined(HAVE_VFX_MODIFICATION) && !VFX_FEATURE_MOTION_VECTORS
//Motion vector is enabled in SG but not active in VFX
const bool forceNoMotion = true;
#else
const bool forceNoMotion = unity_MotionVectorsParams.y == 0.0;
#endif
if (!forceNoMotion)
{
#if defined(HAVE_VFX_MODIFICATION)
float3 previousPositionOS = currentFrameMvData.vfxParticlePositionOS;
#if defined(VFX_FEATURE_MOTION_VECTORS_VERTS)
const bool applyDeformation = false;
#else
const bool applyDeformation = true;
#endif
#else
const bool hasDeformation = unity_MotionVectorsParams.x == 1; // Mesh has skinned deformation
float3 previousPositionOS = hasDeformation ? passInput.previousPositionOS : input.positionOS;
#if defined(AUTOMATIC_TIME_BASED_MOTION_VECTORS) && defined(GRAPH_VERTEX_USES_TIME_PARAMETERS_INPUT)
const bool applyDeformation = true;
#else
const bool applyDeformation = hasDeformation;
#endif
#endif
#if defined(FEATURES_GRAPH_VERTEX)
if (applyDeformation)
previousPositionOS = GetLastFrameDeformedPosition(input, currentFrameMvData, previousPositionOS);
else
previousPositionOS = currentFrameMvData.positionOS;
#if defined(FEATURES_GRAPH_VERTEX_MOTION_VECTOR_OUTPUT)
previousPositionOS -= currentFrameMvData.motionVector;
#endif
#endif
#if defined(UNITY_DOTS_INSTANCING_ENABLED) && defined(DOTS_DEFORMED)
// Deformed vertices in DOTS are not cumulative with built-in Unity skinning/blend shapes
// Needs to be called after vertex modification has been applied otherwise it will be
// overwritten by Compute Deform node
ApplyPreviousFrameDeformedVertexPosition(input.vertexID, previousPositionOS);
#endif
#if defined (_ADD_PRECOMPUTED_VELOCITY)
previousPositionOS -= passInput.alembicMotionVectorOS;
#endif
mvOutput.positionCSNoJitter = mul(_NonJitteredViewProjMatrix, float4(currentFrameMvData.positionWS, 1.0f));
#if defined(HAVE_VFX_MODIFICATION)
#if defined(VFX_FEATURE_MOTION_VECTORS_VERTS)
#if defined(FEATURES_GRAPH_VERTEX_MOTION_VECTOR_OUTPUT) || defined(_ADD_PRECOMPUTED_VELOCITY)
#error Unexpected fast path rendering VFX motion vector while there are vertex modification afterwards.
#endif
mvOutput.previousPositionCSNoJitter = VFXGetPreviousClipPosition(input, currentFrameMvData.vfxElementAttributes, mvOutput.positionCSNoJitter);
#else
#if VFX_WORLD_SPACE
//previousPositionOS is already in world space
const float3 previousPositionWS = previousPositionOS;
#else
const float3 previousPositionWS = mul(UNITY_PREV_MATRIX_M, float4(previousPositionOS, 1.0f)).xyz;
#endif
mvOutput.previousPositionCSNoJitter = mul(_PrevViewProjMatrix, float4(previousPositionWS, 1.0f));
#endif
#else
mvOutput.previousPositionCSNoJitter = mul(_PrevViewProjMatrix, mul(UNITY_PREV_MATRIX_M, float4(previousPositionOS, 1.0f)));
#endif
}
packedMvOutput = PackMotionVectorVaryings(mvOutput);
}
// -------------------------------------
// Fragment
float4 frag(
// Note: packedMvInput needs to be before packedInput as otherwise we get the following error in the speed tree 8 SG:
// "Non system-generated input signature parameter () cannot appear after a system generated value"
PackedMotionVectorPassVaryings packedMvInput,
PackedVaryings packedInput) : SV_Target
{
Varyings input = UnpackVaryings(packedInput);
MotionVectorPassVaryings mvInput = UnpackMotionVectorVaryings(packedMvInput);
UNITY_SETUP_INSTANCE_ID(input);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(input);
#if defined(_ALPHATEST_ON)
clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(input.positionCS);
#endif
return float4(CalcNdcMotionVectorFromCsPositions(mvInput.positionCSNoJitter, mvInput.previousPositionCSNoJitter), 0, 0);
}
#endif

View File

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

View File

@@ -0,0 +1,28 @@
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);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if _ALPHATEST_ON
half alpha = surfaceDescription.Alpha;
clip(alpha - surfaceDescription.AlphaClipThreshold);
#elif _SURFACE_TYPE_TRANSPARENT
half alpha = surfaceDescription.Alpha;
#else
half alpha = 1;
#endif
half4 color = half4(surfaceDescription.BaseColor, alpha);
return color;
}

View File

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

View File

@@ -0,0 +1,173 @@
void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = input.positionWS;
#ifdef _NORMALMAP
// 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.tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz);
#if _NORMAL_DROPOFF_TS
inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, inputData.tangentToWorld);
#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 = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
#if defined(DEBUG_DISPLAY)
#if defined(DYNAMICLIGHTMAP_ON)
inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy;
#endif
#if defined(LIGHTMAP_ON)
inputData.staticLightmapUV = input.staticLightmapUV;
#else
inputData.vertexSH = input.sh;
#endif
#if defined(USE_APV_PROBE_OCCLUSION)
inputData.probeOcclusion = input.probeOcclusion;
#endif
inputData.positionCS = input.positionCS;
#endif
}
void InitializeBakedGIData(Varyings input, inout InputData inputData)
{
#if defined(DYNAMICLIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, input.sh, inputData.normalWS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#elif !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2))
inputData.bakedGI = SAMPLE_GI(input.sh,
GetAbsolutePositionWS(inputData.positionWS),
inputData.normalWS,
inputData.viewDirectionWS,
input.positionCS.xy,
input.probeOcclusion,
inputData.shadowMask);
#else
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.sh, inputData.normalWS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#endif
}
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
void frag(
PackedVaryings packedInput
, out half4 outColor : SV_Target0
#ifdef _WRITE_RENDERING_LAYERS
, out uint outRenderingLayers : SV_Target1
#endif
)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if defined(_SURFACE_TYPE_TRANSPARENT)
bool isTransparent = true;
#else
bool isTransparent = false;
#endif
#if defined(_ALPHATEST_ON)
half alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
#elif defined(_SURFACE_TYPE_TRANSPARENT)
half alpha = surfaceDescription.Alpha;
#else
half alpha = half(1.0);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
InputData inputData;
InitializeInputData(unpacked, surfaceDescription, inputData);
#ifdef VARYINGS_NEED_TEXCOORD0
SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0);
#else
SETUP_DEBUG_TEXTURE_DATA_NO_UV(inputData);
#endif
#ifdef _SPECULAR_SETUP
float3 specular = surfaceDescription.Specular;
float metallic = 1;
#else
float3 specular = 0;
float metallic = surfaceDescription.Metallic;
#endif
half3 normalTS = half3(0, 0, 0);
#if defined(_NORMALMAP) && defined(_NORMAL_DROPOFF_TS)
normalTS = surfaceDescription.NormalTS;
#endif
SurfaceData surface;
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.normalTS = normalTS;
surface.clearCoatMask = 0;
surface.clearCoatSmoothness = 1;
#ifdef _CLEARCOAT
surface.clearCoatMask = saturate(surfaceDescription.CoatMask);
surface.clearCoatSmoothness = saturate(surfaceDescription.CoatSmoothness);
#endif
surface.albedo = AlphaModulate(surface.albedo, surface.alpha);
#if defined(_DBUFFER)
ApplyDecalToSurfaceData(unpacked.positionCS, surface, inputData);
#endif
InitializeBakedGIData(unpacked, inputData);
half4 color = UniversalFragmentPBR(inputData, surface);
color.rgb = MixFog(color.rgb, inputData.fogCoord);
color.a = OutputAlpha(color.a, isTransparent);
outColor = color;
#ifdef _WRITE_RENDERING_LAYERS
outRenderingLayers = EncodeMeshRenderingLayer();
#endif
}

View File

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

View File

@@ -0,0 +1,140 @@
void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = input.positionWS;
inputData.positionCS = input.positionCS;
#ifdef _NORMALMAP
// 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.tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz);
#if _NORMAL_DROPOFF_TS
inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, inputData.tangentToWorld);
#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 = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
#if defined(DEBUG_DISPLAY)
#if defined(DYNAMICLIGHTMAP_ON)
inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy;
#endif
#if defined(LIGHTMAP_ON)
inputData.staticLightmapUV = input.staticLightmapUV;
#else
inputData.vertexSH = input.sh;
#endif
#if defined(USE_APV_PROBE_OCCLUSION)
inputData.probeOcclusion = input.probeOcclusion;
#endif
#endif
}
void InitializeBakedGIData(Varyings input, inout InputData inputData)
{
#if defined(DYNAMICLIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, input.sh, inputData.normalWS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#elif !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2))
inputData.bakedGI = SAMPLE_GI(input.sh,
GetAbsolutePositionWS(inputData.positionWS),
inputData.normalWS,
inputData.viewDirectionWS,
inputData.positionCS.xy,
input.probeOcclusion,
inputData.shadowMask);
#else
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.sh, inputData.normalWS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#endif
}
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
GBufferFragOutput frag(PackedVaryings packedInput)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if defined(_ALPHATEST_ON)
half alpha = surfaceDescription.Alpha;
clip(alpha - surfaceDescription.AlphaClipThreshold);
#elif _SURFACE_TYPE_TRANSPARENT
half alpha = surfaceDescription.Alpha;
#else
half alpha = 1;
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
InputData inputData;
InitializeInputData(unpacked, surfaceDescription, inputData);
#ifdef VARYINGS_NEED_TEXCOORD0
SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0);
#else
SETUP_DEBUG_TEXTURE_DATA_NO_UV(inputData);
#endif
#ifdef _SPECULAR_SETUP
float3 specular = surfaceDescription.Specular;
float metallic = 1;
#else
float3 specular = 0;
float metallic = surfaceDescription.Metallic;
#endif
#if defined(_DBUFFER)
ApplyDecal(unpacked.positionCS,
surfaceDescription.BaseColor,
specular,
inputData.normalWS,
metallic,
surfaceDescription.Occlusion,
surfaceDescription.Smoothness);
#endif
InitializeBakedGIData(unpacked, inputData);
// in LitForwardPass GlobalIllumination (and temporarily LightingPhysicallyBased) are called inside UniversalFragmentPBR
// 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.positionWS, inputData.normalWS, inputData.viewDirectionWS);
return PackGBuffersBRDFData(brdfData, inputData, surfaceDescription.Smoothness, surfaceDescription.Emission + color, surfaceDescription.Occlusion);
}

View File

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

View File

@@ -0,0 +1,40 @@
#ifndef SG_SELECTION_PICKING_PASS_INCLUDED
#define SG_SELECTION_PICKING_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);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if _ALPHATEST_ON
// This isn't defined in the sprite passes. It looks like the built-in legacy shader will use this as it's default constant
float alphaClipThreshold = 0.01f;
#if ALPHA_CLIP_THRESHOLD
alphaClipThreshold = surfaceDescription.AlphaClipThreshold;
#endif
clip(surfaceDescription.Alpha - alphaClipThreshold);
#endif
half4 outColor = 0;
#ifdef SCENESELECTIONPASS
// We use depth prepass for scene selection in the editor, this code allow to output the outline correctly
outColor = half4(_ObjectId, _PassValue, 1.0, 1.0);
#elif defined(SCENEPICKINGPASS)
outColor = unity_SelectionID;
#endif
return outColor;
}
#endif

View File

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

View File

@@ -0,0 +1,28 @@
#ifndef UNIVERSAL_SHADERPASS_INCLUDED
#define UNIVERSAL_SHADERPASS_INCLUDED
#define SHADERPASS_FORWARD (0)
#define SHADERPASS_GBUFFER (1)
#define SHADERPASS_DEPTHONLY (2)
#define SHADERPASS_SHADOWCASTER (3)
#define SHADERPASS_META (4)
#define SHADERPASS_2D (5)
#define SHADERPASS_UNLIT (6)
#define SHADERPASS_SPRITELIT (7)
#define SHADERPASS_SPRITENORMAL (8)
#define SHADERPASS_SPRITEFORWARD (9)
#define SHADERPASS_SPRITEUNLIT (10)
#define SHADERPASS_DEPTHNORMALSONLY (11)
#define SHADERPASS_DBUFFER_PROJECTOR (12)
#define SHADERPASS_DBUFFER_MESH (13)
#define SHADERPASS_FORWARD_EMISSIVE_PROJECTOR (14)
#define SHADERPASS_FORWARD_EMISSIVE_MESH (15)
#define SHADERPASS_FORWARD_PREVIEW (16)
#define SHADERPASS_DECAL_SCREEN_SPACE_PROJECTOR (17)
#define SHADERPASS_DECAL_SCREEN_SPACE_MESH (18)
#define SHADERPASS_DECAL_GBUFFER_PROJECTOR (19)
#define SHADERPASS_DECAL_GBUFFER_MESH (20)
#define SHADERPASS_DEPTHNORMALS (21)
#define SHADERPASS_MOTION_VECTORS (22)
#define SHADERPASS_XR_MOTION_VECTORS (23)
#endif

View File

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

View File

@@ -0,0 +1,376 @@
#if (SHADERPASS != SHADERPASS_DEPTHONLY) && (SHADERPASS != SHADERPASS_DBUFFER_PROJECTOR) && (SHADERPASS != SHADERPASS_DBUFFER_MESH) && (SHADERPASS != SHADERPASS_FORWARD_EMISSIVE_PROJECTOR) && (SHADERPASS != SHADERPASS_FORWARD_EMISSIVE_MESH) && (SHADERPASS != SHADERPASS_DECAL_SCREEN_SPACE_PROJECTOR) && (SHADERPASS != SHADERPASS_DECAL_SCREEN_SPACE_MESH) && (SHADERPASS != SHADERPASS_DECAL_GBUFFER_PROJECTOR) && (SHADERPASS != SHADERPASS_DECAL_GBUFFER_MESH)
#error SHADERPASS_is_not_correctly_define
#endif
#if !defined(SHADERPASS)
#error SHADERPASS_is_not_define
#endif
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR) || (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_PROJECTOR) || (SHADERPASS == SHADERPASS_DECAL_SCREEN_SPACE_PROJECTOR) || (SHADERPASS == SHADERPASS_DECAL_GBUFFER_PROJECTOR)
#define DECAL_PROJECTOR
#endif
#if (SHADERPASS == SHADERPASS_DBUFFER_MESH) || (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_MESH) || (SHADERPASS == SHADERPASS_DECAL_SCREEN_SPACE_MESH) || (SHADERPASS == SHADERPASS_DECAL_GBUFFER_MESH)
#define DECAL_MESH
#endif
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR) || (SHADERPASS == SHADERPASS_DBUFFER_MESH)
#define DECAL_DBUFFER
#endif
#if (SHADERPASS == SHADERPASS_DECAL_SCREEN_SPACE_PROJECTOR) || (SHADERPASS == SHADERPASS_DECAL_SCREEN_SPACE_MESH)
#define DECAL_SCREEN_SPACE
#endif
#if (SHADERPASS == SHADERPASS_DECAL_GBUFFER_PROJECTOR) || (SHADERPASS == SHADERPASS_DECAL_GBUFFER_MESH)
#define DECAL_GBUFFER
#endif
#if (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_PROJECTOR) || (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_MESH)
#define DECAL_FORWARD_EMISSIVE
#endif
#if ((!defined(_MATERIAL_AFFECTS_NORMAL) && defined(_MATERIAL_AFFECTS_ALBEDO)) || (defined(_MATERIAL_AFFECTS_NORMAL) && defined(_MATERIAL_AFFECTS_NORMAL_BLEND))) && (defined(DECAL_SCREEN_SPACE) || defined(DECAL_GBUFFER))
#define DECAL_RECONSTRUCT_NORMAL
#elif defined(DECAL_ANGLE_FADE)
#define DECAL_LOAD_NORMAL
#endif
#ifdef _DECAL_LAYERS
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareRenderingLayerTexture.hlsl"
#endif
#if defined(DECAL_LOAD_NORMAL)
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareNormalsTexture.hlsl"
#endif
#if defined(DECAL_PROJECTOR) || defined(DECAL_RECONSTRUCT_NORMAL)
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"
#endif
#ifdef DECAL_MESH
#include "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DecalMeshBiasTypeEnum.cs.hlsl"
#endif
#ifdef DECAL_RECONSTRUCT_NORMAL
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/NormalReconstruction.hlsl"
#endif
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRendering.hlsl"
void MeshDecalsPositionZBias(inout Varyings input)
{
#if UNITY_REVERSED_Z
input.positionCS.z -= _DecalMeshDepthBias;
#else
input.positionCS.z += _DecalMeshDepthBias;
#endif
}
void InitializeInputData(Varyings input, float3 positionWS, half3 normalWS, half3 viewDirectionWS, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = positionWS;
inputData.normalWS = normalWS;
inputData.viewDirectionWS = viewDirectionWS;
#if defined(VARYINGS_NEED_SHADOW_COORD) && defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
inputData.shadowCoord = input.shadowCoord;
#elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
inputData.shadowCoord = TransformWorldToShadowCoord(positionWS);
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
#ifdef VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
inputData.fogCoord = InitializeInputDataFog(float4(positionWS, 1.0), input.fogFactorAndVertexLight.x);
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
#endif
#if defined(VARYINGS_NEED_DYNAMIC_LIGHTMAP_UV) && defined(DYNAMICLIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, half3(input.sh), normalWS);
#if defined(VARYINGS_NEED_STATIC_LIGHTMAP_UV)
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#endif
#elif defined(VARYINGS_NEED_STATIC_LIGHTMAP_UV)
#if !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2))
inputData.bakedGI = SAMPLE_GI(input.sh,
GetAbsolutePositionWS(inputData.positionWS),
inputData.normalWS,
inputData.viewDirectionWS,
input.positionCS.xy,
input.probeOcclusion,
inputData.shadowMask);
#else
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, half3(input.sh), normalWS);
#if defined(VARYINGS_NEED_STATIC_LIGHTMAP_UV)
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#endif
#endif
#endif
#if defined(DEBUG_DISPLAY)
#if defined(VARYINGS_NEED_DYNAMIC_LIGHTMAP_UV) && defined(DYNAMICLIGHTMAP_ON)
inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy;
#endif
#if defined(VARYINGS_NEED_STATIC_LIGHTMAP_UV) && defined(LIGHTMAP_ON)
inputData.staticLightmapUV = input.staticLightmapUV;
#elif defined(VARYINGS_NEED_SH)
inputData.vertexSH = input.sh;
#endif
#if defined(USE_APV_PROBE_OCCLUSION)
inputData.probeOcclusion = input.probeOcclusion;
#endif
#endif
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
}
void GetSurface(DecalSurfaceData decalSurfaceData, inout SurfaceData surfaceData)
{
surfaceData.albedo = decalSurfaceData.baseColor.rgb;
surfaceData.metallic = saturate(decalSurfaceData.metallic);
surfaceData.specular = 0;
surfaceData.smoothness = saturate(decalSurfaceData.smoothness);
surfaceData.occlusion = decalSurfaceData.occlusion;
surfaceData.emission = decalSurfaceData.emissive;
surfaceData.alpha = saturate(decalSurfaceData.baseColor.w);
surfaceData.clearCoatMask = 0;
surfaceData.clearCoatSmoothness = 1;
}
PackedVaryings Vert(Attributes inputMesh)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(inputMesh);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
#ifdef DECAL_MESH
if (_DecalMeshBiasType == DECALMESHDEPTHBIASTYPE_VIEW_BIAS) // TODO: Check performance of branch
{
float3 viewDirectionOS = GetObjectSpaceNormalizeViewDir(inputMesh.positionOS);
inputMesh.positionOS += viewDirectionOS * (_DecalMeshViewBias);
}
output = BuildVaryings(inputMesh);
if (_DecalMeshBiasType == DECALMESHDEPTHBIASTYPE_DEPTH_BIAS) // TODO: Check performance of branch
{
MeshDecalsPositionZBias(output);
}
#else
output = BuildVaryings(inputMesh);
#endif
#if defined(VARYINGS_NEED_STATIC_LIGHTMAP_UV)
OUTPUT_LIGHTMAP_UV(inputMesh.uv1, unity_LightmapST, output.staticLightmapUV);
#endif
#if defined(VARYINGS_NEED_DYNAMIC_LIGHTMAP_UV) && defined(DYNAMICLIGHTMAP_ON)
output.dynamicLightmapUV.xy = inputMesh.uv2.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
#endif
#if defined(VARYINGS_NEED_SH) && !defined(LIGHTMAP_ON)
output.sh = float3(SampleSHVertex(half3(output.normalWS)));
#endif
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
void Frag(PackedVaryings packedInput,
#if defined(DECAL_DBUFFER)
OUTPUT_DBUFFER(outDBuffer)
#elif defined(DECAL_SCREEN_SPACE)
out half4 outColor : SV_Target0
#elif defined(DECAL_GBUFFER)
out GBufferFragOutput fragmentOutput
#elif defined(DECAL_FORWARD_EMISSIVE)
out half4 outEmissive : SV_Target0
#elif defined(SCENEPICKINGPASS)
out float4 outColor : SV_Target0
#else
#error SHADERPASS_is_not_correctly_define
#endif
)
{
#ifdef SCENEPICKINGPASS
outColor = _SelectionID;
#else
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(packedInput);
UNITY_SETUP_INSTANCE_ID(packedInput);
Varyings input = UnpackVaryings(packedInput);
half angleFadeFactor = 1.0;
float2 positionCS = input.positionCS.xy;
// Only screen space needs flip logic, other passes do not setup needed properties so we skip here
#if defined(DECAL_SCREEN_SPACE)
TransformScreenUV(positionCS, _ScreenSize.y);
#endif
#ifdef _DECAL_LAYERS
#ifdef _RENDER_PASS_ENABLED
uint surfaceRenderingLayer = LOAD_FRAMEBUFFER_X_INPUT(GBUFFER4, positionCS.xy).r;
#else
uint surfaceRenderingLayer = LoadSceneRenderingLayer(positionCS.xy);
#endif
uint projectorRenderingLayer = uint(UNITY_ACCESS_INSTANCED_PROP(Decal, _DecalLayerMaskFromDecal));
// This is simple trick to clip if there is no matching layers
// Part (surfaceRenderingLayer & projectorRenderingLayer) will produce 0, 1, 2 ...
// Finally we subtract with small value to remmap only zero to negative value
clip((surfaceRenderingLayer & projectorRenderingLayer) - 0.1);
#endif
#if defined(DECAL_PROJECTOR)
#if UNITY_REVERSED_Z
#if _RENDER_PASS_ENABLED
float depth = LOAD_FRAMEBUFFER_X_INPUT(GBUFFER3, positionCS.xy).x;
#else
float depth = LoadSceneDepth(positionCS.xy);
#endif
#else
#if _RENDER_PASS_ENABLED
float depth = lerp(UNITY_NEAR_CLIP_VALUE, 1, LOAD_FRAMEBUFFER_X_INPUT(GBUFFER3, positionCS.xy));
#else
// Adjust z to match NDC for OpenGL
float depth = lerp(UNITY_NEAR_CLIP_VALUE, 1, LoadSceneDepth(positionCS.xy));
#endif
#endif
#endif
#if defined(DECAL_RECONSTRUCT_NORMAL)
#if defined(_DECAL_NORMAL_BLEND_HIGH)
half3 normalWS = half3(ReconstructNormalTap9(positionCS.xy));
#elif defined(_DECAL_NORMAL_BLEND_MEDIUM)
half3 normalWS = half3(ReconstructNormalTap5(positionCS.xy));
#else
half3 normalWS = half3(ReconstructNormalDerivative(input.positionCS.xy));
#endif
#elif defined(DECAL_LOAD_NORMAL)
half3 normalWS = half3(LoadSceneNormals(positionCS.xy));
#endif
float2 positionSS = FoveatedRemapNonUniformToLinearCS(input.positionCS.xy) * _ScreenSize.zw;
#ifdef DECAL_PROJECTOR
float3 positionWS = ComputeWorldSpacePosition(positionSS, depth, UNITY_MATRIX_I_VP);
#ifdef VARYINGS_NEED_POSITION_WS
input.positionWS = positionWS;
#endif
// Transform from relative world space to decal space (DS) to clip the decal
float3 positionDS = TransformWorldToObject(positionWS);
positionDS = positionDS * float3(1.0, -1.0, 1.0);
// call clip as early as possible
float clipValue = 0.5 - Max3(abs(positionDS).x, abs(positionDS).y, abs(positionDS).z);
clip(clipValue);
float2 texCoord = positionDS.xz + float2(0.5, 0.5);
#ifdef VARYINGS_NEED_TEXCOORD0
input.texCoord0.xy = texCoord;
#endif
#ifdef VARYINGS_NEED_TEXCOORD1
input.texCoord1.xy = texCoord;
#endif
#ifdef VARYINGS_NEED_TEXCOORD2
input.texCoord2.xy = texCoord;
#endif
#ifdef VARYINGS_NEED_TEXCOORD3
input.texCoord3.xy = texCoord;
#endif
#ifdef DECAL_ANGLE_FADE
// Check if this decal projector require angle fading
half4x4 normalToWorld = UNITY_ACCESS_INSTANCED_PROP(Decal, _NormalToWorld);
half2 angleFade = half2(normalToWorld[1][3], normalToWorld[2][3]);
if (angleFade.y < 0.0f) // if angle fade is enabled
{
half3 decalNormal = half3(normalToWorld[0].z, normalToWorld[1].z, normalToWorld[2].z);
half dotAngle = dot(normalWS, decalNormal);
// See equation in DecalCreateDrawCallSystem.cs - simplified to a madd mul add here
angleFadeFactor = saturate(angleFade.x + angleFade.y * (dotAngle * (dotAngle - 2.0)));
}
#endif
#else // Decal mesh
float3 positionWS = input.positionWS.xyz;
#endif
half3 viewDirectionWS = GetWorldSpaceNormalizeViewDir(positionWS);
DecalSurfaceData surfaceData;
GetSurfaceData(input, input.positionCS, angleFadeFactor, surfaceData);
#if defined(DECAL_DBUFFER)
ENCODE_INTO_DBUFFER(surfaceData, outDBuffer);
#elif defined(DECAL_SCREEN_SPACE)
// Blend normal with background
#ifdef DECAL_RECONSTRUCT_NORMAL
surfaceData.normalWS.xyz = normalize(lerp(normalWS.xyz, surfaceData.normalWS.xyz, surfaceData.normalWS.w));
#endif
InputData inputData;
InitializeInputData(input, positionWS, surfaceData.normalWS.xyz, viewDirectionWS, inputData);
SurfaceData surface = (SurfaceData)0;
GetSurface(surfaceData, surface);
half4 color = UniversalFragmentPBR(inputData, surface);
color.rgb = MixFog(color.rgb, inputData.fogCoord);
outColor = color;
#elif defined(DECAL_GBUFFER)
// Need to reconstruct normal here for inputData.bakedGI, but also save off surfaceData.normalWS for correct GBuffer blending
half3 normalToPack = surfaceData.normalWS.xyz;
#ifdef DECAL_RECONSTRUCT_NORMAL
surfaceData.normalWS.xyz = normalize(lerp(normalWS.xyz, surfaceData.normalWS.xyz, surfaceData.normalWS.w));
#endif
InputData inputData;
InitializeInputData(input, positionWS, surfaceData.normalWS.xyz, viewDirectionWS, inputData);
SurfaceData surface = (SurfaceData)0;
GetSurface(surfaceData, surface);
BRDFData brdfData;
InitializeBRDFData(surface.albedo, surface.metallic, 0, surface.smoothness, surface.alpha, brdfData);
// Skip GI if there is no abledo
#ifdef _MATERIAL_AFFECTS_ALBEDO
Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, inputData.shadowMask);
MixRealtimeAndBakedGI(mainLight, surfaceData.normalWS.xyz, inputData.bakedGI, inputData.shadowMask);
half3 color = GlobalIllumination(brdfData, inputData.bakedGI, surface.occlusion, surfaceData.normalWS.xyz, inputData.viewDirectionWS);
#else
half3 color = 0;
#endif
// We can not use usual GBuffer functions (etc. BRDFDataToGbuffer) as we use alpha for blending
#pragma warning (disable : 3578) // The output value isn't completely initialized.
half3 packedNormalWS = PackGBufferNormal(normalToPack);
fragmentOutput.gBuffer0 = half4(surfaceData.baseColor.rgb, surfaceData.baseColor.a);
fragmentOutput.gBuffer1 = 0;
fragmentOutput.gBuffer2 = half4(packedNormalWS, surfaceData.normalWS.a);
fragmentOutput.color = half4(surfaceData.emissive + color, surfaceData.baseColor.a);
#if defined(GBUFFER_FEATURE_SHADOWMASK)
fragmentOutput.shadowMask = inputData.shadowMask; // will have unity_ProbesOcclusion value if subtractive lighting is used (baked)
#endif
#pragma warning (default : 3578) // Restore output value isn't completely initialized.
#elif defined(DECAL_FORWARD_EMISSIVE)
// Emissive need to be pre-exposed
outEmissive.rgb = surfaceData.emissive * GetCurrentExposureMultiplier();
outEmissive.a = surfaceData.baseColor.a;
#else
#endif
#endif
}

View File

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

View File

@@ -0,0 +1,4 @@
UNITY_INSTANCING_BUFFER_START(Decal)
UNITY_DEFINE_INSTANCED_PROP(half4x4, _NormalToWorld)
UNITY_DEFINE_INSTANCED_PROP(float, _DecalLayerMaskFromDecal)
UNITY_INSTANCING_BUFFER_END(Decal)

View File

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

View File

@@ -0,0 +1,30 @@
#ifndef SG_SHADOW_PASS_INCLUDED
#define SG_SHADOW_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);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if defined(_ALPHATEST_ON)
clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
return 0;
}
#endif

View File

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

View File

@@ -0,0 +1,124 @@
void InitializeInputData(Varyings input, bool frontFace, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = input.positionWS;
float signNormal = frontFace ? 1.0f : -1.0f;
inputData.normalWS = signNormal * input.normalWS;
inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS);
float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale();
float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz);
inputData.tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, signNormal * input.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 = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#if defined(DEBUG_DISPLAY)
#if defined(DYNAMICLIGHTMAP_ON)
inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy;
#endif
#if defined(LIGHTMAP_ON)
inputData.staticLightmapUV = input.staticLightmapUV;
#else
inputData.vertexSH = input.sh;
#endif
#if defined(USE_APV_PROBE_OCCLUSION)
inputData.probeOcclusion = input.probeOcclusion;
#endif
inputData.positionCS = input.positionCS;
#endif
}
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = (PackedVaryings)0;
packedOutput = PackVaryings(output);
return packedOutput;
}
void frag(
PackedVaryings packedInput
, out half4 outColor : SV_Target0
, bool frontFace : FRONT_FACE_SEMANTIC
#ifdef _WRITE_RENDERING_LAYERS
, out uint outRenderingLayers : SV_Target1
#endif
)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if defined(_SURFACE_TYPE_TRANSPARENT)
bool isTransparent = true;
#else
bool isTransparent = false;
#endif
#if defined(_ALPHATEST_ON)
half alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
#elif defined(_SURFACE_TYPE_TRANSPARENT)
half alpha = surfaceDescription.Alpha;
#else
half alpha = half(1.0);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
InputData inputData;
InitializeInputData(unpacked, frontFace, inputData);
#ifdef VARYINGS_NEED_TEXCOORD0
SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0);
#else
SETUP_DEBUG_TEXTURE_DATA_NO_UV(inputData);
#endif
SixWaySurfaceData surfaceData;
surfaceData.rightTopBack = surfaceDescription.RightTopBack * INV_PI;
surfaceData.leftBottomFront = surfaceDescription.LeftBottomFront * INV_PI;
surfaceData.emission = surfaceDescription.Emission;
surfaceData.baseColor = surfaceDescription.BaseColor;
surfaceData.occlusion = surfaceDescription.Occlusion;
surfaceData.alpha = saturate(alpha);
surfaceData.diffuseGIData0 = unpacked.diffuseGIData0;
surfaceData.diffuseGIData1 = unpacked.diffuseGIData1;
surfaceData.diffuseGIData2 = unpacked.diffuseGIData2;
if(!frontFace)
surfaceData.diffuseGIData2.xyz *= -1.0f;
#if defined(_SIX_WAY_COLOR_ABSORPTION)
surfaceData.absorptionRange = INV_PI + saturate(surfaceDescription.AbsorptionStrength) * (1 - INV_PI);
#endif
half4 color = UniversalFragmentSixWay(inputData, surfaceData);
color.rgb = MixFog(color.rgb, inputData.fogCoord);
color.a = OutputAlpha(color.a, isTransparent);
outColor = color;
#ifdef _WRITE_RENDERING_LAYERS
outRenderingLayers = EncodeMeshRenderingLayer();
#endif
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ea5e0c2b753f4b5287a5a23f0e61407e
timeCreated: 1676462852

View File

@@ -0,0 +1,70 @@
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Unlit.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferOutput.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderVariablesFunctions.hlsl"
void InitializeInputData(Varyings input, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionCS = input.positionCS;
inputData.normalWS = normalize(input.normalWS);
inputData.positionWS = float3(0, 0, 0);
inputData.viewDirectionWS = half3(0, 0, 1);
inputData.shadowCoord = 0;
inputData.fogCoord = 0;
inputData.vertexLighting = half3(0, 0, 0);
inputData.bakedGI = half3(0, 0, 0);
inputData.normalizedScreenSpaceUV = 0;
inputData.shadowMask = half4(1, 1, 1, 1);
}
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = PackVaryings(output);
return packedOutput;
}
GBufferFragOutput frag(PackedVaryings packedInput)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
SurfaceData surfaceData = (SurfaceData)0;
surfaceData.alpha = 1;
#if defined(_ALPHATEST_ON)
surfaceData.alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
#if defined(_ALPHAMODULATE_ON)
surfaceData.albedo = AlphaModulate(surfaceDescription.BaseColor, surfaceData.alpha);
#else
surfaceData.albedo = surfaceDescription.BaseColor;
#endif
#if defined(_DBUFFER)
ApplyDecalToBaseColor(unpacked.positionCS, surfaceData.albedo);
#endif
InputData inputData;
InitializeInputData(unpacked, inputData);
#if defined(_SCREEN_SPACE_OCCLUSION) && !defined(_SURFACE_TYPE_TRANSPARENT)
float2 normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(unpacked.positionCS);
AmbientOcclusionFactor aoFactor = GetScreenSpaceAmbientOcclusion(normalizedScreenSpaceUV);
surfaceData.albedo.rgb *= aoFactor.directAmbientOcclusion;
#else
surfaceData.occlusion = 1;
#endif
return PackGBuffersSurfaceData(surfaceData, inputData, float3(0,0,0));
}

View File

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

View File

@@ -0,0 +1,95 @@
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Unlit.hlsl"
void InitializeInputData(Varyings input, out InputData inputData)
{
inputData = (InputData)0;
// InputData is only used for DebugDisplay purposes in Unlit, so these are not initialized.
#if defined(DEBUG_DISPLAY)
inputData.positionWS = input.positionWS;
inputData.positionCS = input.positionCS;
inputData.normalWS = input.normalWS;
#else
inputData.positionWS = half3(0, 0, 0);
inputData.normalWS = half3(0, 0, 1);
inputData.viewDirectionWS = half3(0, 0, 1);
#endif
inputData.shadowCoord = 0;
inputData.fogCoord = 0;
inputData.vertexLighting = half3(0, 0, 0);
inputData.bakedGI = half3(0, 0, 0);
inputData.normalizedScreenSpaceUV = 0;
inputData.shadowMask = half4(1, 1, 1, 1);
}
PackedVaryings vert(Attributes input)
{
Varyings output = (Varyings)0;
output = BuildVaryings(input);
PackedVaryings packedOutput = PackVaryings(output);
return packedOutput;
}
void frag(
PackedVaryings packedInput
, out half4 outColor : SV_Target0
#ifdef _WRITE_RENDERING_LAYERS
, out uint outRenderingLayers : SV_Target1
#endif
)
{
Varyings unpacked = UnpackVaryings(packedInput);
UNITY_SETUP_INSTANCE_ID(unpacked);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
#if defined(_SURFACE_TYPE_TRANSPARENT)
bool isTransparent = true;
#else
bool isTransparent = false;
#endif
#if defined(_ALPHATEST_ON)
half alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
#elif defined(_SURFACE_TYPE_TRANSPARENT)
half alpha = surfaceDescription.Alpha;
#else
half alpha = half(1.0);
#endif
#if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE
LODFadeCrossFade(unpacked.positionCS);
#endif
#if defined(_ALPHAMODULATE_ON)
surfaceDescription.BaseColor = AlphaModulate(surfaceDescription.BaseColor, alpha);
#endif
#if defined(_DBUFFER)
ApplyDecalToBaseColor(unpacked.positionCS, surfaceDescription.BaseColor);
#endif
InputData inputData;
InitializeInputData(unpacked, inputData);
#ifdef VARYINGS_NEED_TEXCOORD0
SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0);
#else
SETUP_DEBUG_TEXTURE_DATA_NO_UV(inputData);
#endif
half4 finalColor = UniversalFragmentUnlit(inputData, surfaceDescription.BaseColor, alpha);
finalColor.a = OutputAlpha(finalColor.a, isTransparent);
#if defined(_SCREEN_SPACE_OCCLUSION) && !defined(_SURFACE_TYPE_TRANSPARENT)
float2 normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(unpacked.positionCS);
AmbientOcclusionFactor aoFactor = GetScreenSpaceAmbientOcclusion(normalizedScreenSpaceUV);
finalColor.rgb *= aoFactor.directAmbientOcclusion;
#endif
outColor = finalColor;
#ifdef _WRITE_RENDERING_LAYERS
outRenderingLayers = EncodeMeshRenderingLayer();
#endif
}

View File

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

View File

@@ -0,0 +1,275 @@
#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.
#ifndef HAVE_VFX_MODIFICATION
float3 _LightDirection;
#else
//_LightDirection is already defined in com.unity.render-pipelines.universal\Runtime\VFXGraph\Shaders\VFXCommon.hlsl
#endif
float3 _LightPosition;
#endif
#if defined(FEATURES_GRAPH_VERTEX)
#if defined(HAVE_VFX_MODIFICATION)
VertexDescription BuildVertexDescription(Attributes input, AttributesElement element, out GraphProperties properties)
{
ZERO_INITIALIZE(GraphProperties, properties);
// Fetch the vertex graph properties for the particle instance.
GetElementVertexProperties(element, properties);
// Evaluate Vertex Graph
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs, properties);
return vertexDescription;
}
#else
VertexDescription BuildVertexDescription(Attributes input)
{
// Evaluate Vertex Graph
VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input);
VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
return vertexDescription;
}
#endif
#endif
#if (SHADERPASS == SHADERPASS_MOTION_VECTORS)
// We want to gather some internal data from the BuildVaryings call to
// avoid rereading and recalculating these values again in the ShaderGraph motion vector pass
struct MotionVectorPassOutput
{
float3 positionOS;
float3 positionWS;
#if defined(FEATURES_GRAPH_VERTEX_MOTION_VECTOR_OUTPUT)
float3 motionVector;
#endif
#if defined(HAVE_VFX_MODIFICATION)
float3 vfxParticlePositionOS;
AttributesElement vfxElementAttributes;
GraphProperties vfxGraphProperties;
#endif
};
#endif
#if defined(HAVE_VFX_MODIFICATION)
bool PrepareVFXModification(inout Attributes input, inout Varyings output, inout AttributesElement element
#if (SHADERPASS == SHADERPASS_MOTION_VECTORS)
, inout MotionVectorPassOutput motionVectorOutput
#endif
)
{
if (!GetMeshAndElementIndex(input, element))
return true; // Culled index.
#if UNITY_ANY_INSTANCING_ENABLED
output.instanceID = input.instanceID; //Transfer instanceID again because we modify it in GetMeshAndElementIndex
#endif
if (!GetInterpolatorAndElementData(input, output, element))
return true; // Dead particle.
SetupVFXMatrices(element, output);
#if (SHADERPASS == SHADERPASS_MOTION_VECTORS)
motionVectorOutput.vfxParticlePositionOS = input.positionOS;
#endif
return false;
}
#endif
Varyings BuildVaryings(Attributes input
#if (SHADERPASS == SHADERPASS_MOTION_VECTORS)
, inout MotionVectorPassOutput motionVectorOutput
#endif
)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
bool isCulledOrDead = false;
#if defined(HAVE_VFX_MODIFICATION)
AttributesElement element;
ZERO_INITIALIZE(AttributesElement, element);
#if (SHADERPASS == SHADERPASS_MOTION_VECTORS)
isCulledOrDead = PrepareVFXModification(input, output, element, motionVectorOutput);
#else
isCulledOrDead = PrepareVFXModification(input, output, element);
#endif
#endif
if (!isCulledOrDead)
{
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
#if defined(FEATURES_GRAPH_VERTEX)
#if defined(HAVE_VFX_MODIFICATION)
GraphProperties properties;
VertexDescription vertexDescription = BuildVertexDescription(input, element, properties);
#else
VertexDescription vertexDescription = BuildVertexDescription(input);
#endif
#if defined(CUSTOMINTERPOLATOR_VARYPASSTHROUGH_FUNC)
CustomInterpolatorPassThroughFunc(output, vertexDescription);
#endif
// Assign modified vertex attributes
input.positionOS = vertexDescription.Position;
#if defined(ATTRIBUTES_NEED_NORMAL) && defined(FEATURES_GRAPH_VERTEX_NORMAL_OUTPUT)
input.normalOS = vertexDescription.Normal;
#endif //FEATURES_GRAPH_NORMAL
#if defined(ATTRIBUTES_NEED_TANGENT) && defined(FEATURES_GRAPH_VERTEX_TANGENT_OUTPUT)
input.tangentOS.xyz = vertexDescription.Tangent.xyz;
#endif //FEATURES GRAPH TANGENT
#endif //FEATURES_GRAPH_VERTEX
// TODO: Avoid path via VertexPositionInputs (Universal)
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
// Returns the camera relative position (if enabled)
float3 positionWS = TransformObjectToWorld(input.positionOS);
#if (SHADERPASS == SHADERPASS_MOTION_VECTORS)
motionVectorOutput.positionOS = input.positionOS;
motionVectorOutput.positionWS = positionWS;
#if defined(FEATURES_GRAPH_VERTEX_MOTION_VECTOR_OUTPUT)
motionVectorOutput.motionVector = vertexDescription.MotionVector;
#endif
#if defined(HAVE_VFX_MODIFICATION)
motionVectorOutput.vfxElementAttributes = element;
motionVectorOutput.vfxGraphProperties = properties;
#endif
#endif
#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
#if (SHADERPASS == SHADERPASS_SHADOWCASTER)
// Define shadow pass specific clip position for Universal
#if _CASTING_PUNCTUAL_LIGHT_SHADOW
float3 lightDirectionWS = normalize(_LightPosition - positionWS);
#else
float3 lightDirectionWS = _LightDirection;
#endif
output.positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirectionWS));
output.positionCS = ApplyShadowClamping(output.positionCS);
#elif (SHADERPASS == SHADERPASS_META)
output.positionCS = UnityMetaVertexPosition(input.positionOS, input.uv1.xy, input.uv2.xy, unity_LightmapST, unity_DynamicLightmapST);
#else
output.positionCS = TransformWorldToHClip(positionWS);
#endif
#if defined(VARYINGS_NEED_TEXCOORD0) || defined(VARYINGS_DS_NEED_TEXCOORD0)
output.texCoord0 = input.uv0;
#endif
#ifdef EDITOR_VISUALIZATION
float2 VizUV = 0;
float4 LightCoord = 0;
UnityEditorVizData(input.positionOS, input.uv0, input.uv1, input.uv2, VizUV, LightCoord);
#endif
#if defined(VARYINGS_NEED_TEXCOORD1) || defined(VARYINGS_DS_NEED_TEXCOORD1)
#ifdef EDITOR_VISUALIZATION
output.texCoord1 = float4(VizUV, 0, 0);
#else
output.texCoord1 = input.uv1;
#endif
#endif
#if defined(VARYINGS_NEED_TEXCOORD2) || defined(VARYINGS_DS_NEED_TEXCOORD2)
#ifdef EDITOR_VISUALIZATION
output.texCoord2 = LightCoord;
#else
output.texCoord2 = input.uv2;
#endif
#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
#if (defined(VARYINGS_NEED_INSTANCEID) || defined(VARYINGS_DS_NEED_INSTANCEID)) && !UNITY_ANY_INSTANCING_ENABLED
output.instanceID = input.instanceID;
#endif
#ifdef VARYINGS_NEED_SCREENPOSITION
output.screenPosition = vertexInput.positionNDC;
#endif
#if (SHADERPASS == SHADERPASS_FORWARD) || (SHADERPASS == SHADERPASS_GBUFFER)
OUTPUT_LIGHTMAP_UV(input.uv1, unity_LightmapST, output.staticLightmapUV);
#if defined(DYNAMICLIGHTMAP_ON)
output.dynamicLightmapUV.xy = input.uv2.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
#endif
OUTPUT_SH4(vertexInput.positionWS, normalWS.xyz, GetWorldSpaceNormalizeViewDir(vertexInput.positionWS), output.sh, output.probeOcclusion);
#endif
#ifdef VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
half fogFactor = 0;
#if !defined(_FOG_FRAGMENT)
fogFactor = ComputeFogFactor(output.positionCS.z);
#endif
half3 vertexLight = VertexLighting(positionWS, normalWS);
output.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#endif
#if defined(VARYINGS_NEED_SHADOW_COORD) && defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
output.shadowCoord = GetShadowCoord(vertexInput);
#endif
#if defined(VARYINGS_NEED_SIX_WAY_DIFFUSE_GI_DATA)
GatherDiffuseGIData(vertexInput.positionWS, normalWS.xyz, tangentWS, output.diffuseGIData0, output.diffuseGIData1, output.diffuseGIData2);
#endif
}
return output;
}
SurfaceDescription BuildSurfaceDescription(Varyings varyings)
{
SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(varyings);
#if defined(HAVE_VFX_MODIFICATION)
GraphProperties properties;
ZERO_INITIALIZE(GraphProperties, properties);
GetElementPixelProperties(surfaceDescriptionInputs, properties);
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs, properties);
#else
SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
#endif
return surfaceDescription;
}

View File

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

View File

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

View File

@@ -0,0 +1,171 @@
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEditor.ShaderGraph.Internal;
using UnityEngine.Rendering.Universal;
using System.Reflection;
using System.Linq;
using UnityEngine.XR;
namespace UnityEditor.Rendering.Universal
{
[SRPFilter(typeof(UniversalRenderPipeline))]
[Title("Input", "Universal", "URP Sample Buffer")]
sealed class UniversalSampleBufferNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireScreenPosition, IMayRequireNDCPosition
{
const string k_ScreenPositionSlotName = "UV";
const string k_OutputSlotName = "Output";
const int k_ScreenPositionSlotId = 0;
const int k_OutputSlotId = 2;
public enum BufferType
{
NormalWorldSpace,
MotionVectors,
BlitSource,
}
[SerializeField]
private BufferType m_BufferType = BufferType.NormalWorldSpace;
[EnumControl("Source Buffer")]
public BufferType bufferType
{
get { return m_BufferType; }
set
{
if (m_BufferType == value)
return;
m_BufferType = value;
UpdateNodeAfterDeserialization();
Dirty(ModificationScope.Graph);
}
}
public override string documentationURL => Documentation.GetPageLink(Documentation.packageName, "SGNode-Universal-Sample-Buffer");
public UniversalSampleBufferNode()
{
name = "URP Sample Buffer";
synonyms = new string[] { "normal", "motion vector", "blit" };
UpdateNodeAfterDeserialization();
}
public override bool hasPreview { get { return true; } }
public override PreviewMode previewMode => PreviewMode.Preview2D;
int channelCount;
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new ScreenPositionMaterialSlot(k_ScreenPositionSlotId, k_ScreenPositionSlotName, k_ScreenPositionSlotName, ScreenSpaceType.Default));
switch (bufferType)
{
case BufferType.NormalWorldSpace:
AddSlot(new Vector3MaterialSlot(k_OutputSlotId, k_OutputSlotName, k_OutputSlotName, SlotType.Output, Vector3.zero, ShaderStageCapability.Fragment));
channelCount = 3;
break;
case BufferType.MotionVectors:
AddSlot(new Vector2MaterialSlot(k_OutputSlotId, k_OutputSlotName, k_OutputSlotName, SlotType.Output, Vector2.zero, ShaderStageCapability.Fragment));
channelCount = 2;
break;
case BufferType.BlitSource:
AddSlot(new ColorRGBAMaterialSlot(k_OutputSlotId, k_OutputSlotName, k_OutputSlotName, SlotType.Output, Color.black, ShaderStageCapability.Fragment));
channelCount = 4;
break;
}
RemoveSlotsNameNotMatching(new[]
{
k_ScreenPositionSlotId,
k_OutputSlotId,
});
}
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
{
if (generationMode.IsPreview())
return;
}
string GetFunctionName() => $"Unity_Universal_SampleBuffer_{bufferType}_$precision";
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
// Preview SG doesn't have access to render pipeline buffer
if (!generationMode.IsPreview())
{
registry.ProvideFunction(GetFunctionName(), s =>
{
if (bufferType == BufferType.MotionVectors)
s.AppendLine("TEXTURE2D_X(_MotionVectorTexture);");
if (bufferType == BufferType.BlitSource)
{
s.AppendLine("TEXTURE2D_X(_BlitTexture);");
}
s.AppendLine("$precision{1} {0}($precision2 uv)", GetFunctionName(), channelCount);
using (s.BlockScope())
{
switch (bufferType)
{
case BufferType.NormalWorldSpace:
s.AppendLine("return SHADERGRAPH_SAMPLE_SCENE_NORMAL(uv);");
break;
case BufferType.MotionVectors:
s.AppendLine("uint2 pixelCoords = uint2(uv * _ScreenSize.xy);");
s.AppendLine($"return LOAD_TEXTURE2D_X_LOD(_MotionVectorTexture, pixelCoords, 0).xy;");
break;
case BufferType.BlitSource:
s.AppendLine("uint2 pixelCoords = uint2(uv * _ScreenSize.xy);");
s.AppendLine($"return LOAD_TEXTURE2D_X_LOD(_BlitTexture, pixelCoords, 0);");
break;
default:
s.AppendLine("return 0.0;");
break;
}
}
});
}
else
{
registry.ProvideFunction(GetFunctionName(), s =>
{
s.AppendLine("$precision{1} {0}($precision2 uv)", GetFunctionName(), channelCount);
using (s.BlockScope())
{
switch (bufferType)
{
case BufferType.NormalWorldSpace:
s.AppendLine("return LatlongToDirectionCoordinate(uv);");
break;
case BufferType.MotionVectors:
s.AppendLine("return uv * 2 - 1;");
break;
case BufferType.BlitSource:
default:
s.AppendLine("return 0.0;");
break;
}
}
});
}
}
public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode)
{
string uv = GetSlotValue(k_ScreenPositionSlotId, generationMode);
sb.AppendLine($"$precision{channelCount} {GetVariableNameForSlot(k_OutputSlotId)} = {GetFunctionName()}({uv}.xy);");
}
public bool RequiresNDCPosition(ShaderStageCapability stageCapability = ShaderStageCapability.All) => true;
public bool RequiresScreenPosition(ShaderStageCapability stageCapability = ShaderStageCapability.All) => true;
}
}

View File

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

View File

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

View File

@@ -0,0 +1,73 @@
using UnityEditor.ShaderGraph;
using UnityEngine;
using static UnityEditor.Rendering.BuiltIn.ShaderUtils;
using UnityEditor.Rendering.BuiltIn;
using System;
using UnityEngine.UIElements;
using UnityEditor.Rendering.Canvas.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
class UniversalCanvasSubTarget: CanvasSubTarget<UniversalTarget>, IRequiresData<CanvasData>, IHasMetadata
{
static readonly GUID kSourceCodeGuid = new GUID("f7075c3a804b49bf86535f6f86615132"); // UniversalCanvasSubTarget.cs
static readonly string kCanvasPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/CanvasPass.hlsl";
public override void Setup(ref TargetSetupContext context)
{
base.Setup(ref context);
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
}
public override bool IsActive() => true;
// We don't need the save context / update materials for now
public override object saveContext => null;
protected override string pipelineTag => UniversalTarget.kPipelineTag;
protected override IncludeCollection pregraphIncludes => new IncludeCollection
{
{ CoreIncludes.CorePregraph },
{ kInstancing, IncludeLocation.Pregraph },
{ CoreIncludes.ShaderGraphPregraph },
};
protected override IncludeCollection postgraphIncludes => new IncludeCollection
{
{kCanvasPass, IncludeLocation.Postgraph},
};
public UniversalCanvasSubTarget()
{
displayName = "Canvas";
}
protected override DefineCollection GetAdditionalDefines()
{
var result = new DefineCollection();
if (canvasData.alphaClip)
result.Add(CoreKeywordDescriptors.AlphaTestOn, 1);
result.Add(base.GetAdditionalDefines());
return result;
}
public override void GetActiveBlocks(ref TargetActiveBlockContext context)
{
base.GetActiveBlocks(ref context);
context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, canvasData.alphaClip);
}
public override void GetFields(ref TargetFieldContext context)
{
base.GetFields(ref context);
if (canvasData.alphaClip)
context.AddField(UnityEditor.ShaderGraph.Fields.AlphaTest);
}
public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
base.CollectShaderProperties(collector, generationMode);
if (canvasData.alphaClip)
collector.AddShaderProperty(CanvasProperties.AlphaTest);
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,47 @@
using UnityEditor.ShaderGraph;
using UnityEngine;
using static UnityEditor.Rendering.BuiltIn.ShaderUtils;
using UnityEditor.Rendering.BuiltIn;
using System;
using UnityEditor.Rendering.Fullscreen.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
class UniversalFullscreenSubTarget : FullscreenSubTarget<UniversalTarget>, IRequiresData<FullscreenData>, IHasMetadata
{
static readonly GUID kSourceCodeGuid = new GUID("48080a5025a54a84087e882e2f988642"); // UniversalFullscreenSubTarget.cs // TODO
public override void Setup(ref TargetSetupContext context)
{
base.Setup(ref context);
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
}
protected override KeywordCollection GetPassKeywords(FullscreenCompatibility compatibility)
{
var modifiedKeywordCollection = base.GetPassKeywords(compatibility);
modifiedKeywordCollection.Add(CoreKeywordDescriptors.GBufferNormalsOct);
return modifiedKeywordCollection;
}
// We don't need the save context / update materials for now
public override object saveContext => null;
protected override string pipelineTag => UniversalTarget.kPipelineTag;
const string kURPInput = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl";
protected override IncludeCollection pregraphIncludes => new IncludeCollection
{
{ kURPInput, IncludeLocation.Pregraph }, // Include before kInstancing
{ kInstancing, IncludeLocation.Pregraph }, // For VR
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
};
public UniversalFullscreenSubTarget()
{
displayName = "Fullscreen";
}
}
}

View File

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

View File

@@ -0,0 +1,963 @@
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.ShaderGraph;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using UnityEditor.ShaderGraph.Legacy;
using UnityEngine.Assertions;
using static UnityEditor.Rendering.Universal.ShaderGraph.SubShaderUtils;
using UnityEngine.Rendering.Universal;
using static Unity.Rendering.Universal.ShaderUtils;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
sealed class UniversalLitSubTarget : UniversalSubTarget, ILegacyTarget
{
static readonly GUID kSourceCodeGuid = new GUID("d6c78107b64145745805d963de80cc17"); // UniversalLitSubTarget.cs
public override int latestVersion => 2;
[SerializeField]
WorkflowMode m_WorkflowMode = WorkflowMode.Metallic;
[SerializeField]
NormalDropOffSpace m_NormalDropOffSpace = NormalDropOffSpace.Tangent;
[SerializeField]
bool m_ClearCoat = false;
[SerializeField]
bool m_BlendModePreserveSpecular = true;
public UniversalLitSubTarget()
{
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 bool clearCoat
{
get => m_ClearCoat;
set => m_ClearCoat = value;
}
private bool complexLit
{
get
{
// Rules for switching to ComplexLit with forward only pass
return clearCoat; // && <complex feature>
}
}
public bool blendModePreserveSpecular
{
get => m_BlendModePreserveSpecular;
set => m_BlendModePreserveSpecular = value;
}
public override bool IsActive() => true;
public override void Setup(ref TargetSetupContext context)
{
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
base.Setup(ref context);
var universalRPType = typeof(UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset);
if (!context.HasCustomEditorForRenderPipeline(universalRPType))
{
var gui = typeof(ShaderGraphLitGUI);
#if HAS_VFX_GRAPH
if (TargetsVFX())
gui = typeof(VFXShaderGraphLitGUI);
#endif
context.AddCustomEditorForRenderPipeline(gui.FullName, universalRPType);
}
// Process SubShaders
context.AddSubShader(PostProcessSubShader(SubShaders.LitSubShader(target, workflowMode, target.renderType, target.renderQueue, target.disableBatching, complexLit, blendModePreserveSpecular)));
}
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.CastShadows, target.castShadows ? 1.0f : 0.0f);
material.SetFloat(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f);
material.SetFloat(Property.SurfaceType, (float)target.surfaceType);
material.SetFloat(Property.BlendMode, (float)target.alphaMode);
material.SetFloat(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
material.SetFloat(Property.CullMode, (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)BaseShaderGUI.QueueControl.Auto);
if (IsSpacewarpSupported())
material.SetFloat(Property.XrMotionVectorsPass, 1.0f);
// call the full unlit material setup function
ShaderGraphLitGUI.UpdateMaterial(material, MaterialUpdateType.CreatedNewMaterial);
}
public override void GetFields(ref TargetFieldContext context)
{
base.GetFields(ref context);
var descs = context.blocks.Select(x => x.descriptor);
// Lit -- always controlled by subtarget
context.AddField(UniversalFields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object);
context.AddField(UniversalFields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent);
context.AddField(UniversalFields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World);
context.AddField(UniversalFields.Normal, descs.Contains(BlockFields.SurfaceDescription.NormalOS) ||
descs.Contains(BlockFields.SurfaceDescription.NormalTS) ||
descs.Contains(BlockFields.SurfaceDescription.NormalWS));
// Complex Lit
// Template Predicates
//context.AddField(UniversalFields.PredicateClearCoat, clearCoat);
}
public override void GetActiveBlocks(ref TargetActiveBlockContext context)
{
context.AddBlock(UniversalBlockFields.VertexDescription.MotionVector, target.additionalMotionVectorMode == AdditionalMotionVectorMode.Custom);
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);
// when the surface options are material controlled, we must show all of these blocks
// when target controlled, we can cull the unnecessary blocks
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);
// always controlled by subtarget clearCoat checkbox (no Material control)
context.AddBlock(BlockFields.SurfaceDescription.CoatMask, clearCoat);
context.AddBlock(BlockFields.SurfaceDescription.CoatSmoothness, clearCoat);
}
public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
// if using material control, add the material property to control workflow mode
if (target.allowMaterialOverride)
{
collector.AddFloatProperty(Property.SpecularWorkflowMode, (float)workflowMode);
collector.AddFloatProperty(Property.CastShadows, target.castShadows ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f);
// setup properties using the defaults
collector.AddFloatProperty(Property.SurfaceType, (float)target.surfaceType);
collector.AddFloatProperty(Property.BlendMode, (float)target.alphaMode);
collector.AddFloatProperty(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.BlendModePreserveSpecular, blendModePreserveSpecular ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.SrcBlendAlpha, 1.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.DstBlendAlpha, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque));
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.CullMode, (float)target.renderFace); // render face enum is designed to directly pass as a cull mode
bool enableAlphaToMask = (target.alphaClip && (target.surfaceType == SurfaceType.Opaque));
collector.AddFloatProperty(Property.AlphaToMask, enableAlphaToMask ? 1.0f : 0.0f);
}
// 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);
if (IsSpacewarpSupported())
collector.AddFloatProperty(Property.XrMotionVectorsPass, 1.0f);
}
public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action<String> registerUndo)
{
var universalTarget = (target as UniversalTarget);
universalTarget.AddDefaultMaterialOverrideGUI(ref context, onChange, registerUndo);
context.AddProperty("Workflow Mode", new EnumField(WorkflowMode.Metallic) { value = workflowMode }, (evt) =>
{
if (Equals(workflowMode, evt.newValue))
return;
registerUndo("Change Workflow");
workflowMode = (WorkflowMode)evt.newValue;
onChange();
});
universalTarget.AddDefaultSurfacePropertiesGUI(ref context, onChange, registerUndo, showReceiveShadows: true);
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();
});
context.AddProperty("Clear Coat", new Toggle() { value = clearCoat }, (evt) =>
{
if (Equals(clearCoat, evt.newValue))
return;
registerUndo("Change Clear Coat");
clearCoat = evt.newValue;
onChange();
});
if (target.surfaceType == SurfaceType.Transparent)
{
if (target.alphaMode == AlphaMode.Alpha || target.alphaMode == AlphaMode.Additive)
context.AddProperty("Preserve Specular Lighting", new Toggle() { value = blendModePreserveSpecular }, (evt) =>
{
if (Equals(blendModePreserveSpecular, evt.newValue))
return;
registerUndo("Change Preserve Specular");
blendModePreserveSpecular = evt.newValue;
onChange();
});
}
}
protected override int ComputeMaterialNeedsUpdateHash()
{
int hash = base.ComputeMaterialNeedsUpdateHash();
hash = hash * 23 + target.allowMaterialOverride.GetHashCode();
return hash;
}
public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary<BlockFieldDescriptor, int> blockMap)
{
blockMap = null;
if (!(masterNode is PBRMasterNode1 pbrMasterNode))
return false;
m_WorkflowMode = (WorkflowMode)pbrMasterNode.m_Model;
m_NormalDropOffSpace = (NormalDropOffSpace)pbrMasterNode.m_NormalDropOffSpace;
// Handle mapping of Normal block specifically
BlockFieldDescriptor normalBlock;
switch (m_NormalDropOffSpace)
{
case NormalDropOffSpace.Object:
normalBlock = BlockFields.SurfaceDescription.NormalOS;
break;
case NormalDropOffSpace.World:
normalBlock = BlockFields.SurfaceDescription.NormalWS;
break;
default:
normalBlock = BlockFields.SurfaceDescription.NormalTS;
break;
}
// Set blockmap
blockMap = new Dictionary<BlockFieldDescriptor, int>()
{
{ BlockFields.VertexDescription.Position, 9 },
{ BlockFields.VertexDescription.Normal, 10 },
{ BlockFields.VertexDescription.Tangent, 11 },
{ BlockFields.SurfaceDescription.BaseColor, 0 },
{ normalBlock, 1 },
{ BlockFields.SurfaceDescription.Emission, 4 },
{ BlockFields.SurfaceDescription.Smoothness, 5 },
{ BlockFields.SurfaceDescription.Occlusion, 6 },
{ BlockFields.SurfaceDescription.Alpha, 7 },
{ BlockFields.SurfaceDescription.AlphaClipThreshold, 8 },
};
// PBRMasterNode adds/removes Metallic/Specular based on settings
if (m_WorkflowMode == WorkflowMode.Specular)
blockMap.Add(BlockFields.SurfaceDescription.Specular, 3);
else if (m_WorkflowMode == WorkflowMode.Metallic)
blockMap.Add(BlockFields.SurfaceDescription.Metallic, 2);
return true;
}
internal override void OnAfterParentTargetDeserialized()
{
Assert.IsNotNull(target);
if (this.sgVersion < latestVersion)
{
// Upgrade old incorrect Premultiplied blend into
// equivalent Alpha + Preserve Specular blend mode.
if (this.sgVersion < 1)
{
if (target.alphaMode == AlphaMode.Premultiply)
{
target.alphaMode = AlphaMode.Alpha;
blendModePreserveSpecular = true;
}
else
blendModePreserveSpecular = false;
}
ChangeVersion(latestVersion);
}
}
#region SubShader
static class SubShaders
{
public static SubShaderDescriptor LitSubShader(UniversalTarget target, WorkflowMode workflowMode, string renderType, string renderQueue, string disableBatchingTag, bool complexLit, bool blendModePreserveSpecular)
{
SubShaderDescriptor result = new SubShaderDescriptor()
{
pipelineTag = UniversalTarget.kPipelineTag,
customTags = complexLit ? UniversalTarget.kComplexLitMaterialTypeTag : UniversalTarget.kLitMaterialTypeTag,
renderType = renderType,
renderQueue = renderQueue,
disableBatchingTag = disableBatchingTag,
generatesPreview = true,
passes = new PassCollection()
};
if (complexLit)
result.passes.Add(LitPasses.ForwardOnly(target, workflowMode, complexLit, blendModePreserveSpecular, CoreBlockMasks.Vertex, LitBlockMasks.FragmentComplexLit, CorePragmas.Forward, LitKeywords.Forward));
else
result.passes.Add(LitPasses.Forward(target, workflowMode, blendModePreserveSpecular, CorePragmas.Forward, LitKeywords.Forward));
// ForwardOnly ComplexLit fills GBuffer too for potential custom usage of the GBuffer.
result.passes.Add(LitPasses.GBuffer(target, workflowMode, blendModePreserveSpecular));
// cull the shadowcaster pass if we know it will never be used
if (target.castShadows || target.allowMaterialOverride)
result.passes.Add(PassVariant(CorePasses.ShadowCaster(target), CorePragmas.Instanced));
if (target.alwaysRenderMotionVectors)
result.customTags = string.Concat(result.customTags, " ", UniversalTarget.kAlwaysRenderMotionVectorsTag);
result.passes.Add(PassVariant(CorePasses.MotionVectors(target), CorePragmas.MotionVectors));
if (IsSpacewarpSupported())
result.passes.Add(PassVariant(CorePasses.XRMotionVectors(target), CorePragmas.XRMotionVectors));
if (target.mayWriteDepth)
result.passes.Add(PassVariant(CorePasses.DepthOnly(target), CorePragmas.Instanced));
if (complexLit)
result.passes.Add(PassVariant(LitPasses.DepthNormalOnly(target), CorePragmas.Instanced));
else
result.passes.Add(PassVariant(LitPasses.DepthNormal(target), CorePragmas.Instanced));
result.passes.Add(PassVariant(LitPasses.Meta(target), CorePragmas.Default));
// Currently neither of these passes (selection/picking) can be last for the game view for
// UI shaders to render correctly. Verify [1352225] before changing this order.
result.passes.Add(PassVariant(CorePasses.SceneSelection(target), CorePragmas.Default));
result.passes.Add(PassVariant(CorePasses.ScenePicking(target), CorePragmas.Default));
result.passes.Add(PassVariant(LitPasses._2D(target), CorePragmas.Default));
return result;
}
}
#endregion
#region Passes
static class LitPasses
{
static void AddWorkflowModeControlToPass(ref PassDescriptor pass, UniversalTarget target, WorkflowMode workflowMode)
{
if (target.allowMaterialOverride)
pass.keywords.Add(LitDefines.SpecularSetup);
else if (workflowMode == WorkflowMode.Specular)
pass.defines.Add(LitDefines.SpecularSetup, 1);
}
static void AddReceiveShadowsControlToPass(ref PassDescriptor pass, UniversalTarget target, bool receiveShadows)
{
if (target.allowMaterialOverride)
pass.keywords.Add(LitKeywords.ReceiveShadowsOff);
else if (!receiveShadows)
pass.defines.Add(LitKeywords.ReceiveShadowsOff, 1);
}
public static PassDescriptor Forward(
UniversalTarget target,
WorkflowMode workflowMode,
bool blendModePreserveSpecular,
PragmaCollection pragmas,
KeywordCollection keywords)
{
var result = new PassDescriptor()
{
// Definition
displayName = "Universal Forward",
referenceName = "SHADERPASS_FORWARD",
lightMode = "UniversalForward",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = LitBlockMasks.FragmentLit,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular),
pragmas = pragmas ?? CorePragmas.Forward, // NOTE: SM 2.0 only GL
defines = new DefineCollection() { },
keywords = new KeywordCollection() { keywords },
includes = LitIncludes.Forward,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular);
CorePasses.AddAlphaToMaskControlToPass(ref result, target);
AddWorkflowModeControlToPass(ref result, target, workflowMode);
AddReceiveShadowsControlToPass(ref result, target, target.receiveShadows);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
public static PassDescriptor ForwardOnly(
UniversalTarget target,
WorkflowMode workflowMode,
bool complexLit,
bool blendModePreserveSpecular,
BlockFieldDescriptor[] vertexBlocks,
BlockFieldDescriptor[] pixelBlocks,
PragmaCollection pragmas,
KeywordCollection keywords)
{
var result = new PassDescriptor
{
// Definition
displayName = "Universal Forward Only",
referenceName = "SHADERPASS_FORWARDONLY",
lightMode = "UniversalForwardOnly",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = vertexBlocks,
validPixelBlocks = pixelBlocks,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular),
pragmas = pragmas,
defines = new DefineCollection { CoreDefines.UseFragmentFog },
keywords = new KeywordCollection { keywords },
includes = new IncludeCollection { LitIncludes.Forward },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
if (complexLit)
result.defines.Add(LitDefines.ClearCoat, 1);
CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular);
CorePasses.AddAlphaToMaskControlToPass(ref result, target);
AddWorkflowModeControlToPass(ref result, target, workflowMode);
AddReceiveShadowsControlToPass(ref result, target, target.receiveShadows);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
// Deferred only in SM4.5
public static PassDescriptor GBuffer(UniversalTarget target, WorkflowMode workflowMode, bool blendModePreserveSpecular)
{
var result = new PassDescriptor
{
// Definition
displayName = "GBuffer",
referenceName = "SHADERPASS_GBUFFER",
lightMode = "UniversalGBuffer",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = LitBlockMasks.FragmentLit,
// Fields
structs = CoreStructCollections.Default,
requiredFields = LitRequiredFields.GBuffer,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular),
pragmas = CorePragmas.GBuffer,
defines = new DefineCollection { CoreDefines.UseFragmentFog },
keywords = new KeywordCollection { LitKeywords.GBuffer },
includes = new IncludeCollection { LitIncludes.GBuffer },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular);
AddWorkflowModeControlToPass(ref result, target, workflowMode);
AddReceiveShadowsControlToPass(ref result, target, target.receiveShadows);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
public static PassDescriptor Meta(UniversalTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "Meta",
referenceName = "SHADERPASS_META",
lightMode = "Meta",
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.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.UseFragmentFog },
keywords = new KeywordCollection() { CoreKeywordDescriptors.EditorVisualization },
includes = LitIncludes.Meta,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddAlphaClipControlToPass(ref result, target);
return result;
}
public static PassDescriptor _2D(UniversalTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "Universal 2D",
referenceName = "SHADERPASS_2D",
lightMode = "Universal2D",
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = CoreBlockMasks.FragmentColorAlpha,
// Fields
structs = CoreStructCollections.Default,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.UberSwitchedRenderState(target),
pragmas = CorePragmas.Instanced,
defines = new DefineCollection(),
keywords = new KeywordCollection(),
includes = LitIncludes._2D,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddAlphaClipControlToPass(ref result, target);
return result;
}
public static PassDescriptor DepthNormal(UniversalTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "DepthNormals",
referenceName = "SHADERPASS_DEPTHNORMALS",
lightMode = "DepthNormals",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = CoreBlockMasks.FragmentDepthNormals,
// Fields
structs = CoreStructCollections.Default,
requiredFields = CoreRequiredFields.DepthNormals,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.DepthNormalsOnly(target),
pragmas = CorePragmas.Instanced,
defines = new DefineCollection(),
keywords = new KeywordCollection(),
includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddAlphaClipControlToPass(ref result, target);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
public static PassDescriptor DepthNormalOnly(UniversalTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "DepthNormalsOnly",
referenceName = "SHADERPASS_DEPTHNORMALSONLY",
lightMode = "DepthNormalsOnly",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = CoreBlockMasks.FragmentDepthNormals,
// Fields
structs = CoreStructCollections.Default,
requiredFields = CoreRequiredFields.DepthNormals,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.DepthNormalsOnly(target),
pragmas = CorePragmas.Instanced,
defines = new DefineCollection(),
keywords = new KeywordCollection(),
includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddAlphaClipControlToPass(ref result, target);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
}
#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[] FragmentComplexLit = 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,
BlockFields.SurfaceDescription.CoatMask,
BlockFields.SurfaceDescription.CoatSmoothness,
};
public static readonly BlockFieldDescriptor[] FragmentMeta = new BlockFieldDescriptor[]
{
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.Emission,
BlockFields.SurfaceDescription.Alpha,
BlockFields.SurfaceDescription.AlphaClipThreshold,
};
}
#endregion
#region RequiredFields
static class LitRequiredFields
{
public static readonly FieldCollection Forward = new FieldCollection()
{
StructFields.Attributes.uv1,
StructFields.Attributes.uv2,
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS,
StructFields.Varyings.tangentWS, // needed for vertex lighting
UniversalStructFields.Varyings.staticLightmapUV,
UniversalStructFields.Varyings.dynamicLightmapUV,
UniversalStructFields.Varyings.sh,
UniversalStructFields.Varyings.probeOcclusion,
UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency
UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency
};
public static readonly FieldCollection GBuffer = new FieldCollection()
{
StructFields.Attributes.uv1,
StructFields.Attributes.uv2,
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS,
StructFields.Varyings.tangentWS, // needed for vertex lighting
UniversalStructFields.Varyings.staticLightmapUV,
UniversalStructFields.Varyings.dynamicLightmapUV,
UniversalStructFields.Varyings.sh,
UniversalStructFields.Varyings.probeOcclusion,
UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency
UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency
};
public static readonly FieldCollection Meta = new FieldCollection()
{
StructFields.Attributes.positionOS,
StructFields.Attributes.normalOS,
StructFields.Attributes.uv0, //
StructFields.Attributes.uv1, // needed for meta vertex position
StructFields.Attributes.uv2, // needed for meta UVs
StructFields.Attributes.instanceID, // needed for rendering instanced terrain
StructFields.Varyings.positionCS,
StructFields.Varyings.texCoord0, // needed for meta UVs
StructFields.Varyings.texCoord1, // VizUV
StructFields.Varyings.texCoord2, // LightCoord
};
}
#endregion
#region Defines
static class LitDefines
{
public static readonly KeywordDescriptor ClearCoat = new KeywordDescriptor()
{
displayName = "Clear Coat",
referenceName = "_CLEARCOAT",
type = KeywordType.Boolean,
definition = KeywordDefinition.ShaderFeature,
scope = KeywordScope.Local,
stages = KeywordShaderStage.Fragment
};
public static readonly KeywordDescriptor SpecularSetup = new KeywordDescriptor()
{
displayName = "Specular Setup",
referenceName = "_SPECULAR_SETUP",
type = KeywordType.Boolean,
definition = KeywordDefinition.ShaderFeature,
scope = KeywordScope.Local,
stages = KeywordShaderStage.Fragment
};
}
#endregion
#region Keywords
static class LitKeywords
{
public static readonly KeywordDescriptor ReceiveShadowsOff = new KeywordDescriptor()
{
displayName = "Receive Shadows Off",
referenceName = ShaderKeywordStrings._RECEIVE_SHADOWS_OFF,
type = KeywordType.Boolean,
definition = KeywordDefinition.ShaderFeature,
scope = KeywordScope.Local,
};
public static readonly KeywordCollection Forward = new KeywordCollection
{
{ CoreKeywordDescriptors.ScreenSpaceAmbientOcclusion },
{ CoreKeywordDescriptors.StaticLightmap },
{ CoreKeywordDescriptors.DynamicLightmap },
{ CoreKeywordDescriptors.DirectionalLightmapCombined },
{ CoreKeywordDescriptors.UseLegacyLightmaps },
{ CoreKeywordDescriptors.LightmapBicubicSampling },
{ CoreKeywordDescriptors.MainLightShadows },
{ CoreKeywordDescriptors.AdditionalLights },
{ CoreKeywordDescriptors.AdditionalLightShadows },
{ CoreKeywordDescriptors.ReflectionProbeBlending },
{ CoreKeywordDescriptors.ReflectionProbeBoxProjection },
{ CoreKeywordDescriptors.ReflectionProbeAtlas },
{ CoreKeywordDescriptors.ShadowsSoft },
{ CoreKeywordDescriptors.LightmapShadowMixing },
{ CoreKeywordDescriptors.ShadowsShadowmask },
{ CoreKeywordDescriptors.DBuffer },
{ CoreKeywordDescriptors.LightLayers },
{ CoreKeywordDescriptors.DebugDisplay },
{ CoreKeywordDescriptors.LightCookies },
{ CoreKeywordDescriptors.ClusterLightLoop },
{ CoreKeywordDescriptors.EvaluateSh },
};
public static readonly KeywordCollection GBuffer = new KeywordCollection
{
{ CoreKeywordDescriptors.StaticLightmap },
{ CoreKeywordDescriptors.DynamicLightmap },
{ CoreKeywordDescriptors.DirectionalLightmapCombined },
{ CoreKeywordDescriptors.UseLegacyLightmaps },
{ CoreKeywordDescriptors.LightmapBicubicSampling },
{ CoreKeywordDescriptors.MainLightShadows },
{ CoreKeywordDescriptors.ReflectionProbeBlending },
{ CoreKeywordDescriptors.ReflectionProbeBoxProjection },
{ CoreKeywordDescriptors.ShadowsSoft },
{ CoreKeywordDescriptors.LightmapShadowMixing },
{ CoreKeywordDescriptors.ShadowsShadowmask },
{ CoreKeywordDescriptors.MixedLightingSubtractive },
{ CoreKeywordDescriptors.DBuffer },
{ CoreKeywordDescriptors.GBufferNormalsOct },
{ CoreKeywordDescriptors.RenderPassEnabled },
{ CoreKeywordDescriptors.DebugDisplay },
{ CoreKeywordDescriptors.ClusterLightLoop },
};
}
#endregion
#region Includes
static class LitIncludes
{
const string kShadows = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl";
const string kMetaInput = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/MetaInput.hlsl";
const string kForwardPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRForwardPass.hlsl";
const string kGBuffer = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferOutput.hlsl";
const string kPBRGBufferPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl";
const string kLightingMetaPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl";
const string k2DPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl";
public static readonly IncludeCollection Forward = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.DOTSPregraph },
{ CoreIncludes.FogPregraph },
{ CoreIncludes.WriteRenderLayersPregraph },
{ CoreIncludes.ProbeVolumePregraph },
{ CoreIncludes.CorePregraph },
{ kShadows, IncludeLocation.Pregraph },
{ CoreIncludes.ShaderGraphPregraph },
{ CoreIncludes.DBufferPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kForwardPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection GBuffer = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.DOTSPregraph },
{ CoreIncludes.FogPregraph },
{ CoreIncludes.WriteRenderLayersPregraph },
{ CoreIncludes.ProbeVolumePregraph },
{ CoreIncludes.CorePregraph },
{ kShadows, IncludeLocation.Pregraph },
{ CoreIncludes.ShaderGraphPregraph },
{ CoreIncludes.DBufferPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kGBuffer, IncludeLocation.Postgraph },
{ kPBRGBufferPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection Meta = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
{ kMetaInput, IncludeLocation.Pregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kLightingMetaPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection _2D = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ k2DPass, IncludeLocation.Postgraph },
};
}
#endregion
}
}

View File

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

View File

@@ -0,0 +1,528 @@
using System;
using UnityEngine;
using UnityEditor.ShaderGraph;
using UnityEngine.UIElements;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
using static UnityEditor.Rendering.Universal.ShaderGraph.SubShaderUtils;
using UnityEngine.Rendering.Universal;
using static Unity.Rendering.Universal.ShaderUtils;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
sealed class UniversalSixWaySubTarget : UniversalSubTarget
{
static readonly GUID kSourceCodeGuid = new GUID("d6c78107b64145745805d963de80cc17"); // UniversalLitSubTarget.cs
public override int latestVersion => 2;
public UniversalSixWaySubTarget()
{
displayName = "Six-way Smoke Lit";
}
protected override ShaderID shaderID => ShaderID.SG_SixWaySmokeLit;
public override bool IsActive() => true;
[SerializeField]
bool m_UseColorAbsorption = true;
bool useColorAbsorption
{
get => m_UseColorAbsorption;
set => m_UseColorAbsorption = value;
}
public override void Setup(ref TargetSetupContext context)
{
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
base.Setup(ref context);
var universalRPType = typeof(UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset);
if (!context.HasCustomEditorForRenderPipeline(universalRPType))
{
var gui = typeof(SixWayGUI);
#if HAS_VFX_GRAPH
if (TargetsVFX())
gui = typeof(VFXSixWayGUI);
#endif
context.AddCustomEditorForRenderPipeline(gui.FullName, universalRPType);
}
// Process SubShaders
context.AddSubShader(PostProcessSubShader(SubShaders.SixWaySubShader(target, target.renderType, target.renderQueue, target.disableBatching, useColorAbsorption)));
}
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.CastShadows, target.castShadows ? 1.0f : 0.0f);
material.SetFloat(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f);
material.SetFloat(Property.SurfaceType, (float)target.surfaceType);
material.SetFloat(Property.BlendMode, (float)target.alphaMode);
material.SetFloat(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
material.SetFloat(Property.CullMode, (int)target.renderFace);
material.SetFloat(Property.ZWriteControl, (float)target.zWriteControl);
material.SetFloat(Property.ZTest, (float)target.zTestMode);
material.SetFloat(SixWayProperties.UseColorAbsorption, useColorAbsorption ? 1.0f : 0.0f );
}
// 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)BaseShaderGUI.QueueControl.Auto);
// call the full unlit material setup function
ShaderGraphLitGUI.UpdateMaterial(material, MaterialUpdateType.CreatedNewMaterial);
bool useColorAbsorptionValue = false;
if (material.HasProperty(SixWayProperties.UseColorAbsorption))
useColorAbsorptionValue = material.GetFloat(SixWayProperties.UseColorAbsorption) > 0.0f;
CoreUtils.SetKeyword(material, "_SIX_WAY_COLOR_ABSORPTION", useColorAbsorptionValue);
}
public override void GetFields(ref TargetFieldContext context)
{
base.GetFields(ref context);
bool containsNormalDescriptor = false;
foreach (var block in context.blocks)
{
if (Equals(block.descriptor, BlockFields.SurfaceDescription.NormalOS) ||
Equals(block.descriptor, BlockFields.SurfaceDescription.NormalTS) ||
Equals(block.descriptor, BlockFields.SurfaceDescription.NormalWS))
{
containsNormalDescriptor = true;
break;
}
}
context.AddField(UniversalFields.Normal, containsNormalDescriptor);
}
public struct Varyings
{
public static string name = "Varyings";
public static FieldDescriptor diffuseGIData0 = new FieldDescriptor(Varyings.name, "diffuseGIData0",
"VARYINGS_NEED_SIX_WAY_DIFFUSE_GI_DATA", ShaderValueType.Float4 ,subscriptOptions: StructFieldOptions.Optional);
public static FieldDescriptor diffuseGIData1 = new FieldDescriptor(Varyings.name, "diffuseGIData1",
"VARYINGS_NEED_SIX_WAY_DIFFUSE_GI_DATA", ShaderValueType.Float4 ,subscriptOptions: StructFieldOptions.Optional);
public static FieldDescriptor diffuseGIData2 = new FieldDescriptor(Varyings.name, "diffuseGIData2",
"VARYINGS_NEED_SIX_WAY_DIFFUSE_GI_DATA", ShaderValueType.Float4, subscriptOptions: StructFieldOptions.Optional);
}
public override void GetActiveBlocks(ref TargetActiveBlockContext context)
{
context.AddBlock(BlockFields.SurfaceDescription.Emission);
context.AddBlock(BlockFields.SurfaceDescription.Occlusion);
context.AddBlock(BlockFields.SurfaceDescription.MapRightTopBack);
context.AddBlock(BlockFields.SurfaceDescription.MapLeftBottomFront);
context.AddBlock(BlockFields.SurfaceDescription.AbsorptionStrength, useColorAbsorption || target.allowMaterialOverride);
// when the surface options are material controlled, we must show all of these blocks
// when target controlled, we can cull the unnecessary blocks
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 using material control, add the material property to control workflow mode
if (target.allowMaterialOverride)
{
collector.AddFloatProperty(Property.CastShadows, target.castShadows ? 1.0f : 0.0f);
collector.AddToggleProperty(Property.ReceiveShadows, target.receiveShadows);
// setup properties using the defaults
collector.AddFloatProperty(Property.SurfaceType, (float)target.surfaceType);
collector.AddFloatProperty(Property.BlendMode, (float)target.alphaMode);
collector.AddFloatProperty(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.SrcBlendAlpha, 1.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.DstBlendAlpha, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque));
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.CullMode, (float)target.renderFace); // render face enum is designed to directly pass as a cull mode
bool enableAlphaToMask = (target.alphaClip && (target.surfaceType == SurfaceType.Opaque));
collector.AddFloatProperty(Property.AlphaToMask, enableAlphaToMask ? 1.0f : 0.0f);
collector.AddToggleProperty(SixWayProperties.UseColorAbsorption, useColorAbsorption);
}
// 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)
{
var universalTarget = (target as UniversalTarget);
universalTarget.AddDefaultMaterialOverrideGUI(ref context, onChange, registerUndo);
universalTarget.AddDefaultSurfacePropertiesGUI(ref context, onChange, registerUndo, showReceiveShadows: true);
context.AddProperty("Use Color Absorption", new Toggle() { value = useColorAbsorption }, (evt) =>
{
if (Equals(useColorAbsorption, evt.newValue))
return;
registerUndo("Change Use Color Absorption");
useColorAbsorption = evt.newValue;
onChange();
});
}
protected override int ComputeMaterialNeedsUpdateHash()
{
int hash = base.ComputeMaterialNeedsUpdateHash();
hash = hash * 23 + target.allowMaterialOverride.GetHashCode();
return hash;
}
#region SubShader
static class SubShaders
{
const string kSixWayMaterialTypeTag = "\"UniversalMaterialType\" = \"SixWayLit\"";
public static SubShaderDescriptor SixWaySubShader(UniversalTarget target, string renderType, string renderQueue, string disableBatchingTag, bool useColorAbsorption)
{
SubShaderDescriptor result = new SubShaderDescriptor()
{
pipelineTag = UniversalTarget.kPipelineTag,
customTags = kSixWayMaterialTypeTag,
renderType = renderType,
renderQueue = renderQueue,
disableBatchingTag = disableBatchingTag,
generatesPreview = true,
passes = new PassCollection()
};
result.passes.Add(SixWayPasses.ForwardOnly(target, CoreBlockMasks.Vertex, SixWayBlockMasks.FragmentLit, CorePragmas.Forward, SixWayKeywords.Forward, useColorAbsorption));
// cull the shadowcaster pass if we know it will never be used
if (target.castShadows || target.allowMaterialOverride)
result.passes.Add(PassVariant(CorePasses.ShadowCaster(target), CorePragmas.Instanced));
if (target.mayWriteDepth)
result.passes.Add(PassVariant(CorePasses.DepthOnly(target), CorePragmas.Instanced));
result.passes.Add(PassVariant(SixWayPasses.Meta(target), CorePragmas.Default));
// Currently neither of these passes (selection/picking) can be last for the game view for
// UI shaders to render correctly. Verify [1352225] before changing this order.
result.passes.Add(PassVariant(CorePasses.SceneSelection(target), CorePragmas.Default));
result.passes.Add(PassVariant(CorePasses.ScenePicking(target), CorePragmas.Default));
return result;
}
}
#endregion
#region Passes
static class SixWayPasses
{
static void AddReceiveShadowsControlToPass(ref PassDescriptor pass, UniversalTarget target, bool receiveShadows)
{
if (target.allowMaterialOverride)
pass.keywords.Add(SixWayKeywords.ReceiveShadowsOff);
else if (!receiveShadows)
pass.defines.Add(SixWayKeywords.ReceiveShadowsOff, 1);
}
static void AddColorAbsorptionControlToPass(ref PassDescriptor pass, UniversalTarget target,
bool useColorAbsorption)
{
if (target.allowMaterialOverride)
pass.keywords.Add(SixWayKeywords.UseColorAbsorption);
else if (useColorAbsorption)
pass.defines.Add(SixWayKeywords.UseColorAbsorption, 1);
}
static StructDescriptor ForwardVaryings
{
get
{
var baseVaryingsDescriptor = UniversalStructs.Varyings;
FieldDescriptor[] varyingsDescriptorFields =
new FieldDescriptor[baseVaryingsDescriptor.fields.Length + 3];
varyingsDescriptorFields[0] = Varyings.diffuseGIData0;
varyingsDescriptorFields[1] = Varyings.diffuseGIData1;
varyingsDescriptorFields[2] = Varyings.diffuseGIData2;
baseVaryingsDescriptor.fields.CopyTo(varyingsDescriptorFields,3);
baseVaryingsDescriptor.fields = varyingsDescriptorFields;
return baseVaryingsDescriptor;
}
}
static readonly StructCollection ForwardStructCollection = new StructCollection
{
{ Structs.Attributes },
{ ForwardVaryings },
{ Structs.SurfaceDescriptionInputs },
{ Structs.VertexDescriptionInputs },
};
public static PassDescriptor ForwardOnly(
UniversalTarget target,
BlockFieldDescriptor[] vertexBlocks,
BlockFieldDescriptor[] pixelBlocks,
PragmaCollection pragmas,
KeywordCollection keywords,
bool useColorAbsorption)
{
var result = new PassDescriptor
{
// Definition
displayName = "Universal Forward Only",
referenceName = "SHADERPASS_FORWARDONLY",
lightMode = "UniversalForwardOnly",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = vertexBlocks,
validPixelBlocks = pixelBlocks,
// Fields
structs = ForwardStructCollection,
requiredFields = SixWayRequiredFields.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.UberSwitchedRenderState(target),
pragmas = pragmas,
defines = new DefineCollection { CoreDefines.UseFragmentFog },
keywords = new KeywordCollection { keywords },
includes = new IncludeCollection { SixWayIncludes.Forward },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddTargetSurfaceControlsToPass(ref result, target);
CorePasses.AddAlphaToMaskControlToPass(ref result, target);
AddReceiveShadowsControlToPass(ref result, target, target.receiveShadows);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
AddColorAbsorptionControlToPass(ref result, target, useColorAbsorption);
return result;
}
public static PassDescriptor Meta(UniversalTarget target)
{
var result = new PassDescriptor()
{
// Definition
displayName = "Meta",
referenceName = "SHADERPASS_META",
lightMode = "Meta",
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = SixWayBlockMasks.FragmentMeta,
// Fields
structs = CoreStructCollections.Default,
requiredFields = SixWayRequiredFields.Meta,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.Meta,
pragmas = CorePragmas.Default,
defines = new DefineCollection() { CoreDefines.UseFragmentFog },
keywords = new KeywordCollection() { CoreKeywordDescriptors.EditorVisualization },
includes = SixWayIncludes.Meta,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddAlphaClipControlToPass(ref result, target);
return result;
}
}
#endregion
#region PortMasks
static class SixWayBlockMasks
{
public static readonly BlockFieldDescriptor[] FragmentLit = new BlockFieldDescriptor[]
{
BlockFields.SurfaceDescription.BaseColor,
BlockFields.SurfaceDescription.MapRightTopBack,
BlockFields.SurfaceDescription.MapLeftBottomFront,
BlockFields.SurfaceDescription.AbsorptionStrength,
BlockFields.SurfaceDescription.Emission,
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,
};
}
#endregion
#region RequiredFields
static class SixWayRequiredFields
{
public static readonly FieldCollection Forward = new FieldCollection()
{
StructFields.Attributes.uv1,
StructFields.Attributes.uv2,
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS,
StructFields.Varyings.tangentWS, // needed for vertex lighting
UniversalStructFields.Varyings.staticLightmapUV,
UniversalStructFields.Varyings.dynamicLightmapUV,
UniversalStructFields.Varyings.sh,
UniversalStructFields.Varyings.probeOcclusion,
UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency
UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency
Varyings.diffuseGIData0,
Varyings.diffuseGIData1,
Varyings.diffuseGIData2,
};
public static readonly FieldCollection Meta = new FieldCollection()
{
StructFields.Attributes.positionOS,
StructFields.Attributes.normalOS,
StructFields.Attributes.uv0, //
StructFields.Attributes.uv1, // needed for meta vertex position
StructFields.Attributes.uv2, // needed for meta UVs
StructFields.Attributes.instanceID, // needed for rendering instanced terrain
StructFields.Varyings.positionCS,
StructFields.Varyings.texCoord0, // needed for meta UVs
StructFields.Varyings.texCoord1, // VizUV
StructFields.Varyings.texCoord2, // LightCoord
};
}
#endregion
#region Defines
public static class SixWayProperties
{
public static readonly string UseColorAbsorption = "_UseColorAbsorption";
}
#endregion
#region Keywords
static class SixWayKeywords
{
public static readonly KeywordDescriptor ReceiveShadowsOff = new KeywordDescriptor()
{
displayName = "Receive Shadows Off",
referenceName = ShaderKeywordStrings._RECEIVE_SHADOWS_OFF,
type = KeywordType.Boolean,
definition = KeywordDefinition.ShaderFeature,
scope = KeywordScope.Local,
};
public static readonly KeywordDescriptor UseColorAbsorption = new KeywordDescriptor()
{
displayName = "Use Color Absorption",
referenceName = "_SIX_WAY_COLOR_ABSORPTION",
type = KeywordType.Boolean,
definition = KeywordDefinition.ShaderFeature,
scope = KeywordScope.Local,
stages = KeywordShaderStage.Fragment
};
public static readonly KeywordCollection Forward = new KeywordCollection
{
{ CoreKeywordDescriptors.MainLightShadows },
{ CoreKeywordDescriptors.AdditionalLights },
{ CoreKeywordDescriptors.AdditionalLightShadows },
{ CoreKeywordDescriptors.ShadowsSoft },
{ CoreKeywordDescriptors.ShadowsShadowmask },
{ CoreKeywordDescriptors.LightLayers },
{ CoreKeywordDescriptors.DebugDisplay },
{ CoreKeywordDescriptors.LightCookies },
{ CoreKeywordDescriptors.ClusterLightLoop },
};
}
#endregion
#region Includes
static class SixWayIncludes
{
const string kShadows = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl";
const string kMetaInput = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/MetaInput.hlsl";
const string kForwardPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SixWayForwardPass.hlsl";
const string kLightingMetaPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl";
const string kSixWayLighting = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SixWayLighting.hlsl";
public static readonly IncludeCollection Forward = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.DOTSPregraph },
{ CoreIncludes.WriteRenderLayersPregraph },
{ CoreIncludes.ProbeVolumePregraph },
{ CoreIncludes.CorePregraph },
{ kShadows, IncludeLocation.Pregraph },
{ CoreIncludes.ShaderGraphPregraph },
{ CoreIncludes.DBufferPregraph },
// Post-graph
{ kSixWayLighting, IncludeLocation.Postgraph},
{ CoreIncludes.CorePostgraph },
{ kForwardPass, IncludeLocation.Postgraph },
};
public static readonly IncludeCollection Meta = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
{ kMetaInput, IncludeLocation.Pregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kLightingMetaPass, IncludeLocation.Postgraph },
};
}
#endregion
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 56722ba5606e4941bf34fc2305532cd4
timeCreated: 1676459765

View File

@@ -0,0 +1,141 @@
using UnityEngine;
using UnityEditor.ShaderGraph;
using static Unity.Rendering.Universal.ShaderUtils;
using UnityEditor.ShaderGraph.Internal;
#if HAS_VFX_GRAPH
using UnityEditor.VFX;
#endif
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
abstract class UniversalSubTarget : SubTarget<UniversalTarget>, IHasMetadata
#if HAS_VFX_GRAPH
, IRequireVFXContext
#endif
{
static readonly GUID kSourceCodeGuid = new GUID("92228d45c1ff66740bfa9e6d97f7e280"); // UniversalSubTarget.cs
public override void Setup(ref TargetSetupContext context)
{
context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
}
protected abstract ShaderID shaderID { get; }
#if HAS_VFX_GRAPH
// VFX Properties
VFXContext m_ContextVFX = null;
VFXTaskCompiledData m_TaskDataVFX;
protected bool TargetsVFX() => m_ContextVFX != null;
public void ConfigureContextData(VFXContext context, VFXTaskCompiledData data)
{
m_ContextVFX = context;
m_TaskDataVFX = data;
}
#endif
protected SubShaderDescriptor PostProcessSubShader(SubShaderDescriptor subShaderDescriptor)
{
#if HAS_VFX_GRAPH
if (TargetsVFX())
return VFXSubTarget.PostProcessSubShader(subShaderDescriptor, m_ContextVFX, m_TaskDataVFX);
#endif
return subShaderDescriptor;
}
public override void GetFields(ref TargetFieldContext context)
{
#if HAS_VFX_GRAPH
if (TargetsVFX())
VFXSubTarget.GetFields(ref context, m_ContextVFX);
#endif
}
public virtual string identifier => GetType().Name;
public virtual ScriptableObject GetMetadataObject(GraphDataReadOnly graphData)
{
var urpMetadata = ScriptableObject.CreateInstance<UniversalMetadata>();
urpMetadata.shaderID = shaderID;
urpMetadata.alphaMode = target.alphaMode;
if (shaderID != ShaderID.SG_SpriteLit && shaderID != ShaderID.SG_SpriteUnlit)
{
urpMetadata.allowMaterialOverride = target.allowMaterialOverride;
urpMetadata.surfaceType = target.surfaceType;
urpMetadata.castShadows = target.castShadows;
urpMetadata.hasVertexModificationInMotionVector = target.additionalMotionVectorMode != AdditionalMotionVectorMode.None || graphData.AnyVertexAnimationActive();
}
else
{
//Ignore unsupported settings in SpriteUnlit/SpriteLit
urpMetadata.allowMaterialOverride = false;
urpMetadata.surfaceType = SurfaceType.Transparent;
urpMetadata.castShadows = false;
urpMetadata.hasVertexModificationInMotionVector = false;
}
urpMetadata.isVFXCompatible = graphData.IsVFXCompatible();
return urpMetadata;
}
private int lastMaterialNeedsUpdateHash = 0;
protected virtual int ComputeMaterialNeedsUpdateHash() => 0;
public override object saveContext
{
get
{
int hash = ComputeMaterialNeedsUpdateHash();
bool needsUpdate = hash != lastMaterialNeedsUpdateHash;
if (needsUpdate)
lastMaterialNeedsUpdateHash = hash;
return new UniversalShaderGraphSaveContext { updateMaterials = needsUpdate };
}
}
}
internal static class SubShaderUtils
{
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,
displayName = referenceName,
overrideReferenceName = referenceName,
});
}
internal static void AddToggleProperty(this PropertyCollector collector, string referenceName, bool defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare)
{
collector.AddShaderProperty(new BooleanShaderProperty
{
value = defaultValue,
hidden = true,
overrideHLSLDeclaration = true,
hlslDeclarationOverride = declarationType,
displayName = referenceName,
overrideReferenceName = referenceName,
});
}
// 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: 92228d45c1ff66740bfa9e6d97f7e280
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@@ -0,0 +1,442 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Legacy;
using static UnityEditor.Rendering.Universal.ShaderGraph.SubShaderUtils;
using static Unity.Rendering.Universal.ShaderUtils;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
sealed class UniversalUnlitSubTarget : UniversalSubTarget, ILegacyTarget
{
static readonly GUID kSourceCodeGuid = new GUID("97c3f7dcb477ec842aa878573640313a"); // UniversalUnlitSubTarget.cs
public override int latestVersion => 2;
public UniversalUnlitSubTarget()
{
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);
base.Setup(ref context);
var universalRPType = typeof(UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset);
if (!context.HasCustomEditorForRenderPipeline(universalRPType))
{
var gui = typeof(ShaderGraphUnlitGUI);
#if HAS_VFX_GRAPH
if (TargetsVFX())
gui = typeof(VFXShaderGraphUnlitGUI);
#endif
context.AddCustomEditorForRenderPipeline(gui.FullName, universalRPType);
}
// Process SubShaders
context.AddSubShader(PostProcessSubShader(SubShaders.Unlit(target, target.renderType, target.renderQueue, target.disableBatching)));
}
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.SurfaceType, (float)target.surfaceType);
material.SetFloat(Property.BlendMode, (float)target.alphaMode);
material.SetFloat(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
material.SetFloat(Property.CullMode, (int)target.renderFace);
material.SetFloat(Property.CastShadows, target.castShadows ? 1.0f : 0.0f);
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)BaseShaderGUI.QueueControl.Auto);
if (IsSpacewarpSupported())
material.SetFloat(Property.XrMotionVectorsPass, 1.0f);
// call the full unlit material setup function
ShaderGraphUnlitGUI.UpdateMaterial(material, MaterialUpdateType.CreatedNewMaterial);
}
public override void GetFields(ref TargetFieldContext context)
{
base.GetFields(ref context);
}
public override void GetActiveBlocks(ref TargetActiveBlockContext context)
{
context.AddBlock(UniversalBlockFields.VertexDescription.MotionVector, target.additionalMotionVectorMode == AdditionalMotionVectorMode.Custom);
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)
{
collector.AddFloatProperty(Property.CastShadows, target.castShadows ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SurfaceType, (float)target.surfaceType);
collector.AddFloatProperty(Property.BlendMode, (float)target.alphaMode);
collector.AddFloatProperty(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector
collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector
collector.AddFloatProperty(Property.SrcBlendAlpha, 1.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.DstBlendAlpha, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque));
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.CullMode, (float)target.renderFace); // render face enum is designed to directly pass as a cull mode
bool enableAlphaToMask = (target.alphaClip && (target.surfaceType == SurfaceType.Opaque));
collector.AddFloatProperty(Property.AlphaToMask, enableAlphaToMask ? 1.0f : 0.0f);
}
// 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);
if (IsSpacewarpSupported())
collector.AddFloatProperty(Property.XrMotionVectorsPass, 1.0f);
}
public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action<String> registerUndo)
{
var universalTarget = (target as UniversalTarget);
universalTarget.AddDefaultMaterialOverrideGUI(ref context, onChange, registerUndo);
universalTarget.AddDefaultSurfacePropertiesGUI(ref context, onChange, registerUndo, showReceiveShadows: false);
}
public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary<BlockFieldDescriptor, int> blockMap)
{
blockMap = null;
if (!(masterNode is UnlitMasterNode1 unlitMasterNode))
return false;
// Set blockmap
blockMap = new Dictionary<BlockFieldDescriptor, int>()
{
{ BlockFields.VertexDescription.Position, 9 },
{ BlockFields.VertexDescription.Normal, 10 },
{ BlockFields.VertexDescription.Tangent, 11 },
{ BlockFields.SurfaceDescription.BaseColor, 0 },
{ BlockFields.SurfaceDescription.Alpha, 7 },
{ BlockFields.SurfaceDescription.AlphaClipThreshold, 8 },
};
return true;
}
internal override void OnAfterParentTargetDeserialized()
{
Assert.IsNotNull(target);
if (this.sgVersion < latestVersion)
{
// Upgrade old incorrect Premultiplied blend (with alpha multiply in shader) into
// equivalent Alpha blend mode for backwards compatibility.
if (this.sgVersion < 1)
{
if (target.alphaMode == AlphaMode.Premultiply)
{
target.alphaMode = AlphaMode.Alpha;
}
}
ChangeVersion(latestVersion);
}
}
#region SubShader
static class SubShaders
{
public static SubShaderDescriptor Unlit(UniversalTarget target, string renderType, string renderQueue, string disableBatchingTag)
{
var result = new SubShaderDescriptor()
{
pipelineTag = UniversalTarget.kPipelineTag,
customTags = UniversalTarget.kUnlitMaterialTypeTag,
renderType = renderType,
renderQueue = renderQueue,
disableBatchingTag = disableBatchingTag,
generatesPreview = true,
passes = new PassCollection()
};
result.passes.Add(UnlitPasses.Forward(target, UnlitKeywords.Forward));
if (target.mayWriteDepth)
result.passes.Add(PassVariant(CorePasses.DepthOnly(target), CorePragmas.Instanced));
if (target.alwaysRenderMotionVectors)
result.customTags = string.Concat(result.customTags, " ", UniversalTarget.kAlwaysRenderMotionVectorsTag);
result.passes.Add(PassVariant(CorePasses.MotionVectors(target), CorePragmas.MotionVectors));
if (IsSpacewarpSupported())
result.passes.Add(PassVariant(CorePasses.XRMotionVectors(target), CorePragmas.XRMotionVectors));
result.passes.Add(PassVariant(UnlitPasses.DepthNormalOnly(target), CorePragmas.Instanced));
if (target.castShadows || target.allowMaterialOverride)
result.passes.Add(PassVariant(CorePasses.ShadowCaster(target), CorePragmas.Instanced));
// Fill GBuffer with color and normal for custom GBuffer use cases.
result.passes.Add(UnlitPasses.GBuffer(target));
// Currently neither of these passes (selection/picking) can be last for the game view for
// UI shaders to render correctly. Verify [1352225] before changing this order.
result.passes.Add(PassVariant(CorePasses.SceneSelection(target), CorePragmas.Default));
result.passes.Add(PassVariant(CorePasses.ScenePicking(target), CorePragmas.Default));
return result;
}
}
#endregion
#region Pass
static class UnlitPasses
{
public static PassDescriptor Forward(UniversalTarget target, KeywordCollection keywords)
{
var result = new PassDescriptor
{
// Definition
displayName = "Universal Forward",
referenceName = "SHADERPASS_UNLIT",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = CoreBlockMasks.FragmentColorAlpha,
// Fields
structs = CoreStructCollections.Default,
requiredFields = UnlitRequiredFields.Unlit,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.UberSwitchedRenderState(target),
pragmas = CorePragmas.Forward,
defines = new DefineCollection { CoreDefines.UseFragmentFog },
keywords = new KeywordCollection { keywords },
includes = new IncludeCollection { UnlitIncludes.Forward },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddTargetSurfaceControlsToPass(ref result, target);
CorePasses.AddAlphaToMaskControlToPass(ref result, target);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
public static PassDescriptor DepthNormalOnly(UniversalTarget target)
{
var result = new PassDescriptor
{
// Definition
displayName = "DepthNormalsOnly",
referenceName = "SHADERPASS_DEPTHNORMALSONLY",
lightMode = "DepthNormalsOnly",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = UnlitBlockMasks.FragmentDepthNormals,
// Fields
structs = CoreStructCollections.Default,
requiredFields = UnlitRequiredFields.DepthNormalsOnly,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.DepthNormalsOnly(target),
pragmas = CorePragmas.Forward,
defines = new DefineCollection(),
keywords = new KeywordCollection { CoreKeywordDescriptors.GBufferNormalsOct },
includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddTargetSurfaceControlsToPass(ref result, target);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
// Deferred only in SM4.5
// GBuffer fill for consistency.
public static PassDescriptor GBuffer(UniversalTarget target)
{
var result = new PassDescriptor
{
// Definition
displayName = "GBuffer",
referenceName = "SHADERPASS_GBUFFER",
lightMode = "UniversalGBuffer",
useInPreview = true,
// Template
passTemplatePath = UniversalTarget.kUberTemplatePath,
sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories,
// Port Mask
validVertexBlocks = CoreBlockMasks.Vertex,
validPixelBlocks = CoreBlockMasks.FragmentColorAlpha,
// Fields
structs = CoreStructCollections.Default,
requiredFields = UnlitRequiredFields.GBuffer,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.UberSwitchedRenderState(target),
pragmas = CorePragmas.GBuffer,
defines = new DefineCollection(),
keywords = new KeywordCollection { UnlitKeywords.GBuffer },
includes = new IncludeCollection { UnlitIncludes.GBuffer },
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
};
CorePasses.AddTargetSurfaceControlsToPass(ref result, target);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
return result;
}
#region PortMasks
static class UnlitBlockMasks
{
public static readonly BlockFieldDescriptor[] FragmentDepthNormals = new BlockFieldDescriptor[]
{
BlockFields.SurfaceDescription.NormalWS,
BlockFields.SurfaceDescription.Alpha,
BlockFields.SurfaceDescription.AlphaClipThreshold,
};
}
#endregion
#region RequiredFields
static class UnlitRequiredFields
{
public static readonly FieldCollection Unlit = new FieldCollection()
{
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS
};
public static readonly FieldCollection DepthNormalsOnly = new FieldCollection()
{
StructFields.Varyings.normalWS,
};
public static readonly FieldCollection GBuffer = new FieldCollection()
{
StructFields.Varyings.positionWS,
StructFields.Varyings.normalWS,
UniversalStructFields.Varyings.sh, // Satisfy !LIGHTMAP_ON requirements.
UniversalStructFields.Varyings.probeOcclusion,
};
}
#endregion
}
#endregion
#region Keywords
static class UnlitKeywords
{
public static readonly KeywordCollection Forward = new KeywordCollection()
{
// This contain lightmaps because without a proper custom lighting solution in Shadergraph,
// people start with the unlit then add lightmapping nodes to it.
// If we removed lightmaps from the unlit target this would ruin a lot of peoples days.
CoreKeywordDescriptors.StaticLightmap,
CoreKeywordDescriptors.DirectionalLightmapCombined,
CoreKeywordDescriptors.UseLegacyLightmaps,
CoreKeywordDescriptors.LightmapBicubicSampling,
CoreKeywordDescriptors.SampleGI,
CoreKeywordDescriptors.DBuffer,
CoreKeywordDescriptors.DebugDisplay,
CoreKeywordDescriptors.ScreenSpaceAmbientOcclusion,
};
public static readonly KeywordCollection GBuffer = new KeywordCollection
{
CoreKeywordDescriptors.DBuffer,
CoreKeywordDescriptors.ScreenSpaceAmbientOcclusion,
CoreKeywordDescriptors.RenderPassEnabled,
CoreKeywordDescriptors.GBufferNormalsOct,
CoreKeywordDescriptors.ShadowsShadowmask
};
}
#endregion
#region Includes
static class UnlitIncludes
{
const string kUnlitPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl";
const string kUnlitGBufferPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitGBufferPass.hlsl";
public static IncludeCollection Forward = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.DOTSPregraph },
{ CoreIncludes.FogPregraph },
{ CoreIncludes.WriteRenderLayersPregraph },
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
{ CoreIncludes.DBufferPregraph },
{ CoreIncludes.WriteRenderLayersPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kUnlitPass, IncludeLocation.Postgraph },
};
public static IncludeCollection GBuffer = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.DOTSPregraph },
{ CoreIncludes.CorePregraph },
{ CoreIncludes.ShaderGraphPregraph },
{ CoreIncludes.DBufferPregraph },
{ CoreIncludes.WriteRenderLayersPregraph },
// Post-graph
{ CoreIncludes.CorePostgraph },
{ kUnlitGBufferPass, IncludeLocation.Postgraph },
};
}
#endregion
}
}

View File

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

View File

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

View File

@@ -0,0 +1,144 @@
Pass
{
$splice(PassName)
Tags
{
$splice(LightMode)
}
// Render State
$splice(RenderState)
// Debug
$splice(Debug)
// --------------------------------------------------
// Pass
HLSLPROGRAM
// Pragmas
$splice(PassPragmas)
// Keywords
$splice(PassKeywords)
$splice(GraphKeywords)
// Defines
$features.graphVFX: #define HAVE_VFX_MODIFICATION
$Normal: #define _NORMALMAP 1
$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
$Attributes.instanceID: #define ATTRIBUTES_NEED_INSTANCEID
$VertexDescriptionInputs.TimeParameters: #define GRAPH_VERTEX_USES_TIME_PARAMETERS_INPUT
$VertexDescription.Normal: #define FEATURES_GRAPH_VERTEX_NORMAL_OUTPUT
$VertexDescription.Tangent: #define FEATURES_GRAPH_VERTEX_TANGENT_OUTPUT
$VertexDescription.MotionVector: #define FEATURES_GRAPH_VERTEX_MOTION_VECTOR_OUTPUT
$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.elementToWorld0: #define VARYINGS_NEED_ELEMENT_TO_WORLD
$Varyings.worldToElement0: #define VARYINGS_NEED_WORLD_TO_ELEMENT
$Varyings.bitangentWS: #define VARYINGS_NEED_BITANGENT_WS
$Varyings.screenPosition: #define VARYINGS_NEED_SCREENPOSITION
$Varyings.fogFactorAndVertexLight: #define VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
$Varyings.shadowCoord: #define VARYINGS_NEED_SHADOW_COORD
$Varyings.cullFace: #define VARYINGS_NEED_CULLFACE
$Varyings.instanceID: #define VARYINGS_NEED_INSTANCEID
$Varyings.diffuseGIData0: #define VARYINGS_NEED_SIX_WAY_DIFFUSE_GI_DATA
$features.graphVertex: #define FEATURES_GRAPH_VERTEX
$Universal.UseLegacySpriteBlocks: #define UNIVERSAL_USELEGACYSPRITEBLOCKS
$splice(PassInstancing)
$splice(GraphDefines)
// 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)
// Graph Includes
$splice(GraphIncludes)
// -- Property used by ScenePickingPass
#ifdef SCENEPICKINGPASS
float4 _SelectionID;
#endif
// -- Properties used by SceneSelectionPass
#ifdef SCENESELECTIONPASS
int _ObjectId;
int _PassValue;
#endif
// 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
#ifdef HAVE_VFX_MODIFICATION
#define VFX_SRP_ATTRIBUTES Attributes
#define VFX_SRP_VARYINGS Varyings
#define VFX_SRP_SURFACE_INPUTS SurfaceDescriptionInputs
#endif
$features.graphVFX: $include("VFXConfig.template.hlsl")
$features.graphVertex: $include("BuildVertexDescriptionInputs.template.hlsl")
$features.graphPixel: $include("SharedCode.template.hlsl")
// --------------------------------------------------
// Main
$splice(PostGraphIncludes)
// --------------------------------------------------
// Visual Effect Vertex Invocations
#ifdef HAVE_VFX_MODIFICATION
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/VisualEffectVertex.hlsl"
#endif
ENDHLSL
}

View File

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

View File

@@ -0,0 +1,90 @@
SurfaceDescriptionInputs BuildSurfaceDescriptionInputs(Varyings input)
{
SurfaceDescriptionInputs output;
ZERO_INITIALIZE(SurfaceDescriptionInputs, output);
#ifdef HAVE_VFX_MODIFICATION
#if VFX_USE_GRAPH_VALUES
uint instanceActiveIndex = asuint(UNITY_ACCESS_INSTANCED_PROP(PerInstance, _InstanceActiveIndex));
$splice(VFXLoadGraphValues)
#endif
$splice(VFXSetFragInputs)
$SurfaceDescriptionInputs.elementToWorld: BuildElementToWorld(input);
$SurfaceDescriptionInputs.worldToElement: BuildWorldToElement(input);
#endif
$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 pr eserve 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) ? (_ScaledScreenParams.y - input.positionCS.y) : input.positionCS.y);
#else
$SurfaceDescriptionInputs.PixelPosition: output.PixelPosition = float2(input.positionCS.x, (_ProjectionParams.x > 0) ? (_ScaledScreenParams.y - input.positionCS.y) : input.positionCS.y);
#endif
$SurfaceDescriptionInputs.NDCPosition: output.NDCPosition = output.PixelPosition.xy / _ScaledScreenParams.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;
#if UNITY_ANY_INSTANCING_ENABLED
$SurfaceDescriptionInputs.InstanceID: output.InstanceID = unity_InstanceID;
#else // TODO: XR support for procedural instancing because in this case UNITY_ANY_INSTANCING_ENABLED is not defined and instanceID is incorrect.
$SurfaceDescriptionInputs.InstanceID: output.InstanceID = input.instanceID;
#endif
$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;
}

View File

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

View File

@@ -0,0 +1,29 @@
using UnityEngine;
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
static class UniversalBlockFields
{
[GenerateBlocks("Universal Render Pipeline")]
public struct VertexDescription
{
public static string name = "VertexDescription";
public static BlockFieldDescriptor MotionVector = new BlockFieldDescriptor(VertexDescription.name, "MotionVector", "Motion Vector", "VERTEXDESCRIPTION_MOTIONVECTOR",
new Vector3Control(new Vector3(0.0f, 0.0f, 0.0f)), ShaderStage.Vertex);
}
[GenerateBlocks("Universal Render Pipeline")]
public struct SurfaceDescription
{
public static string name = "SurfaceDescription";
public static BlockFieldDescriptor SpriteMask = new BlockFieldDescriptor(SurfaceDescription.name, "SpriteMask", "Sprite Mask", "SURFACEDESCRIPTION_SPRITEMASK",
new ColorRGBAControl(new Color(1, 1, 1, 1)), ShaderStage.Fragment);
public static BlockFieldDescriptor NormalAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "NormalAlpha", "Normal Alpha", "SURFACEDESCRIPTION_NORMALALPHA",
new FloatControl(1.0f), ShaderStage.Fragment);
public static BlockFieldDescriptor MAOSAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "MAOSAlpha", "MAOS Alpha", "SURFACEDESCRIPTION_MAOSALPHA",
new FloatControl(1.0f), ShaderStage.Fragment);
}
}
}

View File

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

View File

@@ -0,0 +1,36 @@
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
internal static class UniversalFields
{
#region Tags
public const string kFeatures = "features";
public const string kSurfaceType = "SurfaceType";
public const string kBlendMode = "BlendMode";
#endregion
#region Fields
// still used by sprite targets (NOT used by lit/unlit targets anymore)
public static FieldDescriptor SurfaceOpaque = new FieldDescriptor(kSurfaceType, "Opaque", "_SURFACE_TYPE_OPAQUE 1");
public static FieldDescriptor SurfaceTransparent = new FieldDescriptor(kSurfaceType, "Transparent", "_SURFACE_TYPE_TRANSPARENT 1");
// still used by sprite targets (NOT used by lit/unlit targets anymore)
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");
// Used by lit/unlit targets
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: 95d59ef6d24484ca08922525945ef2ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,74 @@
using System;
using UnityEngine;
using Unity.Rendering.Universal;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
// This is a metadata object attached to ShaderGraph import asset results by the Universal Target
// it contains any additional information that we might want to know about the Universal shader
[Serializable]
sealed class UniversalMetadata : ScriptableObject
{
[SerializeField]
ShaderUtils.ShaderID m_ShaderID;
[SerializeField]
bool m_AllowMaterialOverride;
[SerializeField]
SurfaceType m_SurfaceType;
[SerializeField]
AlphaMode m_AlphaMode;
[SerializeField]
bool m_CastShadows;
[SerializeField]
bool m_HasVertexModificationInMotionVector;
[SerializeField]
bool m_IsVFXCompatible;
public ShaderUtils.ShaderID shaderID
{
get => m_ShaderID;
set => m_ShaderID = value;
}
public bool allowMaterialOverride
{
get => m_AllowMaterialOverride;
set => m_AllowMaterialOverride = value;
}
public SurfaceType surfaceType
{
get => m_SurfaceType;
set => m_SurfaceType = value;
}
public AlphaMode alphaMode
{
get => m_AlphaMode;
set => m_AlphaMode = value;
}
public bool castShadows
{
get => m_CastShadows;
set => m_CastShadows = value;
}
public bool hasVertexModificationInMotionVector
{
get => m_HasVertexModificationInMotionVector;
set => m_HasVertexModificationInMotionVector = value;
}
public bool isVFXCompatible
{
get => m_IsVFXCompatible;
set => m_IsVFXCompatible = value;
}
}
}

View File

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

View File

@@ -0,0 +1,39 @@
using System;
using UnityEditor;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Internal;
using UnityEditor.Rendering.Universal.ShaderGraph;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
internal static class Property
{
public static readonly string SpecularWorkflowMode = "_WorkflowMode";
public static readonly string SurfaceType = "_Surface";
public static readonly string BlendMode = "_Blend";
public static readonly string AlphaClip = "_AlphaClip";
public static readonly string AlphaToMask = "_AlphaToMask";
public static readonly string SrcBlend = "_SrcBlend";
public static readonly string DstBlend = "_DstBlend";
public static readonly string SrcBlendAlpha = "_SrcBlendAlpha";
public static readonly string DstBlendAlpha = "_DstBlendAlpha";
public static readonly string BlendModePreserveSpecular = "_BlendModePreserveSpecular";
public static readonly string ZWrite = "_ZWrite";
public static readonly string CullMode = "_Cull";
public static readonly string CastShadows = "_CastShadows";
public static readonly string ReceiveShadows = "_ReceiveShadows";
public static readonly string QueueOffset = "_QueueOffset";
// for ShaderGraph shaders only
public static readonly string ZTest = "_ZTest";
public static readonly string ZWriteControl = "_ZWriteControl";
public static readonly string QueueControl = "_QueueControl";
public static readonly string AddPrecomputedVelocity = "_AddPrecomputedVelocity";
public static readonly string XrMotionVectorsPass = "_XRMotionVectorsPass";
// Global Illumination requires some properties to be named specifically:
public static readonly string EmissionMap = "_EmissionMap";
public static readonly string EmissionColor = "_EmissionColor";
}
}

View File

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

View File

@@ -0,0 +1,28 @@
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
static class UniversalStructFields
{
public struct Varyings
{
public static string name = "Varyings";
public static FieldDescriptor staticLightmapUV = new FieldDescriptor(Varyings.name, "staticLightmapUV", "", ShaderValueType.Float2,
preprocessor: "defined(LIGHTMAP_ON)", subscriptOptions: StructFieldOptions.Optional);
public static FieldDescriptor dynamicLightmapUV = new FieldDescriptor(Varyings.name, "dynamicLightmapUV", "", ShaderValueType.Float2,
preprocessor: "defined(DYNAMICLIGHTMAP_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, preprocessor: "defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)");
public static FieldDescriptor probeOcclusion = new FieldDescriptor(Varyings.name, "probeOcclusion", "", ShaderValueType.Float4,
preprocessor: "defined(USE_APV_PROBE_OCCLUSION)", 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: aab14984951054bfc8673ef85a1b5017
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,37 @@
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.Universal.ShaderGraph
{
static class UniversalStructs
{
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,
UniversalStructFields.Varyings.staticLightmapUV,
UniversalStructFields.Varyings.dynamicLightmapUV,
UniversalStructFields.Varyings.sh,
UniversalStructFields.Varyings.probeOcclusion,
UniversalStructFields.Varyings.fogFactorAndVertexLight,
UniversalStructFields.Varyings.shadowCoord,
StructFields.Varyings.instanceID,
UniversalStructFields.Varyings.stereoTargetEyeIndexAsBlendIdx0,
UniversalStructFields.Varyings.stereoTargetEyeIndexAsRTArrayIdx,
StructFields.Varyings.cullFace,
}
};
}
}

View File

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