Added terrain and basic terrain textures

This commit is contained in:
2026-06-12 20:57:07 +01:00
parent 65e0008b90
commit b86da7a45a
197 changed files with 20733 additions and 0 deletions

8
Assets/Filamented.meta Normal file
View File

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

View File

@ -0,0 +1,106 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: CrossStandardTest
m_Shader: {fileID: 4800000, guid: 9829e18681954944a8b25de9b080a0b6, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 2800000, guid: 71df313bf94a79746a4688af6ae80017, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DFG:
m_Texture: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 2800000, guid: b582b17f0e346c24188b4e86cc8950b3, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 6f2555b25fa89524f9431086d0e2e8c7, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 2800000, guid: 0329f88e1a406644c97d0ec094ab70e2, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 2800000, guid: c3b93488fd8a11847ad12e8710e6866a, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _RNM0:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _RNM1:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _RNM2:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlphaToMaskMode: 0
- _Bakery: 0
- _BakeryVertexLM: 0
- _BumpScale: 1
- _BumpShadowHardness: 50
- _BumpShadowHeightScale: 0.2
- _CullMode: 2
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _ExposureOcclusion: 0.2
- _GlossMapScale: 1
- _Glossiness: 1
- _GlossyReflections: 1
- _LTCGI: 0
- _LightmapSpecular: 1
- _LightmapSpecularMaxSmoothness: 1
- _Metallic: 1
- _Mode: 0
- _NormalMapShadows: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
- _specularAntiAliasingThreshold: 0.25
- _specularAntiAliasingVariance: 0.15
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 2.7921572, g: 2.729412, b: 2.227451, a: 1}

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7e3e2734c20f8704986e4b44f7950257
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@ -0,0 +1,347 @@
/*
Filamented triplanar example.
*/
Shader "Silent/Filamented Extras/Filamented Fractal Sampling"
{
Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
[Space]
[NoScaleOffset][Normal] _BumpMap("Normal", 2D) = "bump" {}
_BumpScale("Normal Scale", Float) = 1
[Space]
[NoScaleOffset]_MOESMap("MOES Map", 2D) = "white" {}
[NoScaleOffset]_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_Emission("Emission Power", Float) = 0
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[Space]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
}
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
//Samples at three scales, interpolating between them (with mipmapping)
float4 fractal_texture_mip(sampler2D tex, float2 uv, float depth)
{
//Find the pixel level of detail
float LOD = log(depth);
//Round LOD down
float LOD_floor = floor(LOD);
//Compute the fract part for interpolating
float LOD_fract = LOD - LOD_floor;
//Compute scaled uvs
float2 uv1 = uv / exp(LOD_floor - 1.0);
float2 uv2 = uv / exp(LOD_floor + 0.0);
float2 uv3 = uv / exp(LOD_floor + 1.0);
//Compute continous derivitives
float2 dx = ddx(uv) / depth * exp(1.0);
float2 dy = ddy(uv) / depth * exp(1.0);
//Sample at 3 scales
float4 tex0 = tex2Dgrad(tex, uv1, dx, dy);
float4 tex1 = tex2Dgrad(tex, uv2, dx, dy);
float4 tex2 = tex2Dgrad(tex, uv3, dx, dy);
//Blend samples together
return (tex1 + lerp(tex0, tex2, LOD_fract)) * 0.5;
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_pos)
{
float3x3 tangentToWorldOnly = float3x3(tangentToWorld[0].xyz, tangentToWorld[1].xyz, tangentToWorld[2].xyz);
float3 normal = mul ( float3( 0, 0, 1 ), tangentToWorldOnly );
float4 baseColor = 0;
fixed3 normalTangent = 0.0f;
float4 packedMap = 0;
float depth = LinearEyeDepth(i_pos.z);
baseColor = fractal_texture_mip( _MainTex, i_tex, depth) * _Color;
normalTangent = UnpackScaleNormal(fractal_texture_mip( _BumpMap, i_tex, depth), _BumpScale);
packedMap = fractal_texture_mip( _MOESMap, i_tex, depth);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, i.pos);
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, i.pos);
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
// Meta not implemented
UsePass "Standard/META"
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: 9dabe5d8b925aff4a8ce5e93b20bd940
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,397 @@
Shader "Silent/Filamented Extras/Filamented Glinty"
{
Properties
{
[CheckDFGTexture]
[ScaleOffset][SingleLine(_Color)]_MainTex("Albedo", 2D) = "white" {}
[HideInInspector]_Color("Color", Color) = (1,1,1,1)
[Space]
[SingleLine(_BumpScale)][Normal] _BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[Space]
[SingleLine]_MOESMap("MOES Map", 2D) = "white" {}
[Space]
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_Emission("Emission Power", Float) = 0
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[Header(Glint Properties)][Space]
_SpecularGlintSize("Glint Size", Range(0, 1)) = 0.5
_SpecularGlintDensity("Glint Density", Range(0, 1)) = 0.5
[Header(Clear Coat Properties)][Space]
[Toggle(_USE_CLEARCOAT)]_ClearCoatMode("Clear Coat", Float) = 0
[IfDef(_USE_CLEARCOAT)][SingleLine]_ClearCoatMap("Clear Coat Map (R: Intensity, G: Roughness)", 2D) = "white" {}
[IfDef(_USE_CLEARCOAT)]_ClearCoat("Clear Coat Intensity", Range(0, 1)) = 0.0
[IfDef(_USE_CLEARCOAT)]_ClearCoatRoughness("Clear Coat Roughness", Range(0, 1)) = 0.0
[Header(System Settings)][Space]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[Toggle(_ALPHATEST_ON)]_AtoCmode("Cutout Transparency", Float) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
}
HLSLINCLUDE
#define fixed half
#define fixed2 half2
#define fixed3 half3
#define fixed4 half4
ENDHLSL
HLSLINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
#if defined(_USE_CLEARCOAT)
#define MATERIAL_HAS_CLEAR_COAT
#endif
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define MATERIAL_HAS_GLINT
// If this is set, the material will support glint specular.
// Not compatible with cloth/anisotropy.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDHLSL
HLSLINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
uniform half _SpecularGlintSize;
uniform half _SpecularGlintDensity;
#if defined(_USE_CLEARCOAT)
uniform sampler2D _ClearCoatMap;
uniform half _ClearCoat;
uniform half _ClearCoatRoughness;
#endif
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy) * _Color;
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
half internal_glint_alpha = lerp(0.001, 0.1, _SpecularGlintSize * _SpecularGlintSize);
half internal_density = pow(10.0, lerp(3.0, 9.0, _SpecularGlintDensity));
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
material.uv = i_tex.xy;
material.glintAlpha = internal_glint_alpha;
material.glintDensity = internal_density;
#if defined(_USE_CLEARCOAT)
half4 ccMap = tex2D(_ClearCoatMap, i_tex.xy);
material.clearCoat = ccMap.r * _ClearCoat;
material.clearCoatRoughness = ccMap.g * _ClearCoatRoughness;
#endif
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDHLSL
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
HLSLPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local_fragment _ _USE_CLEARCOAT
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDHLSL
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
HLSLPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local_fragment _ _USE_CLEARCOAT
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDHLSL
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
HLSLPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDHLSL
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
HLSLPROGRAM
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
// Note: If your MaterialSetup needs vertex normals, you might want to use a custom vert_meta which passes them through.
float4 dummy[3]; dummy[0] = 1.0; dummy[1] = 0.0; dummy[2] = 0.0;
material = MyMaterialSetup(i.uv, 0, 0, dummy, 0);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature ___ _DETAIL_MULX2
ENDHLSL
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: f0a1aea00313d7046ac9e997ca48e8b0
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,468 @@
Shader "Silent/Filamented Mirror Template"
{
Properties
{
[CheckDFGTexture]
[BlendModeSelector(_SrcBlend, _DstBlend, _CustomRenderQueue, _ZWrite, _AtoCmode)] _Mode ("__mode", Float) = 0.0
[HeaderEx(Base Material)]
[ScaleOffset][SingleLine(_Color)]_MainTex("Albedo", 2D) = "white" {}
[HideInInspector]_Color("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScale)][Normal] _BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[SingleLine]_MOESMap("MOES Map", 2D) = "white" {}
[Space]
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_Emission("Emission Power", Float) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_EmissionColor("Emission Tint", Color) = (1,1,1,1)
[Space]
[HeaderEx(Details)]
_DetailBlendWeight("Blend Weight", Range(0, 1)) = 1
[HideInInspector][Enum(Multiply2x, 0, Multiply, 1, Additive, 2, AlphaBlend, 3)]_DetailBlendMode("Blend Mode", Float) = 0.0
[ScaleOffset][SingleLine(_DetailBlendMode)]_MainTexDetail("Albedo Detail", 2D) = "gray" {}
[SingleLine(_BumpScaleDetail)][Normal] _BumpMapDetail("Normal Detail", 2D) = "bump" {}
[HideInInspector]_BumpScaleDetail("Normal Detail Scale", Float) = 1
[SingleLine]_MOESMapDetail("MOES Map Detail", 2D) = "white" {}
[Space]
[Toggle(_DTRIPLANAR)]_UseDTriplanar("Triplanar Detail", Float) = 0.0
_TriplanarSharp("Blending Sharpness", Range(1, 10)) = 3
[IfDef(_DTRIPLANAR)]_TriplanarTiles0x ("X Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarTiles0y ("Y Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarTiles0z ("X Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarOffset0x ("X Axis Offset", float) = 0
[IfDef(_DTRIPLANAR)]_TriplanarOffset0y ("Y Axis Offset", float) = 0
[IfDef(_DTRIPLANAR)]_TriplanarOffset0z ("X Axis Offset", float) = 0
[Space]
[HeaderEx(System)]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _CustomRenderQueue ("__rq", Float) = 1.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _AtoCmode("__atoc", Float) = 0
[HideInInspector] _ReflectionTex0("", 2D) = "white" {}
[HideInInspector] _ReflectionTex1("", 2D) = "white" {}
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
#pragma multi_compile_local _ _DTRIPLANAR
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
#define MIRROR_REFLECTION
// If this is set, the mirror reflection will be used.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
uniform sampler2D _MainTexDetail;
uniform sampler2D _MOESMapDetail;
uniform sampler2D _BumpMapDetail;
uniform half _BumpScaleDetail;
uniform half _DetailBlendMode;
uniform half _DetailBlendWeight;
uniform half4 _MainTexDetail_ST;
#ifdef _DTRIPLANAR
uniform half _TriplanarTiles0x;
uniform half _TriplanarTiles0y;
uniform half _TriplanarTiles0z;
uniform half _TriplanarOffset0x;
uniform half _TriplanarOffset0y;
uniform half _TriplanarOffset0z;
uniform half _TriplanarSharp;
#endif
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
float4 boxmap(sampler2D tex, float3 p, float3 n, float k )
{
// grab coord derivatives for texturing
float3 dpdx = ddx(p);
float3 dpdy = ddy(p);
float3 m = pow( abs(n), k );
// project+fetch
float4 x = 0.0;
if (m.x > 0) x = tex2Dgrad( tex, p.zy, dpdx.zy, dpdy.zy );
float4 y = 0.0;
if (m.y > 0) y = tex2Dgrad( tex, p.zx, dpdx.zx, dpdy.zx );
float4 z = 0.0;
if (m.z > 0) z = tex2Dgrad( tex, p.xy, dpdx.xy, dpdy.xy );
// and blend
return (x*m.x + y*m.y + z*m.z) / (m.x + m.y + m.z);
}
float3 applyDetailBlendMode(int blendOp, half3 a, half3 b, half t)
{
switch(blendOp)
{
default:
case 0: // Multiply 2x
return a * LerpWhiteTo (b * unity_ColorSpaceDouble.rgb, t);
case 1: // Multiply
return a * LerpWhiteTo (b, t);
case 2: // Additive
return a + b * t;
case 3: // Alpha Blend
return lerp(a, b, t);
}
}
float3 RNMBlendUnpacked(float3 n1, float3 n2)
{
n1 += float3( 0, 0, 1);
n2 *= float3(-1, -1, 1);
return n1*dot(n1, n2)/n1.z - n2;
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy) * _Color;
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
#if defined(_DTRIPLANAR)
float triSharp = _TriplanarSharp;
float3 triPosition = i_posWorld * float3(_TriplanarTiles0x, _TriplanarTiles0y, _TriplanarTiles0z)
+ float3(_TriplanarOffset0x, _TriplanarOffset0y, _TriplanarOffset0z);
half4 baseColorDetail = boxmap (_MainTexDetail, triPosition, tangentToWorld[2], triSharp);
half4 packedMapDetail = boxmap (_MOESMapDetail, triPosition, tangentToWorld[2], triSharp);
half3 normalTangentDetail = UnpackScaleNormal(boxmap (_BumpMapDetail, triPosition, tangentToWorld[2], triSharp), _BumpScaleDetail);
#else
float2 dUV = i_tex.xy * _MainTexDetail_ST.xy + _MainTexDetail_ST.zw;
half4 baseColorDetail = tex2D (_MainTexDetail, dUV);
half4 packedMapDetail = tex2D (_MOESMapDetail, dUV);
half3 normalTangentDetail = UnpackScaleNormal(tex2D (_BumpMapDetail, dUV), _BumpScaleDetail);
#endif
baseColor.rgb = applyDetailBlendMode(_DetailBlendMode, baseColor, baseColorDetail, _DetailBlendWeight);
normalTangent = lerp(normalTangent, RNMBlendUnpacked(normalTangent, normalTangentDetail), _DetailBlendWeight);
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend One [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
AlphaToMask Off
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
CGPROGRAM
#define REQUIRE_META_WORLDPOS
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
float4 dummy[3]; dummy[0] = 1; dummy[1] = 0; dummy[2] = 0;
material = MyMaterialSetup (i.uv, 0, 0, dummy, i.worldPos);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature ___ _DETAIL_MULX2
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,21 @@
fileFormatVersion: 2
guid: 870896c71151de24eb10da376e8cb502
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _MainTexDetail: {instanceID: 0}
- _BumpMapDetail: {instanceID: 0}
- _MOESMapDetail: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
- _ReflectionTex0: {instanceID: 0}
- _ReflectionTex1: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,389 @@
// A shader for displaying artwork in high quality, as though it
// were printed or painted onto a canvas.
Shader "Silent/Filamented Extras/Painting Canvas"
{
Properties
{
_MainTex("Main Texture", 2D) = "white" {}
[Space]
[NoScaleOffset][Normal] _BumpMap("Canvas Pattern Normal", 2D) = "bump" {}
_BumpSize("Pattern Scale", Float) = 1
_BumpScale("Pattern Intensity", Float) = 1
_BumpScaleWarp("Main Texture Canvas Intensity", Float) = 1
[Space]
[NoScaleOffset]_MOESMap("Canvas MOES Map", 2D) = "white" {}
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_Emission("Emission Power", Float) = 0
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[Space]
[Header(System)]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[Toggle(_ALPHATEST_ON)]_AtoCmode("Cutout Transparency", Float) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
}
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform float4 _MainTex_TexelSize;
uniform half _BumpSize;
uniform half _BumpScaleWarp;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
float4 bicubicFilter(sampler2D inTex, float2 texcoord, float4 texscale)
{
//#if _BICUBIC
texcoord *= texscale.zw;
float fx = frac(texcoord.x);
float fy = frac(texcoord.y);
texcoord.x -= fx;
texcoord.y -= fy;
float4 xcubic = cubic(fx);
float4 ycubic = cubic(fy);
float4 c = float4(texcoord.x - 0.5, texcoord.x + 1.5, texcoord.y - 0.5, texcoord.y + 1.5);
float4 s = float4(xcubic.x + xcubic.y, xcubic.z + xcubic.w, ycubic.x + ycubic.y, ycubic.z + ycubic.w);
float4 offset = c + float4(xcubic.y, xcubic.w, ycubic.y, ycubic.w) / s;
float4 sample0 = tex2D(inTex, float2(offset.x, offset.z) * texscale.xy);
float4 sample1 = tex2D(inTex, float2(offset.y, offset.z) * texscale.xy);
float4 sample2 = tex2D(inTex, float2(offset.x, offset.w) * texscale.xy);
float4 sample3 = tex2D(inTex, float2(offset.y, offset.w) * texscale.xy);
float sx = s.x / (s.x + s.y);
float sy = s.z / (s.z + s.w);
return lerp(
lerp(sample3, sample2, sx),
lerp(sample1, sample0, sx), sy);
//#else
return tex2D(inTex, texcoord);
//#endif
}
// https://iquilezles.org/www/articles/biplanar/biplanar.htm
// "p" point being textured
// "n" surface normal at "p"
// "k" controls the sharpness of the blending in the transitions areas
// "s" texture sampler
float4 biplanar( sampler2D sam, float3 p, float3 n, float k )
{
// grab coord derivatives for texturing
float3 dpdx = ddx(p);
float3 dpdy = ddy(p);
n = abs(n);
// determine major axis (in x; yz are following axis)
int3 ma = (n.x>n.y && n.x>n.z) ? int3(0,1,2) :
(n.y>n.z) ? int3(1,2,0) :
int3(2,0,1) ;
// determine minor axis (in x; yz are following axis)
int3 mi = (n.x<n.y && n.x<n.z) ? int3(0,1,2) :
(n.y<n.z) ? int3(1,2,0) :
int3(2,0,1) ;
// determine median axis (in x; yz are following axis)
int3 me = clamp(3 - mi - ma, 0, 2);
// project+fetch
float4 x = tex2Dgrad( sam, float2( p[ma.y], p[ma.z]),
float2(dpdx[ma.y],dpdx[ma.z]),
float2(dpdy[ma.y],dpdy[ma.z]) );
float4 y = tex2Dgrad( sam, float2( p[me.y], p[me.z]),
float2(dpdx[me.y],dpdx[me.z]),
float2(dpdy[me.y],dpdy[me.z]) );
// blend factors
float2 w = float2(n[ma.x],n[me.x]);
// make local support
w = clamp( (w-0.5773)/(1.0-0.5773), 0.0, 1.0 );
// shape transition
w = pow( w, k/8.0 );
// blend and return
return (x*w.x + y*w.y) / (w.x + w.y);
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
// Sample the UVs for the canvas bumps first. These are applied to the
// surface normal, but also the texture sampling.
float3x3 tangentToWorldOnly = float3x3(tangentToWorld[0].xyz, tangentToWorld[1].xyz, tangentToWorld[2].xyz);
float3 normal = mul ( float3( 0, 0, 1 ), tangentToWorldOnly );
half3 normalTangent = UnpackScaleNormal(biplanar(_BumpMap, i_posWorld * _BumpSize, normal, 1.0), _BumpScale);
half4 packedMap = biplanar (_MOESMap, i_posWorld * _BumpSize, normal, 1.0);
half4 baseColor = bicubicFilter (_MainTex, i_tex.xy + normalTangent * 0.01 * _BumpScaleWarp, _MainTex_TexelSize);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: a1fe9ddc772e6c846835192876484746
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,410 @@
Shader "Silent/Filamented Extras/Simple Rotate Filamented"
{
Properties
{
[CheckDFGTexture]
[BlendModeSelector(_SrcBlend, _DstBlend, _CustomRenderQueue, _ZWrite, _AtoCmode)] _Mode ("__mode", Float) = 0.0
[HeaderEx(Base Material)]
[ScaleOffset][SingleLine(_Color)]_MainTex("Albedo", 2D) = "white" {}
[HideInInspector]_Color("Color", Color) = (1,1,1,1)
[IfDef(_ALPHATEST_ON)]_Cutoff("Alpha Cutoff", Range(0, 1)) = 0.5
[SingleLine(_BumpScale)][Normal] _BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[SingleLine]_MOESMap("MOES Map", 2D) = "white" {}
[Space]
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_Emission("Emission Power", Float) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[HeaderEx(Rotation Properties)]
[ToggleUI]_MaskRotationByUV("Limit Rotation to Positive UV", Float) = 0
_RotateSpeed("Rotation Speed", Float) = 0
_RotationAxis("Rotation Axis", Vector) = (0, 0, 1, 0)
_RotationOffset("Rotation Offset", Vector) = (0, 0, 0, 0)
[ToggleUI]_RotationOffsetByWorldPos("Add Random Offset by World Position", Float) = 0
[Space]
[HeaderEx(System)]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _CustomRenderQueue ("__rq", Float) = 1.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _AtoCmode("__atoc", Float) = 0
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
#else
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
#endif
uniform half _RotateSpeed;
uniform half3 _RotationAxis;
uniform half3 _RotationOffset;
uniform float _MaskRotationByUV;
uniform float _RotationOffsetByWorldPos;
// Vertex functions are called from UnityStandardCore/Shadow.
// You can alter values here, or copy the function in and modify it.
float3x3 AngleAxis3x3(float angle, float3 axis)
{
float c, s;
sincos(angle, s, c);
float t = 1 - c;
float x = axis.x;
float y = axis.y;
float z = axis.z;
return float3x3(
t * x * x + c, t * x * y - s * z, t * x * z + s * y,
t * x * y + s * z, t * y * y + c, t * y * z - s * x,
t * x * z - s * y, t * y * z + s * x, t * z * z + c
);
}
inline float hash13(float3 p3)
{
p3 = frac(p3 * 443.8975);
p3 += dot(p3, p3.yzx + 19.19);
return frac((p3.x + p3.y) * p3.z);
}
inline void VertexCommon(inout VertexInput v)
{
bool shouldRotate = (!_MaskRotationByUV || v.uv0.x > 0);
float rotateOffset = _RotationOffsetByWorldPos * hash13(mul(unity_ObjectToWorld, float4(0, 0, 0, 1.0)));
if (shouldRotate)
{
float rotateFactor = frac(_RotateSpeed * _Time.y + rotateOffset) * UNITY_PI * 2.0;
v.vertex.xyz = mul(v.vertex.xyz - _RotationOffset, AngleAxis3x3(rotateFactor, _RotationAxis)) + _RotationOffset;
v.normal.xyz = mul(v.normal.xyz, AngleAxis3x3(rotateFactor, _RotationAxis));
#ifdef _TANGENT_TO_WORLD
v.tangent.xyz = mul(v.tangent.xyz, AngleAxis3x3(rotateFactor, _RotationAxis));
#endif
}
}
#ifndef UNITY_PASS_SHADOWCASTER
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
VertexOutputForwardBase vertBase (VertexInput v) { VertexCommon(v); return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { VertexCommon(v); return vertForwardAdd(v); }
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy) * _Color;
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend One [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
AlphaToMask Off
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCasterLocal
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
// We use Unity's shadowcaster as a base, but unfortunately it's complicated to work with.
void vertShadowCasterLocal (VertexInput v
, out float4 opos : SV_POSITION
#ifdef UNITY_STANDARD_USE_SHADOW_OUTPUT_STRUCT
, out VertexOutputShadowCaster o
#endif
#ifdef UNITY_STANDARD_USE_STEREO_SHADOW_OUTPUT_STRUCT
, out VertexOutputStereoShadowCaster os
#endif
)
{
UNITY_SETUP_INSTANCE_ID(v);
#ifdef UNITY_STANDARD_USE_STEREO_SHADOW_OUTPUT_STRUCT
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(os);
#endif
VertexCommon(v);
TRANSFER_SHADOW_CASTER_NOPOS(o,opos)
#if defined(UNITY_STANDARD_USE_SHADOW_UVS)
o.tex = TRANSFORM_TEX(v.uv0, _MainTex);
#ifdef _PARALLAXMAP
TANGENT_SPACE_ROTATION;
o.viewDirForParallax = mul (rotation, ObjSpaceViewDir(v.vertex));
#endif
#endif
}
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
// Meta not implemented
UsePass "Standard/META"
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: bb6f3dbf7de087b41886f3805bfaf97b
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,359 @@
/*
Filamented example template.
This is a template of how to use Filamented to make a simple shader
that passes its own properties through to Filament, in a manner
similar to a Unity surface shader - but with less jank.
Instead of reading multiple seperate maps, it just asks for
an albedo map, a normal map, and a MOES map.
*/
Shader "Silent/Filamented Extras/Filamented Template"
{
Properties
{
_MainTex("Albedo", 2D) = "white" {}
[Normal] _BumpMap("Normal", 2D) = "bump" {}
_BumpScale("Normal Scale", Float) = 1
[Space]
_MOESMap("MOES Map", 2D) = "white" {}
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_Emission("Emission Power", Float) = 0
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[Space]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[Toggle(_ALPHATEST_ON)]_AtoCmode("Cutout Transparency", Float) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
}
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy);
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
CGPROGRAM
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
// Note: If your MaterialSetup needs vertex normals, you might want to use a custom vert_meta which passes them through.
float4 dummy[3]; dummy[0] = 1.0; dummy[1] = 0.0; dummy[2] = 0.0;
material = MyMaterialSetup(i.uv, 0, 0, dummy, 0);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature ___ _DETAIL_MULX2
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 88e4dbdb6ade3b14da90a528eaec41f5
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,465 @@
/*
Filamented example template.
*/
Shader "Silent/Filamented Extras/Filamented Details Template"
{
Properties
{
[CheckDFGTexture]
[BlendModeSelector(_SrcBlend, _DstBlend, _CustomRenderQueue, _ZWrite, _AtoCmode)] _Mode ("__mode", Float) = 0.0
[HeaderEx(Base Material)]
[ScaleOffset][SingleLine(_Color)]_MainTex("Albedo", 2D) = "white" {}
[HideInInspector]_Color("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScale)][Normal] _BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[SingleLine]_MOESMap("MOES Map", 2D) = "white" {}
[Space]
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_Emission("Emission Power", Float) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_EmissionColor("Emission Tint", Color) = (1,1,1,1)
[Space]
[HeaderEx(Details)]
_DetailBlendWeight("Blend Weight", Range(0, 1)) = 1
[HideInInspector][Enum(Multiply2x, 0, Multiply, 1, Additive, 2, AlphaBlend, 3)]_DetailBlendMode("Blend Mode", Float) = 0.0
[ScaleOffset][SingleLine(_DetailBlendMode)]_MainTexDetail("Albedo Detail", 2D) = "gray" {}
[SingleLine(_BumpScaleDetail)][Normal] _BumpMapDetail("Normal Detail", 2D) = "bump" {}
[HideInInspector]_BumpScaleDetail("Normal Detail Scale", Float) = 1
[SingleLine]_MOESMapDetail("MOES Map Detail", 2D) = "white" {}
[Space]
[Toggle(_DTRIPLANAR)]_UseDTriplanar("Triplanar Detail", Float) = 0.0
_TriplanarSharp("Blending Sharpness", Range(1, 10)) = 3
[IfDef(_DTRIPLANAR)]_TriplanarTiles0x ("X Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarTiles0y ("Y Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarTiles0z ("X Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarOffset0x ("X Axis Offset", float) = 0
[IfDef(_DTRIPLANAR)]_TriplanarOffset0y ("Y Axis Offset", float) = 0
[IfDef(_DTRIPLANAR)]_TriplanarOffset0z ("X Axis Offset", float) = 0
[Space]
[HeaderEx(System)]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _CustomRenderQueue ("__rq", Float) = 1.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _AtoCmode("__atoc", Float) = 0
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
#pragma multi_compile_local _ _DTRIPLANAR
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
uniform sampler2D _MainTexDetail;
uniform sampler2D _MOESMapDetail;
uniform sampler2D _BumpMapDetail;
uniform half _BumpScaleDetail;
uniform half _DetailBlendMode;
uniform half _DetailBlendWeight;
uniform half4 _MainTexDetail_ST;
#ifdef _DTRIPLANAR
uniform half _TriplanarTiles0x;
uniform half _TriplanarTiles0y;
uniform half _TriplanarTiles0z;
uniform half _TriplanarOffset0x;
uniform half _TriplanarOffset0y;
uniform half _TriplanarOffset0z;
uniform half _TriplanarSharp;
#endif
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
float4 boxmap(sampler2D tex, float3 p, float3 n, float k )
{
// grab coord derivatives for texturing
float3 dpdx = ddx(p);
float3 dpdy = ddy(p);
float3 m = pow( abs(n), k );
// project+fetch
float4 x = 0.0;
if (m.x > 0) x = tex2Dgrad( tex, p.zy, dpdx.zy, dpdy.zy );
float4 y = 0.0;
if (m.y > 0) y = tex2Dgrad( tex, p.zx, dpdx.zx, dpdy.zx );
float4 z = 0.0;
if (m.z > 0) z = tex2Dgrad( tex, p.xy, dpdx.xy, dpdy.xy );
// and blend
return (x*m.x + y*m.y + z*m.z) / (m.x + m.y + m.z);
}
float3 applyDetailBlendMode(int blendOp, half3 a, half3 b, half t)
{
switch(blendOp)
{
default:
case 0: // Multiply 2x
return a * LerpWhiteTo (b * unity_ColorSpaceDouble.rgb, t);
case 1: // Multiply
return a * LerpWhiteTo (b, t);
case 2: // Additive
return a + b * t;
case 3: // Alpha Blend
return lerp(a, b, t);
}
}
float3 RNMBlendUnpacked(float3 n1, float3 n2)
{
n1 += float3( 0, 0, 1);
n2 *= float3(-1, -1, 1);
return n1*dot(n1, n2)/n1.z - n2;
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy) * _Color;
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
#if defined(_DTRIPLANAR)
float triSharp = _TriplanarSharp;
float3 triPosition = i_posWorld * float3(_TriplanarTiles0x, _TriplanarTiles0y, _TriplanarTiles0z)
+ float3(_TriplanarOffset0x, _TriplanarOffset0y, _TriplanarOffset0z);
half4 baseColorDetail = boxmap (_MainTexDetail, triPosition, tangentToWorld[2], triSharp);
half4 packedMapDetail = boxmap (_MOESMapDetail, triPosition, tangentToWorld[2], triSharp);
half3 normalTangentDetail = UnpackScaleNormal(boxmap (_BumpMapDetail, triPosition, tangentToWorld[2], triSharp), _BumpScaleDetail);
#else
float2 dUV = i_tex.xy * _MainTexDetail_ST.xy + _MainTexDetail_ST.zw;
half4 baseColorDetail = tex2D (_MainTexDetail, dUV);
half4 packedMapDetail = tex2D (_MOESMapDetail, dUV);
half3 normalTangentDetail = UnpackScaleNormal(tex2D (_BumpMapDetail, dUV), _BumpScaleDetail);
#endif
baseColor.rgb = applyDetailBlendMode(_DetailBlendMode, baseColor, baseColorDetail, _DetailBlendWeight);
normalTangent = lerp(normalTangent, RNMBlendUnpacked(normalTangent, normalTangentDetail), _DetailBlendWeight);
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend One [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
AlphaToMask Off
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
CGPROGRAM
#define REQUIRE_META_WORLDPOS
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
float4 dummy[3]; dummy[0] = 1; dummy[1] = 0; dummy[2] = 0;
material = MyMaterialSetup (i.uv, 0, 0, dummy, i.worldPos);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature ___ _DETAIL_MULX2
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,19 @@
fileFormatVersion: 2
guid: fdde3e81293f3dd4f9d7c390d4b95a5a
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _MainTexDetail: {instanceID: 0}
- _BumpMapDetail: {instanceID: 0}
- _MOESMapDetail: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,349 @@
/*
Filamented example template.
This is a template of how to use Filamented to make a simple shader
that passes its own properties through to Filament, in a manner
similar to a Unity surface shader - but with less jank.
Instead of reading multiple seperate maps, it just asks for
an albedo map, a normal map, and a MOES map.
*/
Shader "Silent/Filamented Extras/Filamented Refraction"
{
Properties
{
_MainTex("Albedo", 2D) = "white" {}
[Normal] _BumpMap("Normal", 2D) = "bump" {}
_BumpScale("Normal Scale", Float) = 1
[Space]
_MOESMap("MOES Map", 2D) = "white" {}
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_Emission("Emission Power", Float) = 0
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[Space]
_Transmission("Transmission", Range(0, 1)) = 1.0
_Absorption("Absorbtion", Color) = (0, 0, 0, 0)
_IOR("IOR", Float) = 1.5
[Space]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
}
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define HAS_REFRACTION
// If this is defined, the material supports refraction.
#define MATERIAL_HAS_TRANSMISSION
#define MATERIAL_HAS_ABSORPTION
#define MATERIAL_HAS_THICKNESS
#define MATERIAL_HAS_IOR
// These properties are controls for the refraction effect.
// REFRACTION_TYPE REFRACTION_TYPE_THIN
// MATERIAL_HAS_MICRO_THICKNESS
// Micro thickness is only supported for thin refraction.
// REFRACTION_MODE REFRACTION_MODE_SCREEN
// Set to use the screen as a refraction source, which is typically very expensive.
// REFRACTION_SOURCE _GrabPassRefraction
// REFRACTION_MULTIPLIER 1.0
// If screen refractions are enabled, you'll need to set these as well.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
// Refraction-specific settings
uniform half _Transmission;
uniform half3 _Absorption;
uniform half _IOR;
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy);
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
material.transmission = _Transmission;
material.absorption = _Absorption;
material.ior = _IOR;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
// Meta not implemented
UsePass "Standard/META"
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 15d843c037dba3d44b1241383a0caf43
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,740 @@
/*
Filamented example template.
*/
Shader "Silent/Filamented Extras/Filamented Selector"
{
Properties
{
[CheckDFGTexture]
[BlendModeSelector(_SrcBlend, _DstBlend, _CustomRenderQueue, _ZWrite, _AtoCmode)] _Mode ("__mode", Float) = 0.0
[KeywordEnum(Standard,Cloth,Anisotropy,Glint,Subsurface)]_Shading("Shading Type", Float) = 0
[HeaderEx(Base Material)]
[ScaleOffset][SingleLine(_Color)]_MainTex("Albedo", 2D) = "white" {}
[HideInInspector]_Color("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScale)][Normal] _BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[Space]
[SingleLine]_MOESMap("Property Map", 2D) = "white" {}
[Space]
[Enum(Red, 0, Green, 1, Blue, 2, Alpha, 3)]_MetallicSelect("Metallic Channel", Range(0, 3)) = 0
_MetallicScale("Metallic Scale", Range( 0 , 1)) = 0
[Space]
[Enum(Red, 0, Green, 1, Blue, 2, Alpha, 3)]_SmoothnessSelect("Smoothness Channel", Range(0, 3)) = 3
[Enum(Smoothness, 0, Roughness, 1)]_SmoothnessMode("Smoothness Mode", Float) = 0
_SmoothnessScale("Smoothness Scale", Range( 0 , 1)) = 0
[Space]
[Enum(Red, 0, Green, 1, Blue, 2, Alpha, 3)]_OcclusionSelect("Occlusion Channel", Range(0, 3)) = 1
_OcclusionScale("Occlusion Scale", Range( 0 , 1)) = 0
[Space]
[Enum(Red, 0, Green, 1, Blue, 2, Alpha, 3)]_EmissionSelect("Emission Mask Channel", Range(0, 3)) = 2
_Emission("Emission Power", Float) = 0
_EmissionColor("Emission Tint", Color) = (1,1,1,1)
_EmissionFluro("Emission Edge Fade Intensity", Range(0, 1)) = 0.0
[Space]
[IfDef(_SHADING_ANISOTROPY)][HeaderEx(Anisotropy Properties)]
_Anisotropy("Anisotropy", Range(-1, 1)) = 0.5
[IfDef(_SHADING_ANISOTROPY)][Normal][SingleLine]
_AnisotropyDirectionMap("Direction Map", 2D) = "bump" {}
[IfDef(_SHADING_GLINT)][HeaderEx(Glint Properties)]
_SpecularGlintSize("Glint Size", Range(0, 1)) = 0.5
[IfDef(_SHADING_GLINT)]
_SpecularGlintDensity("Glint Density", Range(0, 1)) = 0.5
[IfDef(_SHADING_SUBSURFACE)][HeaderEx(Subsurface Properties)]
[SingleLine][NoScaleOffset]_ThicknessMap("Thickness Map", 2D) = "white" {}
[IfDef(_SHADING_SUBSURFACE)]_ThicknessScale("Thickness", Range(0, 1)) = 0.5
[IfDef(_SHADING_SUBSURFACE)]_SubsurfacePower("Subsurface Power", Float) = 12.234
[IfDef(_SHADING_SUBSURFACE,_SHADING_CLOTH)]_SubsurfaceColor("Subsurface Color", Color) = (1.0, 1.0, 1.0, 1.0)
[IfDef(_SHADING_SUBSURFACE,_SHADING_CLOTH)][ToggleUI]_AutoSubsurfaceColor("Subsurface Colour from Albedo", Float) = 1
[Space]
[HeaderEx(Emission Texture)]
[NoScaleOffset][SetKeywordSingleLine(_ADD_EMISSION)]_EmissionMap("Emission Map", 2D) = "black" {}
_EmissionMapPower("Emission Map Intensity", Float) = 1.0
[Space]
[HeaderEx(Detail Mapping)]
_DetailBlendWeight("Blend Weight", Range(0, 1)) = 1
[HideInInspector][Enum(Multiply2x, 0, Multiply, 1, Additive, 2, AlphaBlend, 3)]_DetailBlendMode("Blend Mode", Float) = 0.0
[ScaleOffset][SingleLine(_DetailBlendMode)]_MainTexDetail("Albedo Detail", 2D) = "gray" {}
[SingleLine(_BumpScaleDetail)][Normal] _BumpMapDetail("Normal Detail", 2D) = "bump" {}
[HideInInspector]_BumpScaleDetail("Normal Detail Scale", Float) = 1
[SingleLine]_MOESMapDetail("Property Map Detail", 2D) = "white" {}
[Space]
[Toggle(_DTRIPLANAR)]_UseDTriplanar("Triplanar Detail", Float) = 0.0
[IfDef(_DTRIPLANAR)]_TriplanarSharp("Blending Sharpness", Range(1, 10)) = 3
[IfDef(_DTRIPLANAR)]_TriplanarTiles0x ("X Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarTiles0y ("Y Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarTiles0z ("X Axis Tiling", float) = 1
[IfDef(_DTRIPLANAR)]_TriplanarOffset0x ("X Axis Offset", float) = 0
[IfDef(_DTRIPLANAR)]_TriplanarOffset0y ("Y Axis Offset", float) = 0
[IfDef(_DTRIPLANAR)]_TriplanarOffset0z ("X Axis Offset", float) = 0
[Space]
[HeaderEx(Complex Material)]
[IfNDef(_SHADING_SUBSURFACE,_SHADING_CLOTH,_SHADING_SUBSURFACE)][SingleLine]_IridescenceRamp("Specular Iridescence Ramp", 2D) = "white" {}
[IfNDef(_SHADING_SUBSURFACE,_SHADING_CLOTH,_SHADING_SUBSURFACE)]_IridescenceAmount("Iridescence Amount", Range(0, 1)) = 0
[Space]
[SingleLine]_WetnessMap("Wetness Mask (R)", 2D) = "white" {}
_WetnessAmount("Wetness Amount", Range(0, 1)) = 0.0
[Space]
[Toggle(_USE_CLEARCOAT)]_ClearCoatMode("Clear Coat", Float) = 0
[IfDef(_USE_CLEARCOAT)][SingleLine]_ClearCoatMap("Clear Coat Map (R: Intensity, G: Roughness)", 2D) = "white" {}
[IfDef(_USE_CLEARCOAT)]_ClearCoat("Clear Coat Intensity", Range(0, 1)) = 0.0
[IfDef(_USE_CLEARCOAT)]_ClearCoatRoughness("Clear Coat Roughness", Range(0, 1)) = 0.0
[Space]
[IfNDef(_SHADING_SUBSURFACE,_SHADING_CLOTH)][Toggle(_USE_SHEEN)]_SheenMode("Sheen", Float) = 0
[IfNDef(_SHADING_SUBSURFACE,_SHADING_CLOTH)][IfDef(_USE_SHEEN)][SingleLine]_SheenMap("Sheen Map (R: Intensity, G: Roughness)", 2D) = "white" {}
[IfNDef(_SHADING_SUBSURFACE,_SHADING_CLOTH)][IfDef(_USE_SHEEN)]_SheenColor("Sheen Color", Color) = (1.0, 1.0, 1.0, 1.0)
[IfNDef(_SHADING_SUBSURFACE,_SHADING_CLOTH)][IfDef(_USE_SHEEN)][ToggleUI]_AutoSheenColor("Sheen Colour from Albedo", Float) = 1
[IfNDef(_SHADING_SUBSURFACE,_SHADING_CLOTH)][IfDef(_USE_SHEEN)]_SheenRoughness("Sheen Roughness", Range(0, 1)) = 0.8
[Space]
[HeaderEx(System)]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
[IfDef(_LIGHTMAPSPECULAR)]_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _CustomRenderQueue ("__rq", Float) = 1.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _AtoCmode("__atoc", Float) = 0
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
#pragma shader_feature_local_fragment _ _DTRIPLANAR
#pragma shader_feature_local_fragment _ _ADD_EMISSION
#pragma shader_feature_local_fragment _SHADING_STANDARD _SHADING_CLOTH _SHADING_ANISOTROPY _SHADING_GLINT _SHADING_SUBSURFACE
#pragma shader_feature_local_fragment _ _USE_CLEARCOAT
#pragma shader_feature_local_fragment _ _USE_SHEEN
#pragma skip_variants _METALLICGLOSSMAP _NORMALMAP _EMISSION
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
#if defined(_SHADING_CLOTH)
#define SHADING_MODEL_CLOTH
#define MATERIAL_HAS_SUBSURFACE_COLOR
#undef _USE_SHEEN // Not supported.
#endif
#if defined(_SHADING_ANISOTROPY)
#define MATERIAL_HAS_ANISOTROPY
#endif
#if defined(_SHADING_GLINT)
#define MATERIAL_HAS_GLINT
#endif
#if defined(_SHADING_SUBSURFACE)
#define SHADING_MODEL_SUBSURFACE
#undef _USE_SHEEN // Not supported.
#endif
#if defined(_USE_CLEARCOAT)
#define MATERIAL_HAS_CLEAR_COAT
#endif
#if defined(_USE_SHEEN)
#define MATERIAL_HAS_SHEEN_COLOR
#endif
#if defined(_SHADING_STANDARD) || defined(_SHADING_ANISOTROPY) || defined(_SHADING_GLINT)
#define SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
// This is used to control the specular colour for iridescence.
// However, it is not supported for cloth or subsurface shading.
#endif
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicSelect;
uniform half _SmoothnessSelect;
uniform half _SmoothnessMode;
uniform half _OcclusionSelect;
uniform half _EmissionSelect;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
uniform half _EmissionFluro;
uniform sampler2D _MainTexDetail;
uniform sampler2D _MOESMapDetail;
uniform sampler2D _BumpMapDetail;
uniform half _BumpScaleDetail;
uniform half _DetailBlendMode;
uniform half _DetailBlendWeight;
uniform half4 _MainTexDetail_ST;
#ifdef _DTRIPLANAR
uniform half _TriplanarTiles0x;
uniform half _TriplanarTiles0y;
uniform half _TriplanarTiles0z;
uniform half _TriplanarOffset0x;
uniform half _TriplanarOffset0y;
uniform half _TriplanarOffset0z;
uniform half _TriplanarSharp;
#endif
#ifdef _ADD_EMISSION
//uniform sampler2D _EmissionMap;
uniform half _EmissionMapPower;
#endif
#ifdef _SHADING_ANISOTROPY
uniform half _Anisotropy;
uniform sampler2D _AnisotropyDirectionMap;
#endif
#ifdef _SHADING_GLINT
uniform half _SpecularGlintSize;
uniform half _SpecularGlintDensity;
#endif
#ifdef _SHADING_SUBSURFACE
uniform sampler2D _ThicknessMap;
uniform half _ThicknessScale;
uniform half _SubsurfacePower;
uniform half4 _SubsurfaceColor;
uniform half _AutoSubsurfaceColor;
#endif
#ifdef _SHADING_CLOTH
uniform half4 _SubsurfaceColor;
uniform half _AutoSubsurfaceColor;
#endif
uniform sampler2D _IridescenceRamp;
uniform half4 _IridescenceRamp_TexelSize;
uniform half _IridescenceAmount;
uniform sampler2D _WetnessMap;
uniform half _WetnessAmount;
#if defined(_USE_CLEARCOAT)
uniform sampler2D _ClearCoatMap;
uniform half _ClearCoat;
uniform half _ClearCoatRoughness;
#endif
#if defined(_USE_SHEEN)
uniform sampler2D _SheenMap;
uniform half4 _SheenColor;
uniform half _SheenRoughness;
uniform half _AutoSheenColor;
#endif
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
float4 boxmap(sampler2D tex, float3 p, float3 n, float k )
{
// grab coord derivatives for texturing
float3 dpdx = ddx(p);
float3 dpdy = ddy(p);
float3 m = pow( abs(n), k );
// project+fetch
float4 x = 0.0;
if (m.x > 0) x = tex2Dgrad( tex, p.zy, dpdx.zy, dpdy.zy );
float4 y = 0.0;
if (m.y > 0) y = tex2Dgrad( tex, p.zx, dpdx.zx, dpdy.zx );
float4 z = 0.0;
if (m.z > 0) z = tex2Dgrad( tex, p.xy, dpdx.xy, dpdy.xy );
// and blend
return (x*m.x + y*m.y + z*m.z) / (m.x + m.y + m.z);
}
float3 applyDetailBlendMode(int blendOp, half3 a, half3 b, half t)
{
switch(blendOp)
{
default:
case 0: // Multiply 2x
return a * LerpWhiteTo (b * unity_ColorSpaceDouble.rgb, t);
case 1: // Multiply
return a * LerpWhiteTo (b, t);
case 2: // Additive
return a + b * t;
case 3: // Alpha Blend
return lerp(a, b, t);
}
}
float3 RNMBlendUnpacked(float3 n1, float3 n2)
{
n1 += float3( 0, 0, 1);
n2 *= float3(-1, -1, 1);
return n1*dot(n1, n2)/n1.z - n2;
}
inline float EmissionFluro(float NdotV)
{
float fluroBase = saturate(pow(NdotV, 2));
return lerp(1.0 - _EmissionFluro, 1.0, fluroBase);
}
half4 SampleIridescence(half NoV, half rampID)
{
if (any(_IridescenceRamp_TexelSize.zw > 6.0))
{
half rampIDUV = (1.0 - (floor(rampID * _IridescenceRamp_TexelSize.w) + 0.5) * _IridescenceRamp_TexelSize.y);
half2 rampUV = float2(NoV, rampIDUV);
return tex2D(_IridescenceRamp, rampUV);
}
return 1.0;
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax,
float4 tangentToWorld[3], float3 i_posWorld)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy) * _Color;
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
#if defined(_DTRIPLANAR)
float triSharp = _TriplanarSharp;
float3 triPosition = i_posWorld * float3(_TriplanarTiles0x, _TriplanarTiles0y, _TriplanarTiles0z)
+ float3(_TriplanarOffset0x, _TriplanarOffset0y, _TriplanarOffset0z);
half4 baseColorDetail = boxmap (_MainTexDetail, triPosition, tangentToWorld[2], triSharp);
half4 packedMapDetail = boxmap (_MOESMapDetail, triPosition, tangentToWorld[2], triSharp);
half3 normalTangentDetail = UnpackScaleNormal(boxmap (_BumpMapDetail, triPosition, tangentToWorld[2], triSharp), _BumpScaleDetail);
#else
float2 dUV = i_tex.xy * _MainTexDetail_ST.xy + _MainTexDetail_ST.zw;
half4 baseColorDetail = tex2D (_MainTexDetail, dUV);
half4 packedMapDetail = tex2D (_MOESMapDetail, dUV);
half3 normalTangentDetail = UnpackScaleNormal(tex2D (_BumpMapDetail, dUV), _BumpScaleDetail);
#endif
baseColor.rgb = applyDetailBlendMode(_DetailBlendMode, baseColor, baseColorDetail, _DetailBlendWeight);
normalTangent = lerp(normalTangent, RNMBlendUnpacked(normalTangent, normalTangentDetail), _DetailBlendWeight);
packedMap = lerp(packedMap, packedMap * packedMapDetail, saturate(_DetailBlendWeight));
half metallic = packedMap[_MetallicSelect] * _MetallicScale;
half occlusion = lerp(1, packedMap[_OcclusionSelect], _OcclusionScale);
half emissionMask = packedMap[_EmissionSelect];
half smoothness = packedMap[_SmoothnessSelect] * _SmoothnessScale;
smoothness = (_SmoothnessMode == 0) ? smoothness : 1.0 - smoothness;
half3 emission = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
#if defined(_ADD_EMISSION)
half4 emissionMap = tex2D (_EmissionMap, i_tex.xy);
emission += emissionMap * _EmissionMapPower;
#endif
half anisotropy; half3 anisotropyDir;
#if defined(_SHADING_ANISOTROPY)
anisotropy = _Anisotropy;
anisotropyDir = UnpackNormal(tex2D(_AnisotropyDirectionMap, i_tex.xy));
#endif
half clearCoat, clearCoatRoughness;
#if defined(_USE_CLEARCOAT)
half4 ccMap = tex2D(_ClearCoatMap, i_tex.xy);
clearCoat = ccMap.r * _ClearCoat;
clearCoatRoughness = ccMap.g * _ClearCoatRoughness;
#endif
// In Cloth mode, use metalness for sheen.
half3 sheenColor = lerp(baseColor*baseColor, sqrt(baseColor), metallic);
half sheenRoughness = 1.0h;
#if defined(_USE_SHEEN)
if (_AutoSheenColor != 0)
sheenColor = 1.0h;
half4 sheenMap = tex2D(_SheenMap, i_tex.xy);
sheenColor = sheenColor * _SheenColor.rgb * sheenMap.r;
sheenRoughness = _SheenRoughness * sheenMap.g;
#endif
if (_WetnessAmount > 0)
{
half wetness = tex2D(_WetnessMap, i_tex.xy).r * _WetnessAmount;
half porosity = saturate((1.0 - metallic) * (1.0 - smoothness));
half waterDarken = wetness * porosity;
// Darken and slightly saturate porous surfaces
baseColor.rgb = lerp(baseColor.rgb, baseColor.rgb * baseColor.rgb, waterDarken * 0.5);
baseColor.rgb *= lerp(1.0, 0.2, waterDarken);
normalTangent = lerp(normalTangent, half3(0, 0, 1), wetness);
smoothness = lerp(smoothness, 0.95, wetness);
anisotropy = lerp(anisotropy, 0.0, wetness);
anisotropyDir = lerp(anisotropyDir, half3(0, 0, 1), wetness);
clearCoat = lerp(clearCoat, 1.0, wetness);
clearCoatRoughness = lerp(clearCoatRoughness, 0.05, wetness);
}
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
#if defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
material.baseColor = baseColor;
material.specularColor = baseColor * metallic;
material.glossiness = smoothness;
#else
material.baseColor = baseColor;
#if defined(SHADING_MODEL_CLOTH)
material.sheenColor = lerp(baseColor*baseColor, sqrt(baseColor), metallic);
#else
material.metallic = metallic;
#endif
material.roughness = computeRoughnessFromGlossiness(smoothness);
#endif
material.normal = normalTangent;
material.emissive.rgb = emission;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
#if defined(_SHADING_ANISOTROPY)
material.anisotropy = anisotropy;
material.anisotropyDirection = anisotropyDir;
#endif
#if defined(_SHADING_GLINT)
half internal_glint_alpha = lerp(0.001, 0.1, _SpecularGlintSize * _SpecularGlintSize);
half internal_density = pow(10.0, lerp(3.0, 9.0, _SpecularGlintDensity));
material.uv = i_tex.xy;
material.glintAlpha = internal_glint_alpha;
material.glintDensity = internal_density;
#endif
#if defined(_SHADING_SUBSURFACE) || defined(_SHADING_CLOTH)
half3 subsurfaceColor = 1.0h;
if (_AutoSubsurfaceColor != 0)
subsurfaceColor = lerp(baseColor*baseColor, sqrt(baseColor), metallic);
material.subsurfaceColor = subsurfaceColor * _SubsurfaceColor.rgb;
#endif
#if defined(_SHADING_SUBSURFACE)
material.thickness = tex2D(_ThicknessMap, i_tex.xy).r * _ThicknessScale;
material.subsurfacePower = _SubsurfacePower;
#endif
#if defined(_USE_CLEARCOAT)
material.clearCoat = clearCoat;
material.clearCoatRoughness = clearCoatRoughness;
#endif
#if defined(_USE_SHEEN) && !defined(SHADING_MODEL_CLOTH)
material.sheenColor = sheenColor;
material.sheenRoughness = sheenRoughness;
#endif
return material;
}
inline void applyIridescence(const ShadingParams shading, inout MaterialInputs material)
{
#if defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
if (_IridescenceAmount > 0)
{
half4 specIridescence = lerp(half4(1.0.xxx, 0.0), SampleIridescence(shading.NoV, 0), _IridescenceAmount);
material.specularColor *= specIridescence.rgb;
}
#endif
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i, bool facing)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
material.emissive *= EmissionFluro(shading.NoV);
applyIridescence(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i, bool facing)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
applyIridescence(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i, bool f : SV_IsFrontFace) : SV_Target
{ return fragForwardBaseTemplate(i, f); }
half4 fragAdd (VertexOutputForwardAdd i, bool f : SV_IsFrontFace) : SV_Target
{ return fragForwardAddTemplate(i, f); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local_fragment _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local_fragment _ _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local_fragment _ _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local_fragment _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local_fragment _LTCGI
#pragma shader_feature_local_fragment _VRCLV
#pragma shader_feature_local_fragment _LIGHTMAPSPECULAR
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
//Blend One [_DstBlend]
//ZWrite [_ZWrite]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local_fragment _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local_fragment _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
AlphaToMask Off
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
// Must be in vertex stage to pass UVs.
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
CGPROGRAM
#define REQUIRE_META_WORLDPOS
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
float4 dummy[3]; dummy[0] = 1; dummy[1] = 0; dummy[2] = i.worldPos;
material = MyMaterialSetup (i.uv, 0, 0, dummy, i.worldPos);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,20 @@
fileFormatVersion: 2
guid: 5835b3b76534b964c8b4b6f41edd479f
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _EmissionMap: {instanceID: 0}
- _MainTexDetail: {instanceID: 0}
- _BumpMapDetail: {instanceID: 0}
- _MOESMapDetail: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,371 @@
/*
Filamented example template.
This is a template of how to use Filamented to make a simple shader
that passes its own properties through to Filament, in a manner
similar to a Unity surface shader - but with less jank.
Instead of reading multiple seperate maps, it just asks for
an albedo map, a normal map, and a MOES map.
This version adds vertex colours, and also shows some examples of
how to use the custom material editor from Filamented Extras.
*/
Shader "Silent/Filamented Template (Vertex Color)"
{
Properties
{
[CheckDFGTexture]
[SingleLine]_MainTex("Albedo", 2D) = "white" {}
_VertexColourScale("Vertex Colour Intensity", Range(0, 1)) = 1.0
[Space]
[SingleLine(_BumpScale)][Normal] _BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[Space]
[SingleLine]_MOESMap("MOES Map", 2D) = "white" {}
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_Emission("Emission Power", Float) = 0
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[Space]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[Toggle(_ALPHATEST_ON)]_AtoCmode("Cutout Transparency", Float) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
#define HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
uniform half _VertexColourScale;
// uniform half3 _EmissionColor;
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs VCMaterialSetup (inout float4 i_tex, float3 i_eyeVec,
half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld, float4 i_color)
{
half4 baseColor = tex2D (_MainTex, i_tex.xy);
half4 packedMap = tex2D (_MOESMap, i_tex.xy);
half3 normalTangent = UnpackScaleNormal(tex2D (_BumpMap, i_tex.xy), _BumpScale);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
baseColor.rgb = lerp(baseColor, baseColor * i_color, _VertexColourScale);
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
VCMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData,
IN_WORLDPOS(i), i.color);
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
VCMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir,
IN_WORLDPOS_FWDADD(i), i.color);
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
CGPROGRAM
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
// Note: If your MaterialSetup needs vertex normals, you might want to use a custom vert_meta which passes them through.
float4 dummy[3]; dummy[0] = 1.0; dummy[1] = 0.0; dummy[2] = 0.0;
material = MyMaterialSetup(i.uv, 0, 0, dummy, 0, i.color);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature ___ _DETAIL_MULX2
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: 9d2eaba013d66c24a9b2e5e3bc2cb259
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,722 @@
/*
Filamented texture blending sample.
This is designed to be used as-is in existing projects, but
experienced users may wish to modify how the shader functions.
*/
Shader "Silent/Filamented Extras/Texture Blending Filamented"
{
Properties
{
[CheckDFGTexture]
[BlendModeSelector(_SrcBlend, _DstBlend, _CustomRenderQueue, _ZWrite, _AtoCmode)] _Mode ("__mode", Float) = 0.0
[HeaderEx(Base Settings)]
[Enum(UV0,0,UV1,1,UV2,2,UV3,3)] _UVSec ("UV for Splat Map", Float) = 0
[SetKeyword(_SPLATMAP)]_MainTex("Splat Map (Optional) and Texture Scale", 2D) = "black" {}
[ToggleUI]_WeightFromDirection("World-Space XYZ to Vertex Colour RGB", Float) = 0
[HeaderEx(Base Color)]
[ScaleOffset][SingleLine(_ColorA)]_MainTexA ("Albedo (RGB)", 2D) = "white" {}
[HideInInspector]_ColorA("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScaleA)][Normal]_BumpMapA ("Normal Map (XYZ)", 2D) = "bump" {}
[HideInInspector]_BumpScaleA("Normal Scale", Float) = 1
[SingleLine(_PropertiesA)]_MaskMapA ("Mask (MOES)", 2D) = "green" {}
[HideInInspector]_PropertiesA("MOES Scale", Vector) = (0.0, 0.0, 0.0, 1.0)
[HeaderEx(Vertex Color R)]
[ScaleOffset][SingleLine(_ColorR)]_MainTexR ("Albedo (RGB)", 2D) = "white" {}
[HideInInspector]_ColorR("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScaleR)][Normal]_BumpMapR ("Normal Map (XYZ)", 2D) = "bump" {}
[HideInInspector]_BumpScaleR("Normal Scale", Float) = 1
[SingleLine(_PropertiesR)]_MaskMapR ("Mask (MOES)", 2D) = "green" {}
[HideInInspector]_PropertiesR("MOES Scale", Vector) = (0.0, 0.0, 0.0, 1.0)
[HeaderEx(Vertex Color G)]
[ScaleOffset][SingleLine(_ColorG)]_MainTexG ("Albedo (RGB)", 2D) = "white" {}
[HideInInspector]_ColorG("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScaleG)][Normal]_BumpMapG ("Normal Map (XYZ)", 2D) = "bump" {}
[HideInInspector]_BumpScaleG("Normal Scale", Float) = 1
[SingleLine(_PropertiesG)]_MaskMapG ("Mask (MOES)", 2D) = "green" {}
[HideInInspector]_PropertiesG("MOES Scale", Vector) = (0.0, 0.0, 0.0, 1.0)
[HeaderEx(Vertex Color B)]
[ScaleOffset][SingleLine(_ColorB)]_MainTexB ("Albedo (RGB)", 2D) = "white" {}
[HideInInspector]_ColorB("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScaleB)][Normal]_BumpMapB ("Normal Map (XYZ)", 2D) = "bump" {}
[HideInInspector]_BumpScaleB("Normal Scale", Float) = 1
[SingleLine(_PropertiesB)]_MaskMapB ("Mask (MOES)", 2D) = "green" {}
[HideInInspector]_PropertiesB("MOES Scale", Vector) = (0.0, 0.0, 0.0, 1.0)
[HeaderEx(Texture Blending Settings)]
[ScaleOffset][SingleLine]_BlendMask ("Texture Blending Offset (R)", 2D) = "grey" {}
_MaskStr("Blending Mask Power (per-channel)", Vector) = (1.0, 1.0, 1.0, 1.0)
[Toggle(_DEBUG_VIEWWEIGHTS)]_DebugViewBlendingWeights("Debug View for Blend Weights", Float ) = 0.0
[Space]
[HeaderEx(Sampling Settings)]
[Toggle(_STOCHASTIC)]_UseStochastic("Stochastic Sampling", Float) = 0.0
[Space]
[Toggle(_TRIPLANAR)]_UseTriplanar("Triplanar Sampling", Float) = 0.0
[IfDef(_TRIPLANAR)]_UVTransform0("Triplanar UV Transform X", Vector) = (1, 0, 0, 0)
[IfDef(_TRIPLANAR)]_UVTransform1("Triplanar UV Transform Y", Vector) = (0, 1, 0, 0)
[IfDef(_TRIPLANAR)]_UVTransform2("Triplanar UV Transform Z", Vector) = (0, 0, 1, 0)
[HeaderEx(Filamented Settings)]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _CustomRenderQueue ("__rq", Float) = 1.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _AtoCmode("__atoc", Float) = 0
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
#define HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define HAS_ATTRIBUTE_UV2
#define HAS_ATTRIBUTE_UV3
// If this is not defined, secondary UVs will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
// UNITY_SHADER_NO_UPGRADE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
#include "Packages/s-ilent.filamented/Filamented/SharedSamplingLib.hlsl"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters.
TEXTURE2D(_MainTexR); TEXTURE2D(_MainTexG); TEXTURE2D(_MainTexB); TEXTURE2D(_MainTexA);
TEXTURE2D(_BumpMapR); TEXTURE2D(_BumpMapG); TEXTURE2D(_BumpMapB); TEXTURE2D(_BumpMapA);
TEXTURE2D(_MaskMapR); TEXTURE2D(_MaskMapG); TEXTURE2D(_MaskMapB); TEXTURE2D(_MaskMapA);
SAMPLER(sampler_MainTexR);
SAMPLER(sampler_BumpMapR);
SAMPLER(sampler_MaskMapR);
float4 _MainTexR_ST; float4 _MainTexG_ST; float4 _MainTexB_ST; float4 _MainTexA_ST;
float4 _ColorR; float4 _ColorG; float4 _ColorB; float4 _ColorA;
float _BumpScaleR; float _BumpScaleG; float _BumpScaleB; float _BumpScaleA;
float4 _PropertiesR; float4 _PropertiesG; float4 _PropertiesB; float4 _PropertiesA;
uniform half4 _UVTransform0;
uniform half4 _UVTransform1;
uniform half4 _UVTransform2;
TEXTURE2D(_BlendMask); SAMPLER(sampler_BlendMask);
float4 _BlendMask_ST;
float4 _MaskStr;
half _WeightFromDirection;
VertexOutputForwardBase vertBase (VertexInput v)
{
VertexOutputForwardBase o;
o = vertForwardBase(v);
o.tex.zw = TRANSFORM_TEX(((_UVSec == 0) ? v.uv0 : v.uv1), _MainTex);
#if defined(HAS_ATTRIBUTE_UV2)
o.tex.zw = TRANSFORM_TEX(((_UVSec == 2) ? v.uv2 : o.tex.zw), _MainTex);
#endif
#if defined(HAS_ATTRIBUTE_UV3)
o.tex.zw = TRANSFORM_TEX(((_UVSec == 3) ? v.uv3 : o.tex.zw), _MainTex);
#endif
return o;
}
VertexOutputForwardAdd vertAdd (VertexInput v)
{
VertexOutputForwardAdd o;
o = vertForwardAdd(v);
o.tex.zw = TRANSFORM_TEX(((_UVSec == 0) ? v.uv0 : v.uv1), _MainTex);
#if defined(HAS_ATTRIBUTE_UV2)
o.tex.zw = TRANSFORM_TEX(((_UVSec == 2) ? v.uv2 : o.tex.zw), _MainTex);
#endif
#if defined(HAS_ATTRIBUTE_UV3)
o.tex.zw = TRANSFORM_TEX(((_UVSec == 3) ? v.uv3 : o.tex.zw), _MainTex);
#endif
return o;
}
//hash for randomness
float2 hash2D2D(float2 s)
{
//magic numbers
return frac(sin(fmod(float2(dot(s, float2(127.1, 311.7)), dot(s, float2(269.5, 183.3))), 3.14159)) * 43758.5453);
}
//stochastic sampling
float4 tex2DStochastic(TEXTURE2D_PARAM(tex, smp), float2 UV)
{
//triangle vertices and blend weights
//BW_vx[0...2].xyz = triangle verts
//BW_vx[3].xy = blend weights (z is unused)
float4x3 BW_vx;
//uv transformed into triangular grid space with UV scaled by approximation of 2*sqrt(3)
float2 skewUV = mul(float2x2 (1.0, 0.0, -0.57735027, 1.15470054), UV * 3.464);
//vertex IDs and barycentric coords
float2 vxID = float2 (floor(skewUV));
float3 barry = float3 (frac(skewUV), 0);
barry.z = 1.0 - barry.x - barry.y;
BW_vx = ((barry.z > 0) ?
float4x3(float3(vxID, 0), float3(vxID + float2(0, 1), 0), float3(vxID + float2(1, 0), 0), barry.zyx) :
float4x3(float3(vxID + float2 (1, 1), 0), float3(vxID + float2 (1, 0), 0), float3(vxID + float2 (0, 1), 0), float3(-barry.z, 1.0 - barry.y, 1.0 - barry.x)));
//calculate derivatives to avoid triangular grid artifacts
float2 dx = ddx(UV);
float2 dy = ddy(UV);
//blend samples with calculated weights
return mul(SAMPLE_TEXTURE2D_GRAD(tex, smp, UV + hash2D2D(BW_vx[0].xy), dx, dy), BW_vx[3].x) +
mul(SAMPLE_TEXTURE2D_GRAD(tex, smp, UV + hash2D2D(BW_vx[1].xy), dx, dy), BW_vx[3].y) +
mul(SAMPLE_TEXTURE2D_GRAD(tex, smp, UV + hash2D2D(BW_vx[2].xy), dx, dy), BW_vx[3].z);
}
// Typical triplanar mapping -- has less visual artifacts than biplanar.
// Artifacts stand out because this is a material shader for things like
// terrain which cover a large portion of the screen.
float4 boxmap( TEXTURE2D_PARAM(tex, smp), float3 p, float3 n, float k )
{
// grab coord derivatives for texturing
float3 dpdx = ddx(p);
float3 dpdy = ddy(p);
float3 m = pow( abs(n), k );
// project+fetch
float4 x = 0.0;
if (m.x > 0) x = SAMPLE_TEXTURE2D_GRAD( tex, smp, p.zy, dpdx.zy, dpdy.zy );
float4 y = 0.0;
if (m.y > 0) y = SAMPLE_TEXTURE2D_GRAD( tex, smp, p.zx, dpdx.zx, dpdy.zx );
float4 z = 0.0;
if (m.z > 0) z = SAMPLE_TEXTURE2D_GRAD( tex, smp, p.xy, dpdx.xy, dpdy.xy );
// and blend
return (x*m.x + y*m.y + z*m.z) / (m.x + m.y + m.z);
}
float4 tex2DStochasticBoxmap(TEXTURE2D_PARAM(tex, smp), float3 p, float3 n, float k)
{
// Stochastic sampling
float4x3 BW_vx;
float3 m = pow( abs(n), k );
float2 skewUV = mul(float2x2 (1.0, 0.0, -0.57735027, 1.15470054), (p.xy * m.x + p.yz * m.y + p.zx * m.z) * 3.464);
float2 vxID = float2 (floor(skewUV));
float3 barry = float3 (frac(skewUV), 0);
barry.z = 1.0 - barry.x - barry.y;
BW_vx = ((barry.z > 0) ?
float4x3(float3(vxID, 0), float3(vxID + float2(0, 1), 0), float3(vxID + float2(1, 0), 0), barry.zyx) :
float4x3(float3(vxID + float2 (1, 1), 0), float3(vxID + float2 (1, 0), 0), float3(vxID + float2 (0, 1), 0), float3(-barry.z, 1.0 - barry.y, 1.0 - barry.x)));
// Box mapping
float3 dpdx = ddx(p);
float3 dpdy = ddy(p);
// Blend samples with calculated weights
return ((m.x > 0 ? mul(SAMPLE_TEXTURE2D_GRAD(tex, smp, p.zy + hash2D2D(BW_vx[0].xy), dpdx.zy, dpdy.zy), BW_vx[3].x) : 0) +
(m.y > 0 ? mul(SAMPLE_TEXTURE2D_GRAD(tex, smp, p.zx + hash2D2D(BW_vx[1].xy), dpdx.zx, dpdy.zx), BW_vx[3].y) : 0) +
(m.z > 0 ? mul(SAMPLE_TEXTURE2D_GRAD(tex, smp, p.xy + hash2D2D(BW_vx[2].xy), dpdx.xy, dpdy.xy), BW_vx[3].z) : 0)) / (m.x + m.y + m.z);
}
float3 RNMBlendUnpacked(float3 n1, float3 n2)
{
n1 += float3( 0, 0, 1);
n2 *= float3(-1, -1, 1);
return n1*dot(n1, n2)/n1.z - n2;
}
float3 PDNormalBlend(float3 n1, float3 n2, float alpha)
{
float2 pd1 = n1.xy / n1.z;
float2 pd2 = n2.xy / n2.z;
float2 pd_interpolated = lerp(pd1, pd2, alpha);
return normalize(float3(pd_interpolated, 1.0));
}
void addLayer(float weight, float2 uv, float4 uv_ST,
TEXTURE2D_PARAM(tex_A, smp_A), inout float4 albedoAlpha, float4 tint,
TEXTURE2D_PARAM(tex_N, smp_N), inout float3 normal, float scale,
TEXTURE2D_PARAM(tex_M, smp_M), inout float4 props,
inout float4 maskProps)
{
if (weight > 0)
{
uv = uv * uv_ST.xy + uv_ST.zw;
#if defined(_STOCHASTIC)
float4 thisBasemap = tex2DStochastic(tex_A, smp_A, uv);
float3 thisNormal = UnpackScaleNormal(tex2DStochastic(tex_N, smp_N, uv), weight * scale);
float4 thisProps = tex2DStochastic(tex_M, smp_M, uv);
#else
float4 thisBasemap = SAMPLE_TEXTURE2D(tex_A, smp_A, uv);
float3 thisNormal = UnpackScaleNormal(SAMPLE_TEXTURE2D(tex_N, smp_N, uv), weight * scale);
float4 thisProps = SAMPLE_TEXTURE2D(tex_M, smp_M, uv);
#endif
thisBasemap *= tint;
thisProps.rba *= maskProps.rba; // metallic, emission, smoothness
thisProps.g = lerp(1, thisProps.g, maskProps.g); // occlusion
#if 0
albedoAlpha = albedoAlpha + thisBasemap * weight;
normal = RNMBlendUnpacked(thisNormal, normal);
props = props + thisProps * weight;
#else
albedoAlpha = lerp(albedoAlpha, thisBasemap, weight);
normal = lerp(normal, thisNormal, weight);
props = lerp(props, thisProps, weight);
#endif
}
}
void addLayerTriplanar(float weight, float3 p, float3 n, float4 uv_ST,
TEXTURE2D_PARAM(tex_A, smp_A), inout float4 albedoAlpha, float4 tint,
TEXTURE2D_PARAM(tex_N, smp_N), inout float3 normal, float scale,
TEXTURE2D_PARAM(tex_M, smp_M), inout float4 props,
inout float4 maskProps)
{
const float tightness = 6.0;
if (weight > 0.01)
{
p = p * uv_ST.xyx + uv_ST.zwz;
#if defined(_STOCHASTIC)
float4 thisBasemap = tex2DStochasticBoxmap(TEXTURE2D_ARGS(tex_A, smp_A), p, n, tightness);
float3 thisNormal = UnpackScaleNormal(tex2DStochasticBoxmap(TEXTURE2D_ARGS(tex_N, smp_N), p, n, tightness), weight * scale);
float4 thisProps = tex2DStochasticBoxmap(TEXTURE2D_ARGS(tex_M, smp_M), p, n, tightness);
#else
float4 thisBasemap = boxmap(TEXTURE2D_ARGS(tex_A, smp_A), p, n, tightness);
float3 thisNormal = UnpackScaleNormal(boxmap(TEXTURE2D_ARGS(tex_N, smp_N), p, n, tightness), weight * scale);
float4 thisProps = boxmap(TEXTURE2D_ARGS(tex_M, smp_M), p, n, tightness);
#endif
thisBasemap *= tint;
thisProps.rba *= maskProps.rba; // metallic, emission, smoothness
thisProps.g = lerp(1, thisProps.g, maskProps.g); // occlusion
#if 0
albedoAlpha = albedoAlpha + thisBasemap * weight;
normal = RNMBlendUnpacked(thisNormal, normal);
props = props + thisProps * weight;
#else
albedoAlpha = lerp(albedoAlpha, thisBasemap, weight);
normal = lerp(normal, thisNormal, weight);
props = lerp(props, thisProps, weight);
#endif
}
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs BlendedMaterialSetup (inout float4 i_tex, float4 tangentToWorld[3],
float3 i_posWorld, float4 i_color)
{
// Blend weights in vertex colours
fixed3 weights = i_color;
#if defined(_SPLATMAP)
// Blend weights in splat map
weights = tex2D (_MainTex, i_tex.zw);
#endif
float3x3 tangentToWorldOnly = float3x3(tangentToWorld[0].xyz, tangentToWorld[1].xyz, tangentToWorld[2].xyz);
float3 worldNormalT = mul ( float3( 0, 0, 1 ), tangentToWorldOnly );
float3 worldPosT = float3(
dot(float4(i_posWorld.xyz, 1), _UVTransform0),
dot(float4(i_posWorld.xyz, 1), _UVTransform1),
dot(float4(i_posWorld.xyz, 1), _UVTransform2)
);
if (_WeightFromDirection)
{
weights = (abs(worldNormalT));
}
#if defined(_TRIPLANAR)
float4 blendMod = boxmap(TEXTURE2D_ARGS(_BlendMask, sampler_BlendMask),
worldPosT * _BlendMask_ST.xyx + _BlendMask_ST.zwz, worldNormalT, 1.0).r;
#else
float4 blendMod = SAMPLE_TEXTURE2D(_BlendMask, sampler_BlendMask,
i_tex.xy * _BlendMask_ST.xy + _BlendMask_ST.zw).r;
#endif
weights = saturate( pow(((blendMod*weights)*4) + (weights*2), _MaskStr) );
float baseLayerWeight = 1.0 - saturate(dot(weights, 1.0));
#if defined(_DEBUG_VIEWWEIGHTS)
MaterialInputs debugView = (MaterialInputs)0;
initMaterial(debugView);
debugView.baseColor = 0.0;
debugView.emissive = float4(weights, 1.0);
debugView.emissive.a = 1.0;
return debugView;
#endif
float4 c = 0;
float3 n = float3(0.0, 0.0, 1.0);
float4 m = 0;
#if defined(_TRIPLANAR)
addLayerTriplanar(baseLayerWeight, worldPosT, worldNormalT, _MainTexA_ST,
TEXTURE2D_ARGS(_MainTexA, sampler_MainTexR), c, _ColorA,
TEXTURE2D_ARGS(_BumpMapA, sampler_BumpMapR), n, _BumpScaleA,
TEXTURE2D_ARGS(_MaskMapA, sampler_MaskMapR), m,
_PropertiesA);
addLayerTriplanar(weights.r, worldPosT, worldNormalT, _MainTexR_ST,
TEXTURE2D_ARGS(_MainTexR, sampler_MainTexR), c, _ColorR,
TEXTURE2D_ARGS(_BumpMapR, sampler_BumpMapR), n, _BumpScaleR,
TEXTURE2D_ARGS(_MaskMapR, sampler_MaskMapR), m,
_PropertiesR);
addLayerTriplanar(weights.g, worldPosT, worldNormalT, _MainTexG_ST,
TEXTURE2D_ARGS(_MainTexG, sampler_MainTexR), c, _ColorG,
TEXTURE2D_ARGS(_BumpMapG, sampler_BumpMapR), n, _BumpScaleG,
TEXTURE2D_ARGS(_MaskMapG, sampler_MaskMapR), m,
_PropertiesG);
addLayerTriplanar(weights.b, worldPosT, worldNormalT, _MainTexB_ST,
TEXTURE2D_ARGS(_MainTexB, sampler_MainTexR), c, _ColorB,
TEXTURE2D_ARGS(_BumpMapB, sampler_BumpMapR), n, _BumpScaleB,
TEXTURE2D_ARGS(_MaskMapB, sampler_MaskMapR), m,
_PropertiesB);
#else
addLayer(baseLayerWeight, i_tex.xy, _MainTexA_ST,
TEXTURE2D_ARGS(_MainTexA, sampler_MainTexR), c, _ColorA,
TEXTURE2D_ARGS(_BumpMapA, sampler_BumpMapR), n, _BumpScaleA,
TEXTURE2D_ARGS(_MaskMapA, sampler_MaskMapR), m,
_PropertiesA);
addLayer(weights.r, i_tex.xy, _MainTexR_ST,
TEXTURE2D_ARGS(_MainTexR, sampler_MainTexR), c, _ColorR,
TEXTURE2D_ARGS(_BumpMapR, sampler_BumpMapR), n, _BumpScaleR,
TEXTURE2D_ARGS(_MaskMapR, sampler_MaskMapR), m,
_PropertiesR);
addLayer(weights.g, i_tex.xy, _MainTexG_ST,
TEXTURE2D_ARGS(_MainTexG, sampler_MainTexR), c, _ColorG,
TEXTURE2D_ARGS(_BumpMapG, sampler_BumpMapR), n, _BumpScaleG,
TEXTURE2D_ARGS(_MaskMapG, sampler_MaskMapR), m,
_PropertiesG);
addLayer(weights.b, i_tex.xy, _MainTexB_ST,
TEXTURE2D_ARGS(_MainTexB, sampler_MainTexR), c, _ColorB,
TEXTURE2D_ARGS(_BumpMapB, sampler_BumpMapR), n, _BumpScaleB,
TEXTURE2D_ARGS(_MaskMapB, sampler_MaskMapR), m,
_PropertiesB);
#endif
half metallic = m.x;
half occlusion = m.y;
half emissionMask = m.z;
half smoothness = m.w;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = c;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = n;
material.emissive.rgb = c.rgb * emissionMask;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
BlendedMaterialSetup(i.tex, i.tangentToWorldAndPackedData, IN_WORLDPOS(i), i.color);
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
BlendedMaterialSetup(i.tex,i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i), i.color);
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 5.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma shader_feature_local _SPLATMAP
#pragma shader_feature_local _TRIPLANAR
#pragma shader_feature_local _STOCHASTIC
#pragma shader_feature_local _DEBUG_VIEWWEIGHTS
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
//Blend One [_DstBlend]
//ZWrite [_ZWrite]
CGPROGRAM
#pragma target 5.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _SPLATMAP
#pragma shader_feature_local _TRIPLANAR
#pragma shader_feature_local _STOCHASTIC
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
AlphaToMask Off
CGPROGRAM
#pragma target 5.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
AlphaToMask Off
CGPROGRAM
#define REQUIRE_META_WORLDPOS
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
float4 dummy[3]; dummy[0] = 1; dummy[1] = 0; dummy[2] = 0;
material = BlendedMaterialSetup(i.uv, dummy, i.worldPos, i.color);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature ___ _DETAIL_MULX2
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: bba5baa3e3ab1e1408b673307df0108e
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,432 @@
/*
Filamented triplanar example.
*/
Shader "Silent/Filamented Extras/Simple Triplanar Filamented"
{
Properties
{
[CheckDFGTexture]
[BlendModeSelector(_SrcBlend, _DstBlend, _CustomRenderQueue, _ZWrite, _AtoCmode)] _Mode ("__mode", Float) = 0.0
[HeaderEx(Base Material)]
[SingleLine(_Color)]_MainTex("Albedo", 2D) = "white" {}
[HideInInspector]_Color("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScale)][Normal] _BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[SingleLine]_MOESMap("MOES Map", 2D) = "white" {}
[Space]
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_Emission("Emission Power", Float) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_EmissionColor("Emission Tint", Color) = (1,1,1,1)
[Space]
[HeaderEx(Texture Transform)]
_UVTransform0("UV Transform X", Vector) = (1, 0, 0, 0)
_UVTransform1("UV Transform Y", Vector) = (0, 1, 0, 0)
_UVTransform2("UV Transform Z", Vector) = (0, 0, 1, 0)
[HeaderEx(System)]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _CustomRenderQueue ("__rq", Float) = 1.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _AtoCmode("__atoc", Float) = 0
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
// Note: Unfortunately, Input is still needed due to some interdependancies with other Unity files.
// This means that some properties will always be defined, even if they aren't used.
// In practise, this won't affect the final compilation, but it means you'll need to watch out for the names
// of some common parameters. In this case, only MOESMap and some other properties are defined here because
// they are already defined in Input.
// uniform sampler2D _MainTex;
// uniform sampler2D _BumpMap;
uniform sampler2D _MOESMap;
// uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
// uniform half3 _EmissionColor;
uniform half4 _UVTransform0;
uniform half4 _UVTransform1;
uniform half4 _UVTransform2;
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
// https://iquilezles.org/www/articles/biplanar/biplanar.htm
// "p" point being textured
// "n" surface normal at "p"
// "k" controls the sharpness of the blending in the transitions areas
// "s" texture sampler
float4 biplanar( sampler2D sam, float3 p, float3 n, float k )
{
// grab coord derivatives for texturing
float3 dpdx = ddx(p);
float3 dpdy = ddy(p);
n = abs(n);
// determine major axis (in x; yz are following axis)
int3 ma = (n.x>n.y && n.x>n.z) ? int3(0,1,2) :
(n.y>n.z) ? int3(1,2,0) :
int3(2,0,1) ;
// determine minor axis (in x; yz are following axis)
int3 mi = (n.x<n.y && n.x<n.z) ? int3(0,1,2) :
(n.y<n.z) ? int3(1,2,0) :
int3(2,0,1) ;
// determine median axis (in x; yz are following axis)
int3 me = clamp(3 - mi - ma, 0, 2);
// project+fetch
float4 x = tex2Dgrad( sam, float2( p[ma.y], p[ma.z]),
float2(dpdx[ma.y],dpdx[ma.z]),
float2(dpdy[ma.y],dpdy[ma.z]) );
float4 y = tex2Dgrad( sam, float2( p[me.y], p[me.z]),
float2(dpdx[me.y],dpdx[me.z]),
float2(dpdy[me.y],dpdy[me.z]) );
// blend factors
float2 w = float2(n[ma.x],n[me.x]);
// make local support
w = clamp( (w-0.5773)/(1.0-0.5773), 0.0, 1.0 );
// shape transition
w = pow( w, k/8.0 );
// blend and return
return (x*w.x + y*w.y) / (w.x + w.y);
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
float3x3 tangentToWorldOnly = float3x3(tangentToWorld[0].xyz, tangentToWorld[1].xyz, tangentToWorld[2].xyz);
float3 normal = mul ( float3( 0, 0, 1 ), tangentToWorldOnly );
//float2 x0 = i_posWorld.xz * _UVTransform1.xy + _UVTransform1.zw;
//float2 y0 = i_posWorld.zy * _UVTransform0.xy + _UVTransform0.zw;
//float2 z0 = i_posWorld.xy * _UVTransform2.xy + _UVTransform2.zw;
float3 transformedPos = float3(
dot(float4(i_posWorld.xyz, 1), _UVTransform0),
dot(float4(i_posWorld.xyz, 1), _UVTransform1),
dot(float4(i_posWorld.xyz, 1), _UVTransform2)
);
float4 baseColor = 0;
fixed3 normalTangent = 0.0f;
float4 packedMap = 0;
baseColor = biplanar( _MainTex, transformedPos, normal, 1.0) * _Color;
normalTangent = UnpackScaleNormal(biplanar( _BumpMap, transformedPos, normal, 1.0), _BumpScale);
packedMap = biplanar( _MOESMap, transformedPos, normal, 1.0);
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend One One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
// Blend One [_DstBlend]
// ZWrite [_ZWrite]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
AlphaToMask Off
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
Pass
{
Name "META"
Tags {"LightMode"="Meta"}
Cull Off
CGPROGRAM
#define REQUIRE_META_WORLDPOS
#include "Packages/s-ilent.filamented/Filamented/UnityStandardMeta.cginc"
#define META_PASS
float4 frag_meta2 (v2f_meta i): SV_Target
{
MaterialInputs material = SETUP_BRDF_INPUT (i.uv);
float4 dummy[3]; dummy[0] = 1; dummy[1] = 0; dummy[2] = 0;
material = MyMaterialSetup (i.uv, 0, 0, dummy, i.worldPos);
PixelParams pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
#ifdef EDITOR_VISUALIZATION
o.Albedo = pixel.diffuseColor;
o.VizUV = i.vizUV;
o.LightCoord = i.lightCoord;
#else
o.Albedo = UnityLightmappingAlbedo (pixel.diffuseColor, pixel.f0, 1-pixel.perceptualRoughness);
#endif
o.SpecularColor = pixel.f0;
o.Emission = material.emissive;
return UnityMetaFragment(o);
}
#pragma vertex vert_meta
#pragma fragment frag_meta2
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature ___ _DETAIL_MULX2
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,16 @@
fileFormatVersion: 2
guid: 044744ced35f660428c5b5f0477a6e1d
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,404 @@
/*
Filamented Pixel Art is a shader designed for rendering PBR with pixel art.
It uses the same techniques as my Pixel Standard shader, but adapted for
Filamented.
https://gitlab.com/s-ilent/pixelstandard
*/
Shader "Silent/Filamented Extras/Pixel Art Filamented"
{
Properties
{
[CheckDFGTexture]
[BlendModeSelector(_SrcBlend, _DstBlend, _CustomRenderQueue, _ZWrite, _AtoCmode)] _Mode ("__mode", Float) = 0.0
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[HeaderEx(Base Material)]
[ScaleOffset][SingleLine(_Color)]_MainTex("Albedo", 2D) = "white" {}
[HideInInspector]_Color("Color", Color) = (1,1,1,1)
[SingleLine(_BumpScale)][Normal]_BumpMap("Normal", 2D) = "bump" {}
[HideInInspector]_BumpScale("Normal Scale", Float) = 1
[SingleLine]_MOESMap("MOES Map", 2D) = "white" {}
[Space]
_MetallicScale("Metallic", Range( 0 , 1)) = 0
_OcclusionScale("Occlusion", Range( 0 , 1)) = 0
_Emission("Emission Power", Float) = 0
_SmoothnessScale("Smoothness", Range( 0 , 1)) = 0
[Space]
_EmissionColor("Emission Color", Color) = (1,1,1,1)
[HeaderEx(Texture Animation)]
[Toggle(_ANIMATED)] _Animated ("Texture Animation", Float) = 0
[NoScaleOffset]_AnimationMainTex("Animated Albedo", 2DArray) = "white" {}
[Enum(PingPong, 0, Linear, 1)]_AnimationMode("Animation Mode",Float) = 0
_AnimationSpeed("Animation Speed", Float) = 1.0
[HeaderEx(Animation)]
[ToggleUI]_QuakeWater("Quake-style Distortion", Float) = 0
[HeaderEx(System)]
[Space]
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 1
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Space]
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[HideInInspector]_RNM0("RNM0", 2D) = "black" {}
[HideInInspector]_RNM1("RNM1", 2D) = "black" {}
[HideInInspector]_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Space]
[HideInInspector][Enum(UnityEngine.Rendering.BlendMode)]_SrcBlend ("__src", Float) = 1
[HideInInspector][Enum(UnityEngine.Rendering.BlendMode)]_DstBlend ("__dst", Float) = 0
[HideInInspector][Enum(Off,0,On,1)]_ZWrite ("__zw", Float) = 1
[HideInInspector]_AtoCmode("Cutout Transparency", Float) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
}
CustomEditor "Silent.FilamentedExtras.Unity.FilamentedExtrasInspector"
CGINCLUDE
#pragma shader_feature_local _ANIMATED
// First, setup what Filamented does.
// Filamented's behaviour is decided by the shading model and what material properties are defined.
// These are listed in FilamentMaterialInputs.
// You can set up and use anything in the initMaterials function.
// SHADING_MODEL_SPECULAR_GLOSSINESS
// If this is not defined, the material will default to metallic/roughness workflow.
#define SKIP_UNITY_STANDARD_INPUT_DEFINES
// If this is not defined, Unity Standard textures like _MainTex and _BumpMap
// will be automatically defined.
#define MATERIAL_HAS_NORMAL
// If this is not defined, normal maps won't be enabled.
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// If this is not defined, occlusion won't be taken into account
#define MATERIAL_HAS_EMISSIVE
// If this is not defined, emission won't be taken into account
// MATERIAL_HAS_ANISOTROPY
// If this is set, the material will support anisotropy.
// MATERIAL_HAS_CLEAR_COAT
// If this is set, the material will support clear coat.
// HAS_ATTRIBUTE_COLOR
// If this is not defined, vertex colour will not be available.
#define USE_DFG_LUT
// Whether to use the lookup texture for specular reflection calculation.
// Requires a shader property _DFG to be present and filled.
ENDCG
CGINCLUDE
#ifndef UNITY_PASS_SHADOWCASTER
// Include common files. These will include the other files as needed.
#include "Packages/s-ilent.filamented/Filamented/UnityLightingCommon.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardInput.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardConfig.cginc"
#include "Packages/s-ilent.filamented/Filamented/UnityStandardCore.cginc"
uniform half4 _Color;
uniform half _BumpScale;
uniform half _MetallicScale;
uniform half _OcclusionScale;
uniform half _SmoothnessScale;
uniform half _Emission;
uniform half3 _EmissionColor;
TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex); half4 _MainTex_TexelSize;
TEXTURE2D(_MOESMap); SAMPLER(sampler_MOESMap); half4 _MOESMap_TexelSize;
TEXTURE2D(_BumpMap); SAMPLER(sampler_BumpMap); half4 _BumpMap_TexelSize;
half4 _MainTex_ST;
#if defined(_ANIMATED)
TEXTURE2D_ARRAY(_AnimationMainTex); SAMPLER(sampler_AnimationMainTex); half4 _AnimationMainTex_TexelSize;
TEXTURE2D_ARRAY(_AnimationMOESMap); SAMPLER(sampler_AnimationMOESMap); half4 _AnimationMOESMap_TexelSize;
TEXTURE2D_ARRAY(_AnimationBumpMap); SAMPLER(sampler_AnimationBumpMap); half4 _AnimationBumpMap_TexelSize;
uniform fixed _AnimationMode;
uniform float _AnimationSpeed;
#endif
uniform fixed _QuakeWater;
// Vertex functions are called from UnityStandardCore.
// You can alter values here, or copy the function in and modify it.
VertexOutputForwardBase vertBase (VertexInput v) { return vertForwardBase(v); }
VertexOutputForwardAdd vertAdd (VertexInput v) { return vertForwardAdd(v); }
// Returns pixel sharpened to nearest pixel boundary.
// texSize is Unity _Texture_TexelSize; zw is w/h, xy is 1/wh
float2 sharpSample2( float4 texSize , float2 coord )
{
float2 boxSize = clamp(fwidth(coord) * texSize.zw, 1e-5, 1.0);
coord = coord * texSize.zw - 0.5 * boxSize;
float2 txOffset = smoothstep(1.0 - boxSize, 1.0, frac(coord));
return (floor(coord) + 0.5 + txOffset) * texSize.xy;
}
float4 SampleTexture2DPixelFiltering(TEXTURE2D_PARAM(tex, smp), float2 coord, float4 texSize)
{
float2 boxSize = clamp(fwidth(coord) * texSize.zw, 1e-5, 1);
coord = coord * texSize.zw - 0.5 * boxSize;
float2 txOffset = smoothstep(1 - boxSize, 1, frac(coord));
coord = (floor(coord) + 0.5 + txOffset) * texSize.xy;
return SAMPLE_TEXTURE2D_GRAD(tex, smp, coord, ddx(coord), ddy(coord));
}
float4 SampleTexture2DArrayPixelFiltering(TEXTURE2D_ARRAY_PARAM(tex, smp), float2 coord, float4 texSize, float index)
{
float2 boxSize = clamp(fwidth(coord) * texSize.zw, 1e-5, 1);
coord = coord * texSize.zw - 0.5 * boxSize;
float2 txOffset = smoothstep(1 - boxSize, 1, frac(coord));
coord = (floor(coord) + 0.5 + txOffset) * texSize.xy;
return SAMPLE_TEXTURE2D_ARRAY_GRAD(tex, smp, coord, index, ddx(coord), ddy(coord));
}
// The material function itself! You can alter the code below to add extra properties.
inline MaterialInputs MyMaterialSetup (inout float4 i_tex, float3 i_eyeVec, half3 i_viewDirForParallax, float4 tangentToWorld[3], float3 i_posWorld)
{
i_tex.xy = i_tex * _MainTex_ST.xy + _MainTex_ST.zw;
// Animation stuff first.
if (_QuakeWater)
{
i_tex.xy += float2(sin(_Time.y + i_tex.y * UNITY_PI),cos(_Time.y + i_tex.x * UNITY_PI)) * 0.1;
}
// Sample with derivatives to avoid artifacts.
half4 baseColor = SampleTexture2DPixelFiltering(TEXTURE2D_ARGS(_MainTex, sampler_MainTex), i_tex.xy, _MainTex_TexelSize);
half4 packedMap = SampleTexture2DPixelFiltering(TEXTURE2D_ARGS(_MOESMap, sampler_MOESMap), i_tex.xy, _MOESMap_TexelSize);
half3 normalTangent = UnpackScaleNormal(SampleTexture2DPixelFiltering(TEXTURE2D_ARGS(_BumpMap, sampler_BumpMap), i_tex.xy, _BumpMap_TexelSize), _BumpScale);
#if defined(_ANIMATED)
uint width, height, elements;
_AnimationMainTex.GetDimensions(width, height, elements);
float tex_index = 0;
switch (_AnimationMode) {
case 0:
float t = _Time.y * _AnimationSpeed;
float phase = floor(t); // separate the integer part
t = frac(t); // fractional part of time, in [0, 1)
t = phase % 2 < 1 ? t : 1 - t; // reverse time every other cycle
tex_index = t * (elements - 1);
break;
case 1:
tex_index = floor(frac(_Time.y * _AnimationSpeed) * elements);
break;
}
baseColor = SampleTexture2DArrayPixelFiltering(TEXTURE2D_ARRAY_ARGS(_AnimationMainTex, sampler_AnimationMainTex), i_tex.xy, _AnimationMainTex_TexelSize, tex_index );
#endif
half metallic = packedMap.x * _MetallicScale;
half occlusion = lerp(1, packedMap.y, _OcclusionScale);
half emissionMask = packedMap.z;
half smoothness = packedMap.w * _SmoothnessScale;
MaterialInputs material = (MaterialInputs)0;
initMaterial(material);
material.baseColor = baseColor * _Color;
material.metallic = metallic;
material.roughness = computeRoughnessFromGlossiness(smoothness);
material.normal = normalTangent;
material.emissive.rgb = baseColor.rgb * emissionMask * _Emission * _EmissionColor;
material.emissive.a = 1.0;
material.ambientOcclusion = occlusion;
return material;
}
half4 fragForwardBaseTemplate (VertexOutputForwardBase i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_INSTANCE_ID(i);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardBase(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
GetBakedAttenuation(atten, i.ambientOrLightmapUV.xy, shading.position);
#endif
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndPackedData, IN_WORLDPOS(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG(_unity_fogCoord, c.rgb);
return c;
}
half4 fragForwardAddTemplate (VertexOutputForwardAdd i)
{
UNITY_APPLY_DITHER_CROSSFADE(i.pos.xy);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
ShadingParams shading = (ShadingParams)0;
// Initialize shading with expected parameters
computeShadingParamsForwardAdd(shading, i);
UNITY_LIGHT_ATTENUATION(atten, i, shading.position);
// Your material setup goes here.
MaterialInputs material =
MyMaterialSetup(i.tex, i.eyeVec.xyz, IN_VIEWDIR4PARALLAX_FWDADD(i), i.tangentToWorldAndLightDir, IN_WORLDPOS_FWDADD(i));
prepareMaterial(shading, material);
#if (defined(_NORMALMAP) && defined(NORMALMAP_SHADOW))
float noise = noiseR2(i.pos.xy);
float nmShade = NormalTangentShadow (i.tex, i.lightDirTS, noise);
shading.attenuation = min(shading.attenuation, max(1-nmShade, 0));
#endif
float4 c = evaluateMaterial (shading, material);
UNITY_EXTRACT_FOG_FROM_EYE_VEC(i);
UNITY_APPLY_FOG_COLOR(_unity_fogCoord, c.rgb, half4(0,0,0,0)); // fog towards black in additive pass
return c;
}
half4 fragBase (VertexOutputForwardBase i) : SV_Target { return fragForwardBaseTemplate(i); }
half4 fragAdd (VertexOutputForwardAdd i) : SV_Target { return fragForwardAddTemplate(i); }
#endif
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Cull [_CullMode]
AlphaToMask [_AtoCmode]
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend [_SrcBlend] One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest Equal
Cull [_CullMode]
AlphaToMask [_AtoCmode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
Cull [_CullMode]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#ifndef UNITY_PASS_SHADOWCASTER
#define UNITY_PASS_SHADOWCASTER
#endif
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "Packages/s-ilent.filamented/Filamented/UnityStandardShadow.cginc"
ENDCG
}
}
FallBack "VertexLit"
}

View File

@ -0,0 +1,17 @@
fileFormatVersion: 2
guid: 2dfcee83c1697d34db26ab4c73ff85d1
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _MOESMap: {instanceID: 0}
- _AnimationMainTex: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,268 @@
#ifndef FILAMENT_BRDF_INCLUDED
#define FILAMENT_BRDF_INCLUDED
//------------------------------------------------------------------------------
// BRDF configuration
//------------------------------------------------------------------------------
// Diffuse BRDFs
#define DIFFUSE_LAMBERT 0
#define DIFFUSE_BURLEY 1
// Specular BRDF
// Normal distribution functions
#define SPECULAR_D_GGX 0
// Anisotropic NDFs
#define SPECULAR_D_GGX_ANISOTROPIC 0
// Cloth NDFs
#define SPECULAR_D_CHARLIE 0
// Visibility functions
#define SPECULAR_V_SMITH_GGX 0
#define SPECULAR_V_SMITH_GGX_FAST 1
#define SPECULAR_V_GGX_ANISOTROPIC 2
#define SPECULAR_V_KELEMEN 3
#define SPECULAR_V_NEUBELT 4
// Fresnel functions
#define SPECULAR_F_SCHLICK 0
#define BRDF_DIFFUSE DIFFUSE_BURLEY
#if FILAMENT_QUALITY < FILAMENT_QUALITY_HIGH
#define BRDF_SPECULAR_D SPECULAR_D_GGX
#define BRDF_SPECULAR_V SPECULAR_V_SMITH_GGX_FAST
#define BRDF_SPECULAR_F SPECULAR_F_SCHLICK
#else
#define BRDF_SPECULAR_D SPECULAR_D_GGX
#define BRDF_SPECULAR_V SPECULAR_V_SMITH_GGX
#define BRDF_SPECULAR_F SPECULAR_F_SCHLICK
#endif
#define BRDF_CLEAR_COAT_D SPECULAR_D_GGX
#define BRDF_CLEAR_COAT_V SPECULAR_V_KELEMEN
#define BRDF_ANISOTROPIC_D SPECULAR_D_GGX_ANISOTROPIC
#define BRDF_ANISOTROPIC_V SPECULAR_V_GGX_ANISOTROPIC
#define BRDF_CLOTH_D SPECULAR_D_CHARLIE
#define BRDF_CLOTH_V SPECULAR_V_NEUBELT
//------------------------------------------------------------------------------
// Specular BRDF implementations
//------------------------------------------------------------------------------
half D_GGX(half roughness, half NoH, half3 NxH, const half3 h) {
// Walter et al. 2007, "Microfacet Models for Refraction through Rough Surfaces"
// In mediump, there are two problems computing 1.0 - NoH^2
// 1) 1.0 - NoH^2 suffers floating point cancellation when NoH^2 is close to 1 (highlights)
// 2) NoH doesn't have enough precision around 1.0
// Both problem can be fixed by computing 1-NoH^2 in highp and providing NoH in highp as well
// However, we can do better using Lagrange's identity:
// ||a x b||^2 = ||a||^2 ||b||^2 - (a . b)^2
// since N and H are unit vectors: ||N x H||^2 = 1.0 - NoH^2
// This computes 1.0 - NoH^2 directly (which is close to zero in the highlights and has
// enough precision).
// Overall this yields better performance, keeping all computations in mediump
#if defined(TARGET_MOBILE)
half oneMinusNoHSquared = dot(NxH, NxH);
#else
half oneMinusNoHSquared = 1.0 - NoH * NoH;
#endif
half a = NoH * roughness;
half k = min(roughness / (oneMinusNoHSquared + a * a), 453.5); // 453.5 prevents fp16 overflow
half d = k * (k * (1.0 / PI));
return d;
}
half D_GGX_Anisotropic(half at, half ab, half ToH, half BoH, half NoH) {
// Burley 2012, "Physically-Based Shading at Disney"
// The values at and ab are perceptualRoughness^2, a2 is therefore perceptualRoughness^4
// The dot product below computes perceptualRoughness^8. We cannot fit in fp16 without clamping
// the roughness to too high values so we perform the dot product and the division in fp32
half a2 = at * ab;
float3 d = float3(ab * ToH, at * BoH, a2 * NoH);
float d2 = dot(d, d);
half b2 = a2 / d2;
return a2 * b2 * b2 * (1.0 / PI);
}
half D_Charlie(half roughness, half NoH) {
// Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
half invAlpha = 1.0 / roughness;
half cos2h = NoH * NoH;
half sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16
return (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);
}
half V_SmithGGXCorrelated(half roughness, half NoV, half NoL) {
// Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs"
half a2 = roughness * roughness;
// TODO: lambdaV can be pre-computed for all the lights, it should be moved out of this function
half lambdaV = NoL * sqrt((NoV - a2 * NoV) * NoV + a2);
half lambdaL = NoV * sqrt((NoL - a2 * NoL) * NoL + a2);
// 0.0000077 = nextafter(0.5 / MEDIUMP_FLT_MAX, 1.0) in fp16, so we don't overflow
half v = PREVENT_DIV0(0.5, lambdaV + lambdaL, 0.0000077);
// a2=0 => v = 1 / 4*NoL*NoV => min=1/4, max=+inf
// a2=1 => v = 1 / 2*(NoL+NoV) => min=1/4, max=+inf
return v;
}
half V_SmithGGXCorrelated_Fast(half roughness, half NoV, half NoL) {
// Hammon 2017, "PBR Diffuse Lighting for GGX+Smith Microsurfaces"
// 0.0000077 = nextafter(0.5 / MEDIUMP_FLT_MAX, 1.0) in fp16, so we don't overflow
half v = PREVENT_DIV0(0.5, lerp(2.0 * NoL * NoV, NoL + NoV, roughness), 0.0000077);
return v;
}
half V_SmithGGXCorrelated_Anisotropic(half at, half ab, half ToV, half BoV,
half ToL, half BoL, half NoV, half NoL) {
// Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs"
// TODO: lambdaV can be pre-computed for all the lights, it should be moved out of this function
half lambdaV = NoL * length(half3(at * ToV, ab * BoV, NoV));
half lambdaL = NoV * length(half3(at * ToL, ab * BoL, NoL));
// 0.0000077 = nextafter(0.5 / MEDIUMP_FLT_MAX, 1.0) in fp16, so we don't overflow
half v = PREVENT_DIV0(0.5, lambdaV + lambdaL, 0.0000077);
return v;
}
half V_Kelemen(half LoH) {
// Kelemen 2001, "A Microfacet Based Coupled Specular-Matte BRDF Model with Importance Sampling"
// 0.0000039 = nextafter(0.25 / MEDIUMP_FLT_MAX, 1.0) in fp16, so we don't overflow
return PREVENT_DIV0(0.25, LoH * LoH, 0.0000039);
}
half V_Neubelt(half NoV, half NoL) {
// Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
// 0.00001532 = nextafter(1.0 / MEDIUMP_FLT_MAX, 1.0) in fp16, so we don't overflow
return PREVENT_DIV0(1.0, 4.0 * (NoL + NoV - NoL * NoV), 0.00001532);
}
half3 F_Schlick(const half3 f0, half f90, half VoH) {
// Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering"
return f0 + (f90 - f0) * pow5(1.0 - VoH);
}
half3 F_Schlick(const half3 f0, half VoH) {
half f = pow(1.0 - VoH, 5.0);
return f + f0 * (1.0 - f);
}
half F_Schlick(half f0, half f90, half VoH) {
return f0 + (f90 - f0) * pow5(1.0 - VoH);
}
//------------------------------------------------------------------------------
// Specular BRDF dispatch
//------------------------------------------------------------------------------
half distribution(half roughness, half NoH, half3 NxH, const half3 h) {
#if BRDF_SPECULAR_D == SPECULAR_D_GGX
return D_GGX(roughness, NoH, NxH, h);
#endif
}
half visibility(half roughness, half NoV, half NoL) {
#if BRDF_SPECULAR_V == SPECULAR_V_SMITH_GGX
return V_SmithGGXCorrelated(roughness, NoV, NoL);
#elif BRDF_SPECULAR_V == SPECULAR_V_SMITH_GGX_FAST
return V_SmithGGXCorrelated_Fast(roughness, NoV, NoL);
#endif
}
half3 fresnel(const half3 f0, half LoH) {
#if BRDF_SPECULAR_F == SPECULAR_F_SCHLICK
#if FILAMENT_QUALITY == FILAMENT_QUALITY_LOW
return F_Schlick(f0, LoH); // f90 = 1.0
#else
half f90 = saturate(dot(f0, (50.0 * 0.33)));
return F_Schlick(f0, f90, LoH);
#endif
#endif
}
half3 fresnel(const half3 f0, const half f90, half LoH) {
#if BRDF_SPECULAR_F == SPECULAR_F_SCHLICK
return F_Schlick(f0, f90, LoH);
#endif
}
half distributionAnisotropic(half at, half ab, half ToH, half BoH, half NoH) {
#if BRDF_ANISOTROPIC_D == SPECULAR_D_GGX_ANISOTROPIC
return D_GGX_Anisotropic(at, ab, ToH, BoH, NoH);
#endif
}
half visibilityAnisotropic(half roughness, half at, half ab,
half ToV, half BoV, half ToL, half BoL, half NoV, half NoL) {
#if BRDF_ANISOTROPIC_V == SPECULAR_V_SMITH_GGX
return V_SmithGGXCorrelated(roughness, NoV, NoL);
#elif BRDF_ANISOTROPIC_V == SPECULAR_V_GGX_ANISOTROPIC
return V_SmithGGXCorrelated_Anisotropic(at, ab, ToV, BoV, ToL, BoL, NoV, NoL);
#endif
}
half distributionClearCoat(half roughness, half NoH, half3 NxH, const half3 h) {
#if BRDF_CLEAR_COAT_D == SPECULAR_D_GGX
return D_GGX(roughness, NoH, NxH, h);
#endif
}
half visibilityClearCoat(half LoH) {
#if BRDF_CLEAR_COAT_V == SPECULAR_V_KELEMEN
return V_Kelemen(LoH);
#endif
}
half distributionCloth(half roughness, half NoH) {
#if BRDF_CLOTH_D == SPECULAR_D_CHARLIE
return D_Charlie(roughness, NoH);
#endif
}
half visibilityCloth(half NoV, half NoL) {
#if BRDF_CLOTH_V == SPECULAR_V_NEUBELT
return V_Neubelt(NoV, NoL);
#endif
}
//------------------------------------------------------------------------------
// Diffuse BRDF implementations
//------------------------------------------------------------------------------
half Fd_Lambert() {
return 1.0 / PI;
}
half Fd_Burley(half roughness, half NoV, half NoL, half LoH) {
// Burley 2012, "Physically-Based Shading at Disney"
half f90 = 0.5 + 2.0 * roughness * LoH * LoH;
half lightScatter = F_Schlick(1.0, f90, NoL);
half viewScatter = F_Schlick(1.0, f90, NoV);
return lightScatter * viewScatter * (1.0 / PI);
}
// Energy conserving wrap diffuse term, does *not* include the divide by pi
half Fd_Wrap(half NoL, half w) {
return saturate((NoL + w) / sq(1.0 + w));
}
//------------------------------------------------------------------------------
// Diffuse BRDF dispatch
//------------------------------------------------------------------------------
half diffuse(half roughness, half NoV, half NoL, half LoH) {
#if BRDF_DIFFUSE == DIFFUSE_LAMBERT
return Fd_Lambert();
#elif BRDF_DIFFUSE == DIFFUSE_BURLEY
return Fd_Burley(roughness, NoV, NoL, LoH);
#endif
}
#endif // FILAMENT_BRDF_INCLUDED

View File

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

View File

@ -0,0 +1,112 @@
//------------------------------------------------------------------------------
// Dithering configuration
//------------------------------------------------------------------------------
// Dithering operators
#define DITHERING_NONE 0
#define DITHERING_INTERLEAVED_NOISE 1
#define DITHERING_VLACHOS 2
#define DITHERING_TRIANGLE_NOISE 3
#define DITHERING_TRIANGLE_NOISE_RGB 4
#define DITHERING_OPERATOR DITHERING_TRIANGLE_NOISE
//------------------------------------------------------------------------------
// Noise
//------------------------------------------------------------------------------
// n must be normalized in [0..1] (e.g. texture coordinates)
half triangleNoise(float2 n) {
// triangle noise, in [-1.0..1.0[ range
n = fract(n * float2(5.3987, 5.4421));
n += dot(n.yx, n.xy + float2(21.5351, 14.3137));
float xy = n.x * n.y;
// compute in [0..2[ and remap to [-1.0..1.0[
return fract(xy * 95.4307) + fract(xy * 75.04961) - 1.0;
}
// n must not be normalize (e.g. window coordinates)
half interleavedGradientNoise(float2 n) {
return fract(52.982919 * fract(dot(float2(0.06711, 0.00584), n)));
}
//------------------------------------------------------------------------------
// Dithering
//------------------------------------------------------------------------------
half4 Dither_InterleavedGradientNoise(half4 rgba, const float temporalNoise01) {
// Jimenez 2014, "Next Generation Post-Processing in Call of Duty"
float2 uv = gl_FragCoord.xy + temporalNoise01;
// The noise variable must be to workaround Adreno bug #1096.
float noise = interleavedGradientNoise(uv);
// remap from [0..1[ to [-0.5..0.5[
noise -= 0.5;
return rgba + float4(noise / 255.0);
}
half4 Dither_TriangleNoise(half4 rgba, const float temporalNoise01) {
// Gjøl 2016, "Banding in Games: A Noisy Rant"
float2 uv = gl_FragCoord.xy * frameUniforms.resolution.zw;
uv += float2(0.07 * temporalNoise01);
// The noise variable must be to workaround Adreno bug #1096.
float noise = triangleNoise(uv);
// noise is in [-1..1[
return rgba + float4(noise / 255.0);
}
half4 Dither_Vlachos(half4 rgba, const float temporalNoise01) {
// Vlachos 2016, "Advanced VR Rendering"
float noise = dot(float2(171.0, 231.0), gl_FragCoord.xy + temporalNoise01);
half3 noiseRGB = fract(float3(noise) / float3(103.0, 71.0, 97.0));
// remap from [0..1[ to [-0.5..0.5[
noiseRGB -= 0.5;
return half4(rgba.rgb + (noiseRGB / 255.0), rgba.a);
}
half4 Dither_TriangleNoiseRGB(half4 rgba, const float temporalNoise01) {
// Gjøl 2016, "Banding in Games: A Noisy Rant"
float2 uv = gl_FragCoord.xy * frameUniforms.resolution.zw;
uv += float2(0.07 * temporalNoise01);
half3 noiseRGB = float3(
triangleNoise(uv),
triangleNoise(uv + 0.1337),
triangleNoise(uv + 0.3141));
// noise is in [-1..1[
return rgba + noiseRGB.xyzx / 255.0;
}
//------------------------------------------------------------------------------
// Dithering dispatch
//------------------------------------------------------------------------------
/**
* Dithers the specified RGBA color based on the current time and fragment
* coordinates the input must be in the final color space (including OECF).
* This dithering function assumes we are dithering to an 8-bit target.
* This function dithers the alpha channel assuming premultiplied output
*/
half4 dither(half4 rgba, const float temporalNoise01) {
#if DITHERING_OPERATOR == DITHERING_NONE
return rgba;
#elif DITHERING_OPERATOR == DITHERING_INTERLEAVED_NOISE
return Dither_InterleavedGradientNoise(rgba, temporalNoise01);
#elif DITHERING_OPERATOR == DITHERING_VLACHOS
return Dither_Vlachos(rgba, temporalNoise01);
#elif DITHERING_OPERATOR == DITHERING_TRIANGLE_NOISE
return Dither_TriangleNoise(rgba, temporalNoise01);
#elif DITHERING_OPERATOR == DITHERING_TRIANGLE_NOISE_RGB
return Dither_TriangleNoiseRGB(rgba, temporalNoise01);
#endif
}

View File

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

View File

@ -0,0 +1,119 @@
#ifndef FILAMENT_COMMON_GRAPHICS
#define FILAMENT_COMMON_GRAPHICS
//------------------------------------------------------------------------------
// Common color operations
//------------------------------------------------------------------------------
/**
* Computes the luminance of the specified linear RGB color using the
* luminance coefficients from Rec. 709.
*
* @public-api
*/
half luminance(const half3 linearCol) {
return dot(linearCol, half3(0.2126, 0.7152, 0.0722));
}
/**
* Computes the pre-exposed intensity using the specified intensity and exposure.
* This function exists to force high precision on the two parameters
* ...Which isn't applicable yet.
*/
half computePreExposedIntensity(const float intensity, const float exposure) {
return intensity * exposure;
}
void unpremultiply(inout half4 color) {
color.rgb /= max(color.a, FLT_EPS);
}
/**
* Applies a full range YCbCr to sRGB conversion and returns an RGB color.
*
* @public-api
*/
half3 ycbcrToRgb(half luminance, half2 cbcr) {
// Taken from https://developer.apple.com/documentation/arkit/arframe/2867984-capturedimage
const half4x4 ycbcrToRgbTransform = {
1.0000, 1.0000, 1.0000, 0.0000,
0.0000, -0.3441, 1.7720, 0.0000,
1.4020, -0.7141, 0.0000, 0.0000,
-0.7010, 0.5291, -0.8860, 1.0000
};
return mul(ycbcrToRgbTransform, half4(luminance, cbcr, 1.0)).rgb;
}
//------------------------------------------------------------------------------
// Tone mapping operations
//------------------------------------------------------------------------------
/*
* The input must be in the [0, 1] range.
*/
half3 Inverse_Tonemap_Unreal(const half3 x) {
return (x * -0.155) / (x - 1.019);
}
/**
* Applies the inverse of the tone mapping operator to the specified HDR or LDR
* sRGB (non-linear) color and returns a linear sRGB color. The inverse tone mapping
* operator may be an approximation of the real inverse operation.
*
* @public-api
*/
half3 inverseTonemapSRGB(half3 color) {
// sRGB input
color = clamp(color, 0.0, 1.0);
return Inverse_Tonemap_Unreal(color);
}
/**
* Applies the inverse of the tone mapping operator to the specified HDR or LDR
* linear RGB color and returns a linear RGB color. The inverse tone mapping operator
* may be an approximation of the real inverse operation.
*
* @public-api
*/
half3 inverseTonemap(half3 linearCol) {
// Linear input
linearCol = clamp(linearCol, 0.0, 1.0);
return Inverse_Tonemap_Unreal(pow(linearCol, 1.0 / 2.2));
}
//------------------------------------------------------------------------------
// Common texture operations
//------------------------------------------------------------------------------
/**
* Decodes the specified RGBM value to linear HDR RGB.
*/
half3 decodeRGBM(half4 c) {
c.rgb *= (c.a * 16.0);
return c.rgb * c.rgb;
}
//------------------------------------------------------------------------------
// Common debug
//------------------------------------------------------------------------------
half3 heatmap(half v) {
half3 r = v * 2.1 - half3(1.8, 1.14, 0.3);
return 1.0 - r * r;
}
half3 uintToColorDebug(uint v) {
if (v == 0u) {
return half3(0.0, 1.0, 0.0); // green
} else if (v == 1u) {
return half3(0.0, 0.0, 1.0); // blue
} else if (v == 2u) {
return half3(1.0, 1.0, 0.0); // yellow
} else if (v == 3u) {
return half3(1.0, 0.0, 0.0); // red
} else if (v == 4u) {
return half3(1.0, 0.0, 1.0); // purple
} else if (v == 5u) {
return half3(0.0, 1.0, 1.0); // cyan
}
}
#endif // FILAMENT_COMMON_GRAPHICS

View File

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

View File

@ -0,0 +1,79 @@
#ifndef FILAMENT_COMMON_LIGHTING
#define FILAMENT_COMMON_LIGHTING
struct Light {
float4 colorIntensity; // rgb, pre-exposed intensity
float3 l;
half attenuation;
half NoL;
float3 worldPosition;
};
struct PixelParams {
half3 diffuseColor;
half perceptualRoughness;
half perceptualRoughnessUnclamped;
half3 f0;
half roughness;
half3 dfg;
half3 energyCompensation;
#if defined(MATERIAL_HAS_CLEAR_COAT)
half clearCoat;
half clearCoatPerceptualRoughness;
half clearCoatRoughness;
#endif
#if defined(MATERIAL_HAS_SHEEN_COLOR)
half3 sheenColor;
#if !defined(SHADING_MODEL_CLOTH)
half sheenRoughness;
half sheenPerceptualRoughness;
half sheenScaling;
half sheenDFG;
#endif
#endif
#if defined(MATERIAL_HAS_ANISOTROPY)
half3 anisotropicT;
half3 anisotropicB;
half anisotropy;
#endif
#if defined(SHADING_MODEL_SUBSURFACE) || defined(HAS_REFRACTION)
half thickness;
#endif
#if defined(SHADING_MODEL_SUBSURFACE)
half3 subsurfaceColor;
half subsurfacePower;
#endif
#if defined(SHADING_MODEL_CLOTH) && defined(MATERIAL_HAS_SUBSURFACE_COLOR)
half3 subsurfaceColor;
#endif
#if defined(HAS_REFRACTION)
half etaRI;
half etaIR;
half transmission;
half uThickness;
half3 absorption;
#endif
#if defined(MATERIAL_HAS_GLINT)
float2 uv;
float2 ddx_uv;
float2 ddy_uv;
float glintAlpha;
float glintDensity;
#endif
};
half computeMicroShadowing(half NoL, half visibility) {
// Chan 2018, "Material Advances in Call of Duty: WWII"
half aperture = rsqrt(1.0 - visibility);
half microShadow = saturate(NoL * aperture);
return microShadow * microShadow;
};
#endif // FILAMENT_COMMON_LIGHTING

View File

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

View File

@ -0,0 +1,66 @@
#ifndef FILAMENT_COMMON_MATERIAL
#define FILAMENT_COMMON_MATERIAL
#if defined(TARGET_MOBILE)
// min roughness such that (MIN_PERCEPTUAL_ROUGHNESS^4) > 0 in fp16 (i.e. 2^(-14/4), rounded up)
#define MIN_PERCEPTUAL_ROUGHNESS 0.089
#define MIN_ROUGHNESS 0.007921
#else
#define MIN_PERCEPTUAL_ROUGHNESS 0.045
#define MIN_ROUGHNESS 0.002025
#endif
#define MIN_N_DOT_V 1e-4
half clampNoV(half NoV) {
// Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
return max(NoV, MIN_N_DOT_V);
}
half3 computeDiffuseColor(const half4 baseColor, half metallic) {
return baseColor.rgb * (1.0 - metallic);
}
half3 computeF0(const half4 baseColor, half metallic, half reflectance) {
return baseColor.rgb * metallic + (reflectance * (1.0 - metallic));
}
half computeDielectricF0(half reflectance) {
return 0.16 * reflectance * reflectance;
}
half computeMetallicFromSpecularColor(const half3 specularColor) {
return max3(specularColor);
}
half computeRoughnessFromGlossiness(half glossiness) {
return 1.0 - glossiness;
}
half perceptualRoughnessToRoughness(half perceptualRoughness) {
return perceptualRoughness * perceptualRoughness;
}
half roughnessToPerceptualRoughness(half roughness) {
return sqrt(roughness);
}
half iorToF0(half transmittedIor, half incidentIor) {
return sq((transmittedIor - incidentIor) / (transmittedIor + incidentIor));
}
half f0ToIor(half f0) {
half r = sqrt(f0);
return (1.0 + r) / (1.0 - r);
}
half3 f0ClearCoatToSurface(const half3 f0) {
// Approximation of iorTof0(f0ToIor(f0), 1.5)
// This assumes that the clear coat layer has an IOR of 1.5
#if FILAMENT_QUALITY == FILAMENT_QUALITY_LOW
return saturate(f0 * (f0 * 0.526868 + 0.529324) - 0.0482256);
#else
return saturate(f0 * (f0 * (0.941892 - 0.263008 * f0) + 0.346479) - 0.0285998);
#endif
}
#endif // FILAMENT_COMMON_MATERIAL

View File

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

View File

@ -0,0 +1,125 @@
#ifndef FILAMENT_COMMON_MATH
#define FILAMENT_COMMON_MATH
//------------------------------------------------------------------------------
// Common math
//------------------------------------------------------------------------------
/** @public-api */
#define PI 3.14159265359
/** @public-api */
#define HALF_PI 1.570796327
#define MEDIUMP_FLT_MAX 65504.0
#define MEDIUMP_FLT_MIN 0.00006103515625
#ifdef TARGET_MOBILE
#define FLT_EPS MEDIUMP_FLT_MIN
#define saturateMediump(x) min(x, MEDIUMP_FLT_MAX)
#else
#define FLT_EPS 1e-5
#define saturateMediump(x) x
#endif
#ifdef TARGET_MOBILE
#define PREVENT_DIV0(n, d, magic) ((n) / max(d, magic))
#else
#define PREVENT_DIV0(n, d, magic) ((n) / (d))
#endif
#define atan(x,y) atan2(y,x)
//------------------------------------------------------------------------------
// Scalar operations
//------------------------------------------------------------------------------
/**
* Computes x^5 using only multiply operations.
*
* @public-api
*/
half pow5(half x) {
half x2 = x * x;
return x2 * x2 * x;
}
/**
* Computes x^2 as a single multiplication.
*
* @public-api
*/
half sq(half x) {
return x * x;
}
//------------------------------------------------------------------------------
// Vector operations
//------------------------------------------------------------------------------
/**
* Returns the maximum component of the specified vector.
*
* @public-api
*/
half max3(const half3 v) {
return max(v.x, max(v.y, v.z));
}
half vmax(const half2 v) {
return max(v.x, v.y);
}
half vmax(const half3 v) {
return max(v.x, max(v.y, v.z));
}
half vmax(const half4 v) {
return max(max(v.x, v.y), max(v.y, v.z));
}
/**
* Returns the minimum component of the specified vector.
*
* @public-api
*/
half min3(const half3 v) {
return min(v.x, min(v.y, v.z));
}
half vmin(const half2 v) {
return min(v.x, v.y);
}
half vmin(const half3 v) {
return min(v.x, min(v.y, v.z));
}
half vmin(const half4 v) {
return min(min(v.x, v.y), min(v.y, v.z));
}
//------------------------------------------------------------------------------
// Trigonometry
//------------------------------------------------------------------------------
/**
* Approximates acos(x) with a max absolute error of 9.0x10^-3.
* Valid in the range -1..1.
*/
half acosFast(half x) {
// Lagarde 2014, "Inverse trigonometric functions GPU optimization for AMD GCN architecture"
// This is the approximation of degree 1, with a max absolute error of 9.0x10^-3
half y = abs(x);
half p = -0.1565827 * y + 1.570796;
p *= sqrt(1.0 - y);
return x >= 0.0 ? p : PI - p;
}
/**
* Approximates acos(x) with a max absolute error of 9.0x10^-3.
* Valid only in the range 0..1.
*/
half acosFastPositive(half x) {
half p = -0.1565827 * x + 1.570796;
return p * sqrt(1.0 - x);
}
#endif // FILAMENT_COMMON_MATH

View File

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

View File

@ -0,0 +1,120 @@
#ifndef FILAMENT_COMMON_OCCLUSION
#define FILAMENT_COMMON_OCCLUSION
//------------------------------------------------------------------------------
// Ambient occlusion configuration
//------------------------------------------------------------------------------
// Diffuse BRDFs
#define SPECULAR_AO_OFF 0
#define SPECULAR_AO_SIMPLE 1
#define SPECULAR_AO_BENT_NORMALS 2
//------------------------------------------------------------------------------
// Ambient occlusion helpers
//------------------------------------------------------------------------------
half SpecularAO_Lagarde(half NoV, half visibility, half roughness) {
// Lagarde and de Rousiers 2014, "Moving Frostbite to PBR"
return saturate(pow(NoV + visibility, exp2(-16.0 * roughness - 1.0)) - 1.0 + visibility);
}
#if defined(MATERIAL_HAS_BENT_NORMAL)
half sphericalCapsIntersection(half cosCap1, half cosCap2, half cosDistance) {
// Oat and Sander 2007, "Ambient Aperture Lighting"
// Approximation mentioned by Jimenez et al. 2016
half r1 = acosFastPositive(cosCap1);
half r2 = acosFastPositive(cosCap2);
half d = acosFast(cosDistance);
// We work with cosine angles, replace the original paper's use of
// cos(min(r1, r2)) with max(cosCap1, cosCap2)
// We also remove a multiplication by 2 * PI to simplify the computation
// since we divide by 2 * PI in computeBentSpecularAO()
if (min(r1, r2) <= max(r1, r2) - d) {
return 1.0 - max(cosCap1, cosCap2);
} else if (r1 + r2 <= d) {
return 0.0;
}
half delta = abs(r1 - r2);
half x = 1.0 - saturate((d - delta) / max(r1 + r2 - delta, 1e-4));
// simplified smoothstep()
half area = sq(x) * (-2.0 * x + 3.0);
return area * (1.0 - max(cosCap1, cosCap2));
}
#endif
// This function could (should?) be implemented as a 3D LUT instead, but we need to save samplers
half SpecularAO_Cones(half NoV, half visibility, half roughness) {
#if defined(MATERIAL_HAS_BENT_NORMAL)
// Jimenez et al. 2016, "Practical Realtime Strategies for Accurate Indirect Occlusion"
// aperture from ambient occlusion
half cosAv = sqrt(1.0 - visibility);
// aperture from roughness, log(10) / log(2) = 3.321928
half cosAs = exp2(-3.321928 * sq(roughness));
// angle betwen bent normal and reflection direction
half cosB = dot(shading_bentNormal, shading_reflected);
// Remove the 2 * PI term from the denominator, it cancels out the same term from
// sphericalCapsIntersection()
half ao = sphericalCapsIntersection(cosAv, cosAs, cosB) / (1.0 - cosAs);
// Smoothly kill specular AO when entering the perceptual roughness range [0.1..0.3]
// Without this, specular AO can remove all reflections, which looks bad on metals
return lerp(1.0, ao, smoothstep(0.01, 0.09, roughness));
#else
return SpecularAO_Lagarde(NoV, visibility, roughness);
#endif
}
/**
* Computes a specular occlusion term from the ambient occlusion term.
*/
half computeSpecularAO(half NoV, half visibility, half roughness) {
#if SPECULAR_AMBIENT_OCCLUSION == SPECULAR_AO_SIMPLE
return SpecularAO_Lagarde(NoV, visibility, roughness);
#elif SPECULAR_AMBIENT_OCCLUSION == SPECULAR_AO_BENT_NORMALS
return SpecularAO_Cones(NoV, visibility, roughness);
#else
return 1.0;
#endif
}
#if MULTI_BOUNCE_AMBIENT_OCCLUSION == 1
/**
* Returns a color ambient occlusion based on a pre-computed visibility term.
* The albedo term is meant to be the diffuse color or f0 for the diffuse and
* specular terms respectively.
*/
half3 gtaoMultiBounce(half visibility, const half3 albedo) {
// Jimenez et al. 2016, "Practical Realtime Strategies for Accurate Indirect Occlusion"
half3 a = 2.0404 * albedo - 0.3324;
half3 b = -4.7951 * albedo + 0.6417;
half3 c = 2.7552 * albedo + 0.6903;
return max((visibility), ((visibility * a + b) * visibility + c) * visibility);
}
#endif
void multiBounceAO(half visibility, const half3 albedo, inout half3 color) {
#if MULTI_BOUNCE_AMBIENT_OCCLUSION == 1
color *= gtaoMultiBounce(visibility, albedo);
#endif
}
void multiBounceSpecularAO(half visibility, const half3 albedo, inout half3 color) {
#if MULTI_BOUNCE_AMBIENT_OCCLUSION == 1 && SPECULAR_AMBIENT_OCCLUSION != SPECULAR_AO_OFF
color *= gtaoMultiBounce(visibility, albedo);
#endif
}
half singleBounceAO(half visibility) {
#if MULTI_BOUNCE_AMBIENT_OCCLUSION == 1
return 1.0;
#else
return visibility;
#endif
}
#endif // FILAMENT_COMMON_OCCLUSION

View File

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

View File

@ -0,0 +1,57 @@
#ifndef FILAMENT_COMMON_SHADING
#define FILAMENT_COMMON_SHADING
/*
// These variables should be in a struct but some GPU drivers ignore the
// precision qualifier on individual struct members
highp float3x3 shading_tangentToWorld; // TBN matrix
highp float3 shading_position; // position of the fragment in world space
float3 shading_view; // normalized vector from the fragment to the eye
float3 shading_normal; // normalized transformed normal, in world space
float3 shading_geometricNormal; // normalized geometric normal, in world space
float3 shading_reflected; // reflection of view about normal
float shading_NoV; // dot(normal, view), always strictly >= MIN_N_DOT_V
#if defined(MATERIAL_HAS_BENT_NORMAL)
float3 shading_bentNormal; // normalized transformed normal, in world space
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT)
float3 shading_clearCoatNormal; // normalized clear coat layer normal, in world space
#endif
highp float2 shading_normalizedViewportCoord;
*/
// Worry about that problem later.
struct ShadingParams {
float3x3 tangentToWorld; // TBN matrix
float3 position; // position of the fragment in world space
half3 view; // normalized vector from the fragment to the eye
half3 normal; // normalized transformed normal, in world space
half3 geometricNormal; // normalized geometric normal, in world space
half3 reflected; // reflection of view about normal
half NoV; // dot(normal, view), always strictly >= MIN_N_DOT_V
#if defined(MATERIAL_HAS_BENT_NORMAL)
half3 bentNormal; // normalized transformed normal, in world space
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT)
half3 clearCoatNormal; // normalized clear coat layer normal, in world space
#endif
half2 normalizedViewportCoord;
// These parameters are provided to inject Unity lighting into Filament data.
half attenuation;
half3 ambient;
half4 lightmapUV;
#if defined(USING_BAKERY_VERTEXLMSH)
half3 ambientSH[3];
#elif defined(USING_BAKERY_VERTEXLMDIR)
half3 ambientDir;
#endif
};
#endif // FILAMENT_COMMON_SHADING

View File

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

View File

@ -0,0 +1,90 @@
#ifndef FILAMENT_LIGHT_DIRECTIONAL
#define FILAMENT_LIGHT_DIRECTIONAL
#include "UnityLightingCommon.cginc"
//------------------------------------------------------------------------------
// Directional light evaluation
//------------------------------------------------------------------------------
#if FILAMENT_QUALITY < FILAMENT_QUALITY_HIGH
//#define SUN_AS_AREA_LIGHT
#endif
half3 sampleSunAreaLight(const half3 lightDirection, const ShadingParams shading) {
// Replaced frameUniforms.sun
#if defined(SUN_AS_AREA_LIGHT)
// cos(sunAngle), sin(sunAngle), 1/(sunAngle*HALO_SIZE-sunAngle), HALO_EXP
static const half sunAngle = 0.00951f;
static const half sunHaloSize = 10.0f;
static const half sunHaloFalloff = 80.0f;
static const half4 sunParameters = half4(cos(sunAngle), sin(sunAngle), 1/(sunAngle*sunHaloSize-sunAngle), sunHaloFalloff);
if (sunParameters.w >= 0.0) {
// simulate sun as disc area light
half LoR = dot(lightDirection, shading.reflected);
half d = sunParameters.x;
float3 s = shading.reflected - LoR * lightDirection;
return LoR < d ?
normalize(lightDirection * d + normalize(s) * sunParameters.y) : shading.reflected;
}
#endif
return lightDirection;
}
half4 UnityLight_ColorIntensitySeperated() {
return half4(_LightColor0.xyz, 1.0);
if (_LightColor0.w <= 0) return 0.0;
_LightColor0 += 0.000001;
return half4(_LightColor0.xyz / _LightColor0.w, _LightColor0.w);
}
Light getDirectionalLight(ShadingParams shading) {
Light light;
// note: lightColorIntensity.w is always premultiplied by the exposure
light.colorIntensity = UnityLight_ColorIntensitySeperated();
light.l = sampleSunAreaLight(_WorldSpaceLightPos0.xyz, shading);
light.attenuation = 1.0;
light.NoL = saturate(dot(shading.normal, light.l));
return light;
}
// Much of this function has changed from the original because we still use
// Unity's BIRP shadow handling. Sorry!
void evaluateDirectionalLight(const ShadingParams shading, const MaterialInputs material,
const PixelParams pixel, inout half3 color) {
Light light = getDirectionalLight(shading);
half visibility = 1.0;
#if defined(HAS_SHADOWING)
if (light.NoL > 0.0) {
half ssContactShadowOcclusion = 0.0;
// hasDirectionalShadows && cascadeHasVisibleShadows
if (1) {
visibility*=shading.attenuation;
// apply directional shadows to visibility here
}
// if contact shadows are enabled
if (true && visibility > 0.0) {
// ssContactShadowOcclusion = screenSpaceContactShadow(light.l);
}
visibility *= 1.0 - ssContactShadowOcclusion;
#if defined(MATERIAL_HAS_AMBIENT_OCCLUSION)
visibility *= computeMicroShadowing(light.NoL, material.ambientOcclusion * 1.6 + 0.2);
#endif
} else {
#if defined(MATERIAL_CAN_SKIP_LIGHTING)
return;
#endif
}
#elif defined(MATERIAL_CAN_SKIP_LIGHTING)
if (light.NoL <= 0.0) return;
#endif
color.rgb += surfaceShading(shading, pixel, light, visibility);
}
#endif // FILAMENT_LIGHT_DIRECTIONAL

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -0,0 +1,55 @@
#ifndef FILAMENT_LIGHT_LTCGI
#define FILAMENT_LIGHT_LTCGI
#if defined(_LTCGI)
#if defined(_SPECULARHIGHLIGHTS_OFF)
#define LTCGI_SPECULAR_OFF
#endif
#include "Packages/at.pimaker.ltcgi/Shaders/LTCGI_structs.cginc"
struct accumulator_struct {
half3 diffuse;
half3 specular;
half3 specularIntensity;
};
void callback_diffuse(inout accumulator_struct acc, in ltcgi_output output);
void callback_specular(inout accumulator_struct acc, in ltcgi_output output);
#define LTCGI_V2_CUSTOM_INPUT accumulator_struct
#define LTCGI_V2_DIFFUSE_CALLBACK callback_diffuse
#define LTCGI_V2_SPECULAR_CALLBACK callback_specular
#include "Packages/at.pimaker.ltcgi/Shaders/LTCGI.cginc"
void callback_diffuse(inout accumulator_struct acc, in ltcgi_output output) {
acc.diffuse += output.intensity * output.color;
}
void callback_specular(inout accumulator_struct acc, in ltcgi_output output) {
acc.specular += output.intensity * output.color;
acc.specularIntensity += output.intensity;
}
#endif
//------------------------------------------------------------------------------
// LTCGI evaluation
//------------------------------------------------------------------------------
// This is a small function to abstract the calls to the LTCGI functions.
void evaluateLTCGI(const ShadingParams shading, const PixelParams pixel, inout half3 color) {
#if defined(_LTCGI)
accumulator_struct acc = (accumulator_struct)0;
LTCGI_Contribution(
acc,
shading.position,
shading.normal,
shading.view,
pixel.perceptualRoughness,
shading.lightmapUV.xy
);
color.rgb += acc.specular + acc.diffuse;
#endif
}
#endif // FILAMENT_LIGHT_LTCGI

View File

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

View File

@ -0,0 +1,113 @@
#ifndef FILAMENT_LIGHT_MIRROR
#define FILAMENT_LIGHT_MIRROR
// Commmon code for sampling from VRC (or similar) mirrors systems.
//
// Use a mirror as the source for the reflection. Multiple samples taken for roughness.
// This is a rough approximation for performance's sake.
// Based on https://www.shadertoy.com/view/DtBXDt (CC0)
#if defined(MIRROR_REFLECTION)
UNITY_DECLARE_TEX2D_FLOAT(_ReflectionTex0);
UNITY_DECLARE_TEX2D_FLOAT(_ReflectionTex1);
#endif
class MirrorReflectionSampler
{
// Calculate R2 for index i
float2 getR2(float2 i) {
return frac(i * float2(0.245122333753, 0.430159709002));
}
uint hilbert_idx(uint2 uv, uint offset)
{
// Hilbert curve:
uint C = 0xB4361E9Cu;// cost lookup
uint P = 0xEC7A9107u;// pattern lookup
uv += uint(offset) * uint2(2447445397u, 3242174893u);
uint c = 0u;// accumulated cost
uint p = 0u;// current pattern
const uint N = 7u;// tile size = 2^N
for(uint i = N; --i < N;)
{
uint2 m = (uv >> i) & 1u;// local uv
uint n = m.x ^ (m.y << 1u);// linearized local uv
uint o = (p << 3u) ^ (n << 1u);// offset into lookup tables
c += ((C >> o) & 3u) << (i << 1u);// accu cost (scaled by layer)
p = (P >> o) & 3u;// update pattern
}
return c;
}
inline half4 getMirrorReflection(float2 screenCoord) {
half4 refl = 0;
#if defined(MIRROR_REFLECTION)
refl = (unity_StereoEyeIndex == 0)
? UNITY_SAMPLE_TEX2D(_ReflectionTex0, screenCoord)
: UNITY_SAMPLE_TEX2D(_ReflectionTex1, screenCoord);
#endif // MIRROR_REFLECTION
return refl;
}
inline half4 getFilteredMirrorRadiance(const ShadingParams shading, float roughness) {
half4 refl = 0;
half weight = 0;
#if defined(MIRROR_REFLECTION)
float2 refSize;
_ReflectionTex0.GetDimensions(refSize.x, refSize.y);
// Since it's possible the user might not know the resolution will have
// a big impact on performance, force a resolution scale.
half totalPixels = refSize.x * refSize.y;
const half minArea = 256.0 * 256.0;
const half maxArea = 1024.0 * 1024.0;
half resScale = saturate((totalPixels - minArea) / (maxArea - minArea));
// If there is no mirror texture, exit.
if (totalPixels <= 0) return 0;
float3 normalOffset = shading.geometricNormal - shading.normal;
half2 normalVS = mul((float3x3)UNITY_MATRIX_V, normalOffset);
half2 screenCoord = shading.normalizedViewportCoord;
// At 256 or lower, do the full 64 samples and use a low roughness cutoff.
// At 1024 or higher, perform only one sample and no roughness.
half roughnessCutoff = lerp(0.1h, 0.01h, resScale);
uint N = clamp(uint(lerp(64.0h, 1.0h, resScale)), 1, 64); // sample count
half dmax = roughness * lerp(4.0h, 0.01h, resScale); // max blur distance
if (roughness >= roughnessCutoff) return 0;
float sigma = dmax / 2.5;
sigma *= sigma;
half idx = fmod(hilbert_idx(uint2(screenCoord * _ScreenParams.xy), 0), 100000.0h);
half sampleMask = 1.0;
[loop]
for (uint i = 0.0; i < N; i++) {
half2 uvoff = dmax * (getR2(half2(idx + i, idx + i + 1)) - 0.5);
half bw = exp(-dot(uvoff, uvoff) / sigma);
half2 sampleCoord = screenCoord + uvoff + normalVS;
sampleMask *= 1.0 - length(saturate(sampleCoord) - sampleCoord) * bw;
refl += bw * max(0, getMirrorReflection(sampleCoord));
weight += bw;
}
refl /= weight;
refl.a = 1 - saturate((roughness - MIN_ROUGHNESS) / roughnessCutoff) * sampleMask;
#endif // MIRROR_REFLECTION
return max(0, refl);
}
};
#endif // FILAMENT_LIGHT_MIRROR

View File

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

View File

@ -0,0 +1,89 @@
#ifndef FILAMENT_LIGHT_DYNAMIC
#define FILAMENT_LIGHT_DYNAMIC
#include "UnityLightingCommon.cginc"
//------------------------------------------------------------------------------
// Punctual lights evaluation
//------------------------------------------------------------------------------
// This is based off light_directional, not light_punctual, because of Unity's
// light model.
half4 UnityLight_ColorIntensitySeperated_Punctual() {
return half4(_LightColor0.xyz, 1.0);
if (_LightColor0.w <= 0) return 0.0;
return half4(_LightColor0.xyz / _LightColor0.w, _LightColor0.w);
}
half getSquareFalloffAttenuation(half distanceSquare, half falloff) {
half factor = distanceSquare * falloff;
half smoothFactor = saturate(1.0 - factor * factor);
// We would normally divide by the square distance here
// but we do it at the call site
return smoothFactor * smoothFactor;
}
half getDistanceAttenuation(const half3 posToLight, half falloff) {
half distanceSquare = dot(posToLight, posToLight);
half attenuation = getSquareFalloffAttenuation(distanceSquare, falloff);
// Assume a punctual light occupies a volume of 1cm to avoid a division by 0
return attenuation * 1.0 / max(distanceSquare, 1e-4);
}
half getAngleAttenuation(const half3 lightDir, const half3 l, const half2 scaleOffset) {
half cd = dot(lightDir, l);
half attenuation = saturate(cd * scaleOffset.x + scaleOffset.y);
return attenuation * attenuation;
}
Light getLight(ShadingParams shading) {
Light light;
// position-to-light vector
float3 posToLight = _WorldSpaceLightPos0.xyz - shading.position;
// note: lightColorIntensity.w is always premultiplied by the exposure
light.colorIntensity = UnityLight_ColorIntensitySeperated_Punctual();
light.l = normalize(posToLight);
light.attenuation = shading.attenuation; //getDistanceAttenuation(posToLight, _WorldSpaceLightPos0.w);
light.NoL = saturate(dot(shading.normal, light.l));
light.worldPosition = _WorldSpaceLightPos0.xyz;
return light;
}
// Much of this function has changed from the original because we still use
// Unity's BIRP shadow handling. Sorry!
void evaluatePunctualLights(const ShadingParams shading, const PixelParams pixel, inout half3 color) {
Light light = getLight(shading);
half visibility = 1.0;
#if defined(HAS_SHADOWING)
if (light.NoL > 0.0) {
float ssContactShadowOcclusion = 0.0;
// hasDirectionalShadows && cascadeHasVisibleShadows
if (1) {
//visibility*=shading.attenuation;
// apply directional shadows to visibility here
}
// if contact shadows are enabled
if (true && visibility > 0.0) {
// ssContactShadowOcclusion = screenSpaceContactShadow(light.l);
}
visibility *= 1.0 - ssContactShadowOcclusion;
} else {
#if defined(MATERIAL_CAN_SKIP_LIGHTING)
return;
#endif
}
#elif defined(MATERIAL_CAN_SKIP_LIGHTING)
if (light.NoL <= 0.0) return;
#endif
color.rgb += surfaceShading(shading, pixel, light, visibility);
}
#endif // FILAMENT_LIGHT_DYNAMIC

View File

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

View File

@ -0,0 +1,9 @@
#ifndef FILAMENT_LIGHT_VRCLV
#define FILAMENT_LIGHT_VRCLV
#include "SharedSHLib.hlsl"
#if defined(_VRCLV)
#include "LightVolumes.cginc"
#endif
#endif // FILAMENT_LIGHT_VRCLV

View File

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

View File

@ -0,0 +1,217 @@
#ifndef FILAMENT_MATERIAL_INPUTS
#define FILAMENT_MATERIAL_INPUTS
// Decide if we can skip lighting when dot(n, l) <= 0.0
#if defined(SHADING_MODEL_CLOTH)
#if !defined(MATERIAL_HAS_SUBSURFACE_COLOR)
#define MATERIAL_CAN_SKIP_LIGHTING
#endif
#elif defined(SHADING_MODEL_SUBSURFACE)
// Cannot skip lighting
#else
#define MATERIAL_CAN_SKIP_LIGHTING
#endif
struct MaterialInputs {
half4 baseColor;
#if !defined(SHADING_MODEL_UNLIT)
#if !defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
half roughness;
#endif
#if !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
half metallic;
half reflectance;
#endif
half ambientOcclusion;
#endif
half4 emissive;
#if !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SUBSURFACE) && !defined(SHADING_MODEL_UNLIT)
half3 sheenColor;
half sheenRoughness;
#endif
#if defined(MATERIAL_HAS_GLINT)
float2 uv;
float glintAlpha;
float glintDensity;
#endif
half clearCoat;
half clearCoatRoughness;
half anisotropy;
half3 anisotropyDirection;
#if defined(SHADING_MODEL_SUBSURFACE) || defined(HAS_REFRACTION)
half thickness;
#endif
#if defined(SHADING_MODEL_SUBSURFACE)
half subsurfacePower;
half3 subsurfaceColor;
#endif
#if defined(SHADING_MODEL_CLOTH)
half3 sheenColor;
#if defined(MATERIAL_HAS_SUBSURFACE_COLOR)
half3 subsurfaceColor;
#endif
#endif
#if defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
half3 specularColor;
half glossiness;
#endif
#if defined(MATERIAL_HAS_NORMAL)
half3 normal;
#endif
#if defined(MATERIAL_HAS_BENT_NORMAL)
half3 bentNormal;
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT) && defined(MATERIAL_HAS_CLEAR_COAT_NORMAL)
half3 clearCoatNormal;
#endif
#if defined(MATERIAL_HAS_POST_LIGHTING_COLOR)
half4 postLightingColor;
#endif
#if !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SUBSURFACE) && !defined(SHADING_MODEL_UNLIT)
#if defined(HAS_REFRACTION)
#if defined(MATERIAL_HAS_ABSORPTION)
half3 absorption;
#endif
#if defined(MATERIAL_HAS_TRANSMISSION)
half transmission;
#endif
#if defined(MATERIAL_HAS_IOR)
half ior;
#endif
#if defined(MATERIAL_HAS_MICRO_THICKNESS) && (REFRACTION_TYPE == REFRACTION_TYPE_THIN)
half microThickness;
#endif
#elif !defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
#if defined(MATERIAL_HAS_IOR)
half ior;
#endif
#endif
#endif
};
void initMaterial(out MaterialInputs material) {
material = (MaterialInputs)0;
material.baseColor = 1.0;
#if !defined(SHADING_MODEL_UNLIT)
#if !defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
material.roughness = 1.0;
#endif
#if !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
material.metallic = 0.0;
material.reflectance = 0.5;
#endif
material.ambientOcclusion = 1.0;
#endif
material.emissive = half4(half3(0.0.xxx), 1.0);
#if !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SUBSURFACE) && !defined(SHADING_MODEL_UNLIT)
#if defined(MATERIAL_HAS_SHEEN_COLOR)
material.sheenColor = half3(0.0.xxx);
material.sheenRoughness = 0.0;
#endif
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT)
material.clearCoat = 1.0;
material.clearCoatRoughness = 0.0;
#endif
#if defined(MATERIAL_HAS_ANISOTROPY)
material.anisotropy = 0.0;
material.anisotropyDirection = half3(1.0, 0.0, 0.0);
#endif
#if defined(SHADING_MODEL_SUBSURFACE) || defined(HAS_REFRACTION)
material.thickness = 0.5;
#endif
#if defined(SHADING_MODEL_SUBSURFACE)
material.subsurfacePower = 12.234;
material.subsurfaceColor = half3(1.0.xxx);
#endif
#if defined(SHADING_MODEL_CLOTH)
material.sheenColor = sqrt(material.baseColor.rgb);
#if defined(MATERIAL_HAS_SUBSURFACE_COLOR)
material.subsurfaceColor = half3(0.0.xxx);
#endif
#endif
#if defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
material.glossiness = 0.0;
material.specularColor = half3(0.0.xxx);
#endif
#if defined(MATERIAL_HAS_NORMAL)
material.normal = half3(0.0, 0.0, 1.0);
#endif
#if defined(MATERIAL_HAS_BENT_NORMAL)
material.bentNormal = half3(0.0, 0.0, 1.0);
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT) && defined(MATERIAL_HAS_CLEAR_COAT_NORMAL)
material.clearCoatNormal = half3(0.0, 0.0, 1.0);
#endif
#if defined(MATERIAL_HAS_POST_LIGHTING_COLOR)
material.postLightingColor = half4(0.0.xxx);
#endif
#if defined(MATERIAL_HAS_GLINT)
material.uv = float2(0.0, 0.0);
material.glintAlpha = 0.05;
material.glintDensity = 10000.0;
#endif
#if !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SUBSURFACE) && !defined(SHADING_MODEL_UNLIT)
#if defined(HAS_REFRACTION)
#if defined(MATERIAL_HAS_ABSORPTION)
material.absorption = half3(0.0.xxx);
#endif
#if defined(MATERIAL_HAS_TRANSMISSION)
material.transmission = 1.0;
#endif
#if defined(MATERIAL_HAS_IOR)
material.ior = 1.5;
#endif
#if defined(MATERIAL_HAS_MICRO_THICKNESS) && (REFRACTION_TYPE == REFRACTION_TYPE_THIN)
material.microThickness = 0.0;
#endif
#elif !defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
#if defined(MATERIAL_HAS_IOR)
material.ior = 1.5;
#endif
#endif
#endif
}
#if defined(MATERIAL_HAS_CUSTOM_SURFACE_SHADING)
/** @public-api */
struct LightData {
half4 colorIntensity;
half3 l;
half NdotL;
half3 worldPosition;
half attenuation;
half visibility;
};
/** @public-api */
struct ShadingData {
half3 diffuseColor;
half perceptualRoughness;
half3 f0;
half roughness;
};
#endif
#endif // FILAMENT_MATERIAL_INPUTS

View File

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

View File

@ -0,0 +1,58 @@
#ifndef FILAMENT_SHADING_CLOTH_INCLUDED
#define FILAMENT_SHADING_CLOTH_INCLUDED
#include "FilamentBRDF.cginc"
/**
* Evaluates lit materials with the cloth shading model. Similar to the standard
* model, the cloth shading model is based on a Cook-Torrance microfacet model.
* Its distribution and visibility terms are however very different to take into
* account the softer apperance of many types of cloth. Some highly reflecting
* fabrics like satin or leather should use the standard model instead.
*
* This shading model optionally models subsurface scattering events. The
* computation of these events is not physically based but can add necessary
* details to a material.
*/
half3 surfaceShading(const ShadingParams shading, const PixelParams pixel, const Light light, half occlusion) {
half3 h = normalize(shading.view + light.l);
half NoL = light.NoL;
half NoH = saturate(dot(shading.normal, h));
half LoH = saturate(dot(light.l, h));
// specular BRDF
half D = distributionCloth(pixel.roughness, NoH);
half V = visibilityCloth(shading.NoV, NoL);
half3 F = pixel.f0;
// Ignore pixel.energyCompensation since we use a different BRDF here
half3 Fr = (D * V) * F;
// diffuse BRDF
half diffuseLobe = diffuse(pixel.roughness, shading.NoV, NoL, LoH);
#if defined(MATERIAL_HAS_SUBSURFACE_COLOR)
// Energy conservative wrap diffuse to simulate subsurface scattering
diffuseLobe *= Fd_Wrap(dot(shading.normal, light.l), 0.5);
#endif
// We do not multiply the diffuse term by the Fresnel term as discussed in
// Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
// The effect is fairly subtle and not deemed worth the cost for mobile
half3 Fd = diffuseLobe * pixel.diffuseColor;
#if defined(MATERIAL_HAS_SUBSURFACE_COLOR)
// Cheap subsurface scatter
Fd *= saturate(pixel.subsurfaceColor + NoL);
// We need to apply NoL separately to the specular lobe since we already took
// it into account in the diffuse lobe
half3 color = Fd + Fr * NoL;
color *= light.colorIntensity.rgb * (light.colorIntensity.w * light.attenuation * occlusion);
#else
half3 color = Fd + Fr;
color *= light.colorIntensity.rgb * (light.colorIntensity.w * light.attenuation * NoL * occlusion);
#endif
return color;
}
#endif // FILAMENT_SHADING_CLOTH_INCLUDED

View File

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

View File

@ -0,0 +1,371 @@
#ifndef FILAMENT_SHADING_LIT
#define FILAMENT_SHADING_LIT
#include "FilamentMaterialInputs.cginc"
#include "FilamentCommonMath.cginc"
#include "FilamentCommonGraphics.cginc"
#include "FilamentCommonLighting.cginc"
#include "FilamentCommonMaterial.cginc"
#include "FilamentCommonShading.cginc"
#if defined(SHADING_MODEL_SUBSURFACE)
#include "FilamentShadingSubsurface.cginc"
#elif defined(SHADING_MODEL_CLOTH)
#include "FilamentShadingCloth.cginc"
#else
#include "FilamentShadingStandard.cginc"
#endif
#include "FilamentLightIndirect.cginc"
#include "FilamentShadingLit.cginc"
#include "FilamentLightDirectional.cginc"
#include "FilamentLightPunctual.cginc"
#include "FilamentLightLTCGI.cginc"
#include "UnityStandardInput.cginc"
//------------------------------------------------------------------------------
// Lighting
//------------------------------------------------------------------------------
#if defined(BLEND_MODE_MASKED)
half computeMaskedAlpha(half a) {
// Use derivatives to smooth alpha tested edges
return (a - getMaskThreshold()) / max(fwidth(a), 1e-3) + 0.5;
}
half computeDiffuseAlpha(half a) {
// If we reach this point in the code, we already know that the fragment is not discarded due
// to the threshold factor. Therefore we can just output 1.0, which prevents a "punch through"
// effect from occuring. We do this only for TRANSLUCENT views in order to prevent breakage
// of ALPHA_TO_COVERAGE.
return (NEEDS_ALPHA_CHANNEL == 1.0) ? 1.0 : a;
}
void applyAlphaMask(inout float4 baseColor) {
baseColor.a = computeMaskedAlpha(baseColor.a);
if (baseColor.a <= 0.0) {
discard;
}
}
#else // not masked
float computeDiffuseAlpha(float a) {
#if defined(BLEND_MODE_TRANSPARENT) || defined(BLEND_MODE_FADE)
return a;
#else
return 1.0;
#endif
}
void applyAlphaMask(inout float4 baseColor) {}
#endif
#if defined(GEOMETRIC_SPECULAR_AA)
half normalFiltering(half perceptualRoughness, const half3 worldNormal) {
// Kaplanyan 2016, "Stable specular highlights"
// Tokuyoshi 2017, "Error Reduction and Simplification for Shading Anti-Aliasing"
// Tokuyoshi and Kaplanyan 2019, "Improved Geometric Specular Antialiasing"
// This implementation is meant for deferred rendering in the original paper but
// we use it in forward rendering as well (as discussed in Tokuyoshi and Kaplanyan
// 2019). The main reason is that the forward version requires an expensive transform
// of the half vector by the tangent frame for every light. This is therefore an
// approximation but it works well enough for our needs and provides an improvement
// over our original implementation based on Vlachos 2015, "Advanced VR Rendering".
half3 du = ddx(worldNormal);
half3 dv = ddy(worldNormal);
half variance = _specularAntiAliasingVariance * (dot(du, du) + dot(dv, dv));
half roughness = perceptualRoughnessToRoughness(perceptualRoughness);
half kernelRoughness = min(2.0 * variance, _specularAntiAliasingThreshold);
half squareRoughness = saturate(roughness * roughness + kernelRoughness);
return roughnessToPerceptualRoughness(sqrt(squareRoughness));
}
#endif
void getCommonPixelParams(const MaterialInputs material, inout PixelParams pixel) {
half4 baseColor = material.baseColor;
applyAlphaMask(baseColor);
#if defined(BLEND_MODE_FADE) && !defined(SHADING_MODEL_UNLIT)
// Since we work in premultiplied alpha mode, we need to un-premultiply
// in fade mode so we can apply alpha to both the specular and diffuse
// components at the end
unpremultiply(baseColor);
#endif
#if defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
// This is from KHR_materials_pbrSpecularGlossiness.
half3 specularColor = material.specularColor;
half metallic = computeMetallicFromSpecularColor(specularColor);
pixel.diffuseColor = computeDiffuseColor(baseColor, metallic);
pixel.f0 = specularColor;
#elif !defined(SHADING_MODEL_CLOTH)
pixel.diffuseColor = computeDiffuseColor(baseColor, material.metallic);
#if !defined(SHADING_MODEL_SUBSURFACE) && (!defined(MATERIAL_HAS_REFLECTANCE) && defined(MATERIAL_HAS_IOR))
half reflectance = iorToF0(max(1.0, material.ior), 1.0);
#else
// Assumes an interface from air to an IOR of 1.5 for dielectrics
half reflectance = computeDielectricF0(material.reflectance);
#endif
pixel.f0 = computeF0(baseColor, material.metallic, reflectance);
#else
pixel.diffuseColor = baseColor.rgb;
pixel.f0 = material.sheenColor;
#if defined(MATERIAL_HAS_SUBSURFACE_COLOR)
pixel.subsurfaceColor = material.subsurfaceColor;
#endif
#endif
#if !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SUBSURFACE)
#if defined(HAS_REFRACTION)
// Air's Index of refraction is 1.000277 at STP but everybody uses 1.0
const half airIor = 1.0;
#if !defined(MATERIAL_HAS_IOR)
// [common case] ior is not set in the material, deduce it from F0
half materialor = f0ToIor(pixel.f0.g);
#else
// if ior is set in the material, use it (can lead to unrealistic materials)
half materialor = max(1.0, material.ior);
#endif
pixel.etaIR = airIor / materialor; // air -> material
pixel.etaRI = materialor / airIor; // material -> air
#if defined(MATERIAL_HAS_TRANSMISSION)
pixel.transmission = saturate(material.transmission);
#else
pixel.transmission = 1.0;
#endif
#if defined(MATERIAL_HAS_ABSORPTION)
#if defined(MATERIAL_HAS_THICKNESS) || defined(MATERIAL_HAS_MICRO_THICKNESS)
pixel.absorption = max(0.0, material.absorption);
#else
pixel.absorption = saturate(material.absorption);
#endif
#else
pixel.absorption = 0.0;
#endif
#if defined(MATERIAL_HAS_THICKNESS)
pixel.thickness = max(0.0, material.thickness);
#endif
#if defined(MATERIAL_HAS_MICRO_THICKNESS) && (REFRACTION_TYPE == REFRACTION_TYPE_THIN)
pixel.uThickness = max(0.0, material.microThickness);
#else
pixel.uThickness = 0.0;
#endif
#endif
#endif
}
void getSheenPixelParams(const ShadingParams shading, const MaterialInputs material, inout PixelParams pixel) {
#if defined(MATERIAL_HAS_SHEEN_COLOR) && !defined(SHADING_MODEL_CLOTH) && !defined(SHADING_MODEL_SUBSURFACE)
pixel.sheenColor = material.sheenColor;
half sheenPerceptualRoughness = material.sheenRoughness;
sheenPerceptualRoughness = clamp(sheenPerceptualRoughness, MIN_PERCEPTUAL_ROUGHNESS, 1.0);
#if defined(GEOMETRIC_SPECULAR_AA)
sheenPerceptualRoughness =
normalFiltering(sheenPerceptualRoughness, shading.geometricNormal);
#endif
pixel.sheenPerceptualRoughness = sheenPerceptualRoughness;
pixel.sheenRoughness = perceptualRoughnessToRoughness(sheenPerceptualRoughness);
#endif
}
void getClearCoatPixelParams(const ShadingParams shading, const MaterialInputs material, inout PixelParams pixel) {
#if defined(MATERIAL_HAS_CLEAR_COAT)
pixel.clearCoat = material.clearCoat;
// Clamp the clear coat roughness to avoid divisions by 0
half clearCoatPerceptualRoughness = material.clearCoatRoughness;
clearCoatPerceptualRoughness =
clamp(clearCoatPerceptualRoughness, MIN_PERCEPTUAL_ROUGHNESS, 1.0);
#if defined(GEOMETRIC_SPECULAR_AA)
clearCoatPerceptualRoughness =
normalFiltering(clearCoatPerceptualRoughness, shading.geometricNormal);
#endif
pixel.clearCoatPerceptualRoughness = clearCoatPerceptualRoughness;
pixel.clearCoatRoughness = perceptualRoughnessToRoughness(clearCoatPerceptualRoughness);
#if defined(CLEAR_COAT_IOR_CHANGE)
// The base layer's f0 is computed assuming an interface from air to an IOR
// of 1.5, but the clear coat layer forms an interface from IOR 1.5 to IOR
// 1.5. We recompute f0 by first computing its IOR, then reconverting to f0
// by using the correct interface
pixel.f0 = lerp(pixel.f0, f0ClearCoatToSurface(pixel.f0), pixel.clearCoat);
#endif
#endif
}
void getRoughnessPixelParams(const ShadingParams shading, const MaterialInputs material, inout PixelParams pixel) {
#if defined(SHADING_MODEL_SPECULAR_GLOSSINESS)
half perceptualRoughness = computeRoughnessFromGlossiness(material.glossiness);
#else
half perceptualRoughness = material.roughness;
#endif
// This is used by the refraction code and must be saved before we apply specular AA
pixel.perceptualRoughnessUnclamped = perceptualRoughness;
#if defined(GEOMETRIC_SPECULAR_AA)
perceptualRoughness = normalFiltering(perceptualRoughness, shading.geometricNormal);
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT) && defined(MATERIAL_HAS_CLEAR_COAT_ROUGHNESS)
// This is a hack but it will do: the base layer must be at least as rough
// as the clear coat layer to take into account possible diffusion by the
// top layer
half basePerceptualRoughness = max(perceptualRoughness, pixel.clearCoatPerceptualRoughness);
perceptualRoughness = lerp(perceptualRoughness, basePerceptualRoughness, pixel.clearCoat);
#endif
// Clamp the roughness to a minimum value to avoid divisions by 0 during lighting
pixel.perceptualRoughness = clamp(perceptualRoughness, MIN_PERCEPTUAL_ROUGHNESS, 1.0);
// Remaps the roughness to a perceptually linear roughness (roughness^2)
pixel.roughness = perceptualRoughnessToRoughness(pixel.perceptualRoughness);
}
void getSubsurfacePixelParams(const MaterialInputs material, inout PixelParams pixel) {
#if defined(SHADING_MODEL_SUBSURFACE)
pixel.subsurfacePower = material.subsurfacePower;
pixel.subsurfaceColor = material.subsurfaceColor;
pixel.thickness = saturate(material.thickness);
#endif
}
void getAnisotropyPixelParams(const ShadingParams shading, const MaterialInputs material, inout PixelParams pixel) {
#if defined(MATERIAL_HAS_ANISOTROPY)
half3 direction = material.anisotropyDirection;
pixel.anisotropy = material.anisotropy;
pixel.anisotropicT = normalize(mul(shading.tangentToWorld, direction));
pixel.anisotropicB = normalize(cross(shading.geometricNormal, pixel.anisotropicT));
#endif
}
void getEnergyCompensationPixelParams(const ShadingParams shading, inout PixelParams pixel) {
// Pre-filtered DFG term used for image-based lighting
pixel.dfg = prefilteredDFG(pixel.perceptualRoughness, shading.NoV);
#if !defined(SHADING_MODEL_CLOTH)
// Energy compensation for multiple scattering in a microfacet model
// See "Multiple-Scattering Microfacet BSDFs with the Smith Model"
pixel.energyCompensation = 1.0 + pixel.f0 * (1.0 / pixel.dfg.yyy - 1.0);
#else
pixel.energyCompensation = (1.0);
#endif
#if !defined(SHADING_MODEL_CLOTH)
#if defined(MATERIAL_HAS_SHEEN_COLOR)
pixel.sheenDFG = prefilteredDFG(pixel.sheenPerceptualRoughness, shading.NoV).z;
pixel.sheenScaling = 1.0 - max3(pixel.sheenColor) * pixel.sheenDFG;
#endif
#endif
}
void geGlintPixelParams(const ShadingParams shading, const MaterialInputs material, inout PixelParams pixel) {
#if defined(MATERIAL_HAS_GLINT)
pixel.uv = material.uv;
pixel.ddx_uv = ddx(material.uv);
pixel.ddy_uv = ddy(material.uv);
pixel.glintAlpha = material.glintAlpha;
pixel.glintDensity = material.glintDensity;
#endif
}
/**
* Computes all the parameters required to shade the current pixel/fragment.
* These parameters are derived from the MaterialInputs structure computed
* by the user's material code.
*
* This function is also responsible for discarding the fragment when alpha
* testing fails.
*/
void getPixelParams(const ShadingParams shading, const MaterialInputs material, out PixelParams pixel) {
pixel = (PixelParams)0;
getCommonPixelParams(material, pixel);
getSheenPixelParams(shading, material, pixel);
getClearCoatPixelParams(shading, material, pixel);
getRoughnessPixelParams(shading, material, pixel);
getSubsurfacePixelParams(material, pixel);
getAnisotropyPixelParams(shading, material, pixel);
geGlintPixelParams(shading, material, pixel);
getEnergyCompensationPixelParams(shading, pixel);
}
/**
* This function evaluates all lights one by one:
* - Image based lights (IBL)
* - Directional lights
* - Punctual lights
*
* Area lights are currently not supported.
*
* Returns a pre-exposed HDR RGBA color in linear space.
*/
half4 evaluateLights(const ShadingParams shading, const MaterialInputs material) {
PixelParams pixel;
getPixelParams(shading, material, pixel);
// Ideally we would keep the diffuse and specular components separate
// until the very end but it costs more ALUs on mobile. The gains are
// currently not worth the extra operations
half3 color = 0.0;
// We always evaluate the IBL as not having one is going to be uncommon,
// it also saves 1 shader variant
#if defined(UNITY_PASS_FORWARDBASE)
evaluateIBL(shading, material, pixel, color);
#endif
#if defined(HAS_DIRECTIONAL_LIGHTING)
evaluateDirectionalLight(shading, material, pixel, color);
#endif
#if defined(HAS_DYNAMIC_LIGHTING)
evaluatePunctualLights(shading, pixel, color);
#endif
#if defined(BLEND_MODE_FADE) && !defined(SHADING_MODEL_UNLIT)
// In fade mode we un-premultiply baseColor early on, so we need to
// premultiply again at the end (affects diffuse and specular lighting)
color *= material.baseColor.a;
#endif
return half4(color, computeDiffuseAlpha(material.baseColor.a));
}
void addEmissive(const MaterialInputs material, inout half4 color) {
#if defined(MATERIAL_HAS_EMISSIVE)
float4 emissive = material.emissive;
//float attenuation = lerp(1.0, frameUniforms.exposure, emissive.w);
// Exposure not supported yet
float attenuation = emissive.w;
color.rgb += emissive.rgb * (attenuation * color.a);
#endif
}
/**
* Evaluate lit materials. The actual shading model used to do so is defined
* by the function surfaceShading() found in shading_model_*.fs.
*
* Returns a pre-exposed HDR RGBA color in linear space.
*/
half4 evaluateMaterial(const ShadingParams shading, const MaterialInputs material) {
half4 color = evaluateLights(shading, material);
addEmissive(material, color);
return color;
}
#endif // FILAMENT_SHADING_LIT

View File

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

View File

@ -0,0 +1,81 @@
//------------------------------------------------------------------------------
// Material evaluation
//------------------------------------------------------------------------------
/**
* Computes global shading parameters used to apply lighting, such as the view
* vector in world space, the tangent frame at the shading point, etc.
*/
void computeShadingParams(inout ShadingParams shading, float3 vertex_worldNormal, float4 vertex_worldTangent, float3 vertex_worldPosition,
float4 vertex_position, float3 frameUniforms_cameraPosition, bool isDoubleSided, bool gl_FrontFacing) {
#if defined(HAS_ATTRIBUTE_TANGENTS)
float3 n = vertex_worldNormal;
#if defined(MATERIAL_NEEDS_TBN)
float3 t = vertex_worldTangent.xyz;
float3 b = cross(n, t) * sign(vertex_worldTangent.w);
#endif
#if defined(MATERIAL_HAS_DOUBLE_SIDED_CAPABILITY)
if (isDoubleSided) {
n = gl_FrontFacing ? n : -n;
#if defined(MATERIAL_NEEDS_TBN)
t = gl_FrontFacing ? t : -t;
b = gl_FrontFacing ? b : -b;
#endif
}
#endif
shading.geometricNormal = normalize(n);
#if defined(MATERIAL_NEEDS_TBN)
// We use unnormalized post-interpolation values, assuming mikktspace tangents
shading.tangentToWorld = float3x3(t, b, n);
#endif
#endif
shading.position = vertex_worldPosition.xyz;
shading.view = normalize(frameUniforms_cameraPosition - shading.position);
float2 viewportUV = vertex_position.xy / _ScreenParams.xy;
#if defined(UNITY_SINGLE_PASS_STEREO)
viewportUV.x = viewportUV.x * 2.0 - float(unity_StereoEyeIndex);
#endif
shading.normalizedViewportCoord = viewportUV;
}
/**
* Computes global shading parameters that the material might need to access
* before lighting: N dot V, the reflected vector and the shading normal (before
* applying the normal map). These parameters can be useful to material authors
* to compute other material properties.
*
* This function must be invoked by the user's material code (guaranteed by
* the material compiler) after setting a value for MaterialInputs.normal.
*/
void prepareMaterial(inout ShadingParams shading, const MaterialInputs material) {
#if defined(HAS_ATTRIBUTE_TANGENTS)
#if defined(MATERIAL_HAS_NORMAL)
shading.normal = normalize(mul(shading.tangentToWorld, material.normal));
#else
shading.normal = shading.geometricNormal;
#endif // MATERIAL_HAS_NORMAL
shading.NoV = clampNoV(dot(shading.normal, shading.view));
shading.reflected = reflect(-shading.view, shading.normal);
#if defined(MATERIAL_HAS_BENT_NORMAL)
shading.bentNormal = normalize(mul(shading.tangentToWorld, material.bentNormal));
#endif // MATERIAL_HAS_BENT_NORMAL
#if defined(MATERIAL_HAS_CLEAR_COAT)
#if defined(MATERIAL_HAS_CLEAR_COAT_NORMAL)
shading.clearCoatNormal = normalize(mul(shading.tangentToWorld, material.clearCoatNormal));
#else
shading.clearCoatNormal = shading.geometricNormal;
#endif // MATERIAL_HAS_CLEAR_COAT_NORMAL
#endif // MATERIAL_HAS_CLEAR_COAT
#endif // HAS_ATTRIBUTE_TANGENTS
}

View File

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

View File

@ -0,0 +1,213 @@
#ifndef FILAMENT_SHADING_STANDARD_INCLUDED
#define FILAMENT_SHADING_STANDARD_INCLUDED
#include "FilamentBRDF.cginc"
#if defined(MATERIAL_HAS_GLINT)
#include "SharedGlintyBRDF.hlsl"
#endif
#if defined(MATERIAL_HAS_SHEEN_COLOR)
half3 sheenLobe(const PixelParams pixel, half NoV, half NoL, half NoH) {
half D = distributionCloth(pixel.sheenRoughness, NoH);
half V = visibilityCloth(NoV, NoL);
return (D * V) * pixel.sheenColor;
}
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT)
half clearCoatLobe(const ShadingParams shading, const PixelParams pixel,
const half3 h, half NoH, half LoH, half3 NxH, out half Fcc) {
#if defined(MATERIAL_HAS_NORMAL) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL)
// If the material has a normal map, we want to use the geometric normal
// instead to avoid applying the normal map details to the clear coat layer
half clearCoatNoH = saturate(dot(shading.clearCoatNormal, h));
half3 clearCoatNxH = cross(shading.clearCoatNormal, h);
#else
half clearCoatNoH = NoH;
half3 clearCoatNxH = NxH;
#endif
// clear coat specular lobe
half D = distributionClearCoat(pixel.clearCoatRoughness, clearCoatNoH, clearCoatNxH, h);
half V = visibilityClearCoat(LoH);
half F = F_Schlick(0.04, 1.0, LoH) * pixel.clearCoat; // fix IOR to 1.5
Fcc = F;
return D * V * F;
}
#endif
#if defined(MATERIAL_HAS_ANISOTROPY)
half3 anisotropicLobe(const ShadingParams shading, const PixelParams pixel, const Light light,
const half3 h, half NoV, half NoL, half NoH, half LoH) {
half3 l = light.l;
half3 t = pixel.anisotropicT;
half3 b = pixel.anisotropicB;
half3 v = shading.view;
half ToV = dot(t, v);
half BoV = dot(b, v);
half ToL = dot(t, l);
half BoL = dot(b, l);
half ToH = dot(t, h);
half BoH = dot(b, h);
// Anisotropic parameters: at and ab are the roughness along the tangent and bitangent
// to simplify materials, we derive them from a single roughness parameter
// Kulla 2017, "Revisiting Physically Based Shading at Imageworks"
half at = max(pixel.roughness * (1.0 + pixel.anisotropy), MIN_ROUGHNESS);
half ab = max(pixel.roughness * (1.0 - pixel.anisotropy), MIN_ROUGHNESS);
// specular anisotropic BRDF
half D = distributionAnisotropic(at, ab, ToH, BoH, NoH);
half V = visibilityAnisotropic(pixel.roughness, at, ab, ToV, BoV, ToL, BoL, NoV, NoL);
half3 F = fresnel(pixel.f0, LoH);
return (D * V) * F;
}
#endif
half3 isotropicLobe(const PixelParams pixel, const Light light, const half3 h,
half NoV, half NoL, half NoH, half LoH, half3 NxH) {
half D = distribution(pixel.roughness, NoH, NxH, h);
half V = visibility(pixel.roughness, NoV, NoL);
#if defined(MATERIAL_HAS_SPECULAR_COLOR_FACTOR) || defined(MATERIAL_HAS_SPECULAR_FACTOR)
half3 F = fresnel(pixel.f0, pixel.f90, LoH);
#else
half3 F = fresnel(pixel.f0, LoH);
#endif
return (D * V) * F;
}
#if defined(MATERIAL_HAS_GLINT)
half3 isotropicGlintLobe(const ShadingParams shading, const PixelParams pixel, const Light light,
const half3 h, half NoV, half NoL, half NoH, half LoH) {
float3 tangentH = mul(h, shading.tangentToWorld);
float2x2 Jacobian = float2x2(pixel.ddx_uv, pixel.ddy_uv);
float2x2 uv_ellipsoid = get_uv_ellipsoid(Jacobian);
half D = EvaluateGlintyNDF(
tangentH,
pixel.roughness,
pixel.glintAlpha,
pixel.uv,
uv_ellipsoid,
pixel.glintDensity,
0.8 // Filter size
);
D = max(0, D);
half V = visibility(pixel.roughness, NoV, NoL);
#if defined(MATERIAL_HAS_SPECULAR_COLOR_FACTOR) || defined(MATERIAL_HAS_SPECULAR_FACTOR)
half3 F = fresnel(pixel.f0, pixel.f90, LoH);
#else
half3 F = fresnel(pixel.f0, LoH);
#endif
return (D * V) * F;
}
#endif
half3 specularLobe(const ShadingParams shading, const PixelParams pixel, const Light light,
const half3 h, half NoV, half NoL, half NoH, half LoH, half3 NxH) {
#if defined(MATERIAL_HAS_ANISOTROPY)
return anisotropicLobe(shading, pixel, light, h, NoV, NoL, NoH, LoH);
#elif defined(MATERIAL_HAS_GLINT)
return isotropicGlintLobe(shading, pixel, light, h, NoV, NoL, NoH, LoH);
#else
return isotropicLobe(pixel, light, h, NoV, NoL, NoH, LoH, NxH);
#endif
}
half3 diffuseLobe(const PixelParams pixel, half NoV, half NoL, half LoH) {
return pixel.diffuseColor * diffuse(pixel.roughness, NoV, NoL, LoH);
}
/**
* Evaluates lit materials with the standard shading model. This model comprises
* of 2 BRDFs: an optional clear coat BRDF, and a regular surface BRDF.
*
* Surface BRDF
* The surface BRDF uses a diffuse lobe and a specular lobe to render both
* dielectrics and conductors. The specular lobe is based on the Cook-Torrance
* micro-facet model (see brdf.fs for more details). In addition, the specular
* can be either isotropic or anisotropic.
*
* Clear coat BRDF
* The clear coat BRDF simulates a transparent, absorbing dielectric layer on
* top of the surface. Its IOR is set to 1.5 (polyutherane) to simplify
* our computations. This BRDF only contains a specular lobe and while based
* on the Cook-Torrance microfacet model, it uses cheaper terms than the surface
* BRDF's specular lobe (see brdf.fs).
*/
half3 surfaceShading(const ShadingParams shading, const PixelParams pixel, const Light light,
half occlusion) {
half3 h = normalize(shading.view + light.l);
half NoV = shading.NoV;
half NoL = saturate(light.NoL);
half NoH = saturate(dot(shading.normal, h));
half LoH = saturate(dot(light.l, h));
half3 NxH = cross(shading.normal, h);
// Note: For Unity, specular and diffuse terms must be multiplied by Pi
// to match the light intensities of other shaders.
// This is partly because the diffuse term is already divided by Pi here.
half3 Fr = specularLobe(shading, pixel, light, h, NoV, NoL, NoH, LoH, NxH) * PI;
half3 Fd = diffuseLobe(pixel, NoV, NoL, LoH) * PI;
// Unity toggle for disabling specular highlights.
#if defined(_SPECULARHIGHLIGHTS_OFF)
Fr = 0.0;
#endif
#if defined(HAS_REFRACTION)
Fd *= (1.0 - pixel.transmission);
#endif
// TODO: attenuate the diffuse lobe to avoid energy gain
// The energy compensation term is used to counteract the darkening effect
// at high roughness
half3 color = Fd + Fr * pixel.energyCompensation;
#if defined(MATERIAL_HAS_SHEEN_COLOR)
color *= pixel.sheenScaling;
color += sheenLobe(pixel, NoV, NoL, NoH);
#endif
#if defined(MATERIAL_HAS_CLEAR_COAT)
half Fcc;
half clearCoat = clearCoatLobe(shading, pixel, h, NoH, LoH, NxH, Fcc);
half attenuation = 1.0 - Fcc;
#if defined(MATERIAL_HAS_NORMAL) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL)
color *= attenuation * NoL;
// If the material has a normal map, we want to use the geometric normal
// instead to avoid applying the normal map details to the clear coat layer
half clearCoatNoL = saturate(dot(shading.clearCoatNormal, light.l));
color += clearCoat * clearCoatNoL;
// Early exit to avoid the extra multiplication by NoL
return (color * light.colorIntensity.rgb) *
(light.colorIntensity.w * light.attenuation * occlusion);
#else
color *= attenuation;
color += clearCoat;
#endif
#endif
return (color * light.colorIntensity.rgb) *
(light.colorIntensity.w * light.attenuation * NoL * occlusion);
}
#endif // FILAMENT_SHADING_STANDARD_INCLUDED

View File

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

View File

@ -0,0 +1,48 @@
#ifndef FILAMENT_SHADING_SUBSURFACE_INCLUDED
#define FILAMENT_SHADING_SUBSURFACE_INCLUDED
#include "FilamentBRDF.cginc"
/**
* Evalutes lit materials with the subsurface shading model. This model is a
* combination of a BRDF (the same used in shading_model_standard.fs, refer to that
* file for more information) and of an approximated BTDF to simulate subsurface
* scattering. The BTDF itself is not physically based and does not represent a
* correct interpretation of transmission events.
*/
half3 surfaceShading(const ShadingParams shading, const PixelParams pixel, const Light light, half occlusion) {
half3 h = normalize(shading.view + light.l);
half NoL = light.NoL;
half NoH = saturate(dot(shading.normal, h));
half LoH = saturate(dot(light.l, h));
half3 NxH = cross(shading.normal, h);
half3 Fr = 0.0;
if (NoL > 0.0) {
// specular BRDF
half D = distribution(pixel.roughness, NoH, NxH, h);
half V = visibility(pixel.roughness, shading.NoV, NoL);
half3 F = fresnel(pixel.f0, LoH);
Fr = (D * V) * F * pixel.energyCompensation;
}
// diffuse BRDF
half3 Fd = pixel.diffuseColor * diffuse(pixel.roughness, shading.NoV, NoL, LoH);
// NoL does not apply to transmitted light
half3 color = (Fd + Fr) * (NoL * occlusion);
// subsurface scattering
// Use a spherical gaussian approximation of pow() for forwardScattering
// We could include distortion by adding shading.normal * distortion to light.l
half scatterVoH = saturate(dot(shading.view, -light.l));
half forwardScatter = exp2(scatterVoH * pixel.subsurfacePower - pixel.subsurfacePower);
half backScatter = saturate(NoL * pixel.thickness + (1.0 - pixel.thickness)) * 0.5;
half subsurface = lerp(backScatter, 1.0, forwardScatter) * (1.0 - pixel.thickness);
color += pixel.subsurfaceColor * (subsurface * Fd_Lambert());
// TODO: apply occlusion to the transmitted light
return (color * light.colorIntensity.rgb) * (light.colorIntensity.w * light.attenuation);
}
#endif // FILAMENT_SHADING_SUBSURFACE_INCLUDED

View File

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

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 RED_SIM
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

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

View File

@ -0,0 +1,949 @@
#ifndef VRC_LIGHT_VOLUMES_INCLUDED
#define VRC_LIGHT_VOLUMES_INCLUDED
#define VRCLV_VERSION 2
#define VRCLV_MAX_VOLUMES_COUNT 32
#define VRCLV_MAX_LIGHTS_COUNT 128
#ifndef SHADER_TARGET_SURFACE_ANALYSIS
cbuffer LightVolumeUniforms {
#endif
// Are Light Volumes enabled on scene? can be 0 or 1
uniform float _UdonLightVolumeEnabled;
// Rreturns 1, 2 or other number if there are light volumes on the scene. Number represents the light volumes system internal version number.
uniform float _UdonLightVolumeVersion;
// All volumes count in scene
uniform float _UdonLightVolumeCount;
// Additive volumes max overdraw count
uniform float _UdonLightVolumeAdditiveMaxOverdraw;
// Additive volumes count
uniform float _UdonLightVolumeAdditiveCount;
// Should volumes be blended with lightprobes?
uniform float _UdonLightVolumeProbesBlend;
// Should volumes be with sharp edges when not blending with each other
uniform float _UdonLightVolumeSharpBounds;
// World to Local (-0.5, 0.5) UVW Matrix 4x4
uniform float4x4 _UdonLightVolumeInvWorldMatrix[VRCLV_MAX_VOLUMES_COUNT];
// L1 SH quaternion rotation (relative to baked rotation)
//uniform float4 _UdonLightVolumeRotationQuaternion[32];
uniform float4 _UdonLightVolumeRotation[VRCLV_MAX_VOLUMES_COUNT * 2]; // Legacy! Used in this version to have back compatibility with older worlds. Array commented above will be used in future releases! Legacy!
// Value that is needed to smoothly blend volumes ( BoundsScale / edgeSmooth )
uniform float3 _UdonLightVolumeInvLocalEdgeSmooth[VRCLV_MAX_VOLUMES_COUNT];
// AABB Bounds of islands on the 3D Texture atlas. XYZ: UvwMin, W: Scale per axis
// uniform float4 _UdonLightVolumeUvwScale[96];
uniform float3 _UdonLightVolumeUvw[VRCLV_MAX_VOLUMES_COUNT * 6]; // Legacy! AABB Bounds of islands on the 3D Texture atlas. Array commented above will be used in future releases! Legacy!
// XYZ: AABB Bounds of islands on the 3D Texture atlas storing occlusion. W: Scale factor for the occlusion volume UVW
// This is optional data. If the volume has no occlusion, the value will be (-1, -1, -1, -1).
uniform float4 _UdonLightVolumeOcclusionUvw[VRCLV_MAX_VOLUMES_COUNT];
// Color multiplier (RGB) | If we actually need to rotate L1 components at all (A)
uniform float4 _UdonLightVolumeColor[VRCLV_MAX_VOLUMES_COUNT];
// Point Lights count
uniform float _UdonPointLightVolumeCount;
// Cubemaps count in the custom textures array
uniform float _UdonPointLightVolumeCubeCount;
// For point light: XYZ = Position, W = Inverse squared range
// For spot light: XYZ = Position, W = Inverse squared range, negated
// For area light: XYZ = Position, W = Width
uniform float4 _UdonPointLightVolumePosition[VRCLV_MAX_LIGHTS_COUNT];
// For point light: XYZ = Color, W = Cos of angle (for LUT)
// For spot light: XYZ = Color, W = Cos of outer angle if no custom texture, tan of outer angle otherwise
// For area light: XYZ = Color, W = 2 + Height
uniform float4 _UdonPointLightVolumeColor[VRCLV_MAX_LIGHTS_COUNT];
// For point light: XYZW = Rotation quaternion
// For spot light: XYZ = Direction, W = Cone falloff
// For area light: XYZW = Rotation quaternion
uniform float4 _UdonPointLightVolumeDirection[VRCLV_MAX_LIGHTS_COUNT];
// X = Custom ID:
// If parametric: X stores 0
// If uses custom lut: X stores LUT ID with positive sign
// If uses custom texture: X stores texture ID with negative sign
// Y = Shadowmask index. If light doesn't use shadowmask, the index will be negative.
// Z = Squared Culling Range. Just a precalculated culling range to not recalculate in in shader.
uniform float3 _UdonPointLightVolumeCustomID[VRCLV_MAX_LIGHTS_COUNT];
// If we are far enough from a light that the irradiance
// is guaranteed lower than the threshold defined by this value,
// we cull the light.
uniform float _UdonLightBrightnessCutoff;
// The number of volumes that provide occlusion data.
// We use this to take faster paths when no occlusion is needed.
uniform float _UdonLightVolumeOcclusionCount;
#ifndef SHADER_TARGET_SURFACE_ANALYSIS
}
#endif
#ifndef SHADER_TARGET_SURFACE_ANALYSIS
// Main 3D Texture atlas
uniform Texture3D _UdonLightVolume;
uniform SamplerState sampler_UdonLightVolume;
// First elements must be cubemap faces (6 face textures per cubemap). Then goes other textures
uniform Texture2DArray _UdonPointLightVolumeTexture;
// Samples a texture using mip 0, and reusing a single sampler
#define LV_SAMPLE(tex, uvw) tex.SampleLevel(sampler_UdonLightVolume, uvw, 0)
#else
// Dummy macro definition to satisfy MojoShader (surface shaders).
#define LV_SAMPLE(tex, uvw) float4(0,0,0,0)
#endif
#define LV_PI 3.141592653589793f
#define LV_PI2 6.283185307179586f
// Smoothstep to 0, 1 but cheaper
float LV_Smoothstep01(float x) {
return x * x * (3 - 2 * x);
}
// Rotates vector by Quaternion
float3 LV_MultiplyVectorByQuaternion(float3 v, float4 q) {
float3 t = 2.0 * cross(q.xyz, v);
return v + q.w * t + cross(q.xyz, t);
}
// Rotates vector by Matrix 2x3
float3 LV_MultiplyVectorByMatrix2x3(float3 v, float3 r0, float3 r1) {
float3 r2 = cross(r0, r1);
return float3(dot(v, r0), dot(v, r1), dot(v, r2));
}
// Fast approximate inverse cosine. Max absolute error = 0.009.
// From https://seblagarde.wordpress.com/2014/12/01/inverse-trigonometric-functions-gpu-optimization-for-amd-gcn-architecture/
float LV_FastAcos(float x) {
float absX = abs(x);
float res = -0.156583f * absX + LV_PI * 0.5f;
res *= sqrt(1.0f - absX);
return (x >= 0) ? res : (LV_PI - res);
}
// Forms specular based on roughness
float LV_DistributionGGX(float NoH, float roughness) {
float f = (roughness - 1) * ((roughness + 1) * (NoH * NoH)) + 1;
return (roughness * roughness) / ((float) LV_PI * f * f);
}
// Checks if local UVW point is in bounds from -0.5 to +0.5
bool LV_PointLocalAABB(float3 localUVW) {
return all(abs(localUVW) <= 0.5);
}
// Calculates local UVW using volume ID
float3 LV_LocalFromVolume(uint volumeID, float3 worldPos) {
return mul(_UdonLightVolumeInvWorldMatrix[volumeID], float4(worldPos, 1.0)).xyz;
}
// Linear single SH L1 channel evaluation
float LV_EvaluateSH(float L0, float3 L1, float3 n) {
return L0 + dot(L1, n);
}
// Samples a cubemap from _UdonPointLightVolumeTexture array
float4 LV_SampleCubemapArray(uint id, float3 dir) {
float3 absDir = abs(dir);
float2 uv;
uint face;
if (absDir.x >= absDir.y && absDir.x >= absDir.z) {
face = dir.x > 0 ? 0 : 1;
uv = float2((dir.x > 0 ? -dir.z : dir.z), -dir.y) * rcp(absDir.x);
} else if (absDir.y >= absDir.z) {
face = dir.y > 0 ? 2 : 3;
uv = float2(dir.x, (dir.y > 0 ? dir.z : -dir.z)) * rcp(absDir.y);
} else {
face = dir.z > 0 ? 4 : 5;
uv = float2((dir.z > 0 ? dir.x : -dir.x), -dir.y) * rcp(absDir.z);
}
float3 uvid = float3(uv * 0.5 + 0.5, id * 6 + face);
return LV_SAMPLE(_UdonPointLightVolumeTexture, uvid);
}
// Projects irradiance from a planar quad with uniform radiant exitance into L1 spherical harmonics.
// Based on "Analytic Spherical Harmonic Coefficients for Polygonal Area Lights" by Wang and Ramamoorthi.
// https://cseweb.ucsd.edu/~ravir/ash.pdf. Assumes that shadingPosition is not behind the quad.
float4 LV_ProjectQuadLightIrradianceSH(float3 shadingPosition, float3 lightVertices[4]) {
// Transform the vertices into local space centered on the shading position,
// project, the polygon onto the unit sphere.
[unroll] for (uint edge0 = 0; edge0 < 4; edge0++) {
lightVertices[edge0] = normalize(lightVertices[edge0] - shadingPosition);
}
// Precomputed directions of rotated zonal harmonics,
// and associated weights for each basis function.
// I.E. \omega_{l,d} and \alpha_{l,d}^m in the paper respectively.
const float3 zhDir0 = float3(0.866025, -0.500001, -0.000004);
const float3 zhDir1 = float3(-0.759553, 0.438522, -0.480394);
const float3 zhDir2 = float3(-0.000002, 0.638694, 0.769461);
const float3 zhWeightL1y = float3(2.1995339f, 2.50785367f, 1.56572711f);
const float3 zhWeightL1z = float3(-1.82572523f, -2.08165037f, 0.00000000f);
const float3 zhWeightL1x = float3(2.42459869f, 1.44790525f, 0.90397552f);
float solidAngle = 0.0;
float3 surfaceIntegral = 0.0;
[loop] for (uint edge1 = 0; edge1 < 4; edge1++) {
uint next = (edge1 + 1) % 4;
uint prev = (edge1 + 4 - 1) % 4;
float3 prevVert = lightVertices[prev];
float3 thisVert = lightVertices[edge1];
float3 nextVert = lightVertices[next];
// Compute the solid angle subtended by the polygon at the shading position,
// using Arvo's formula (5.1) https://dl.acm.org/doi/pdf/10.1145/218380.218467.
// The L0 term is directly proportional to the solid angle.
float3 a = cross(thisVert, prevVert);
float3 b = cross(thisVert, nextVert);
float lenA = length(a);
float lenB = length(b);
solidAngle += LV_FastAcos(clamp(dot(a, b) / (lenA * lenB), -1, 1));
// Compute the integral of the legendre polynomials over the surface of the
// projected polygon for each zonal harmonic direction (S_l in the paper).
// Computed as a sum of line integrals over the edges of the polygon.
float3 mu = b * rcp(lenB);
float cosGamma = dot(thisVert, nextVert);
float gamma = LV_FastAcos(clamp(cosGamma, -1, 1));
surfaceIntegral.x += gamma * dot(zhDir0, mu);
surfaceIntegral.y += gamma * dot(zhDir1, mu);
surfaceIntegral.z += gamma * dot(zhDir2, mu);
}
solidAngle = solidAngle - LV_PI2;
surfaceIntegral *= 0.5;
// The L0 term is just the projection of the solid angle onto the L0 basis function.
const float normalizationL0 = 0.5f * sqrt(1.0f / LV_PI);
float l0 = normalizationL0 * solidAngle;
// Combine each surface (sub)integral with the associated weights to get
// full surface integral for each L1 SH basis function.
float l1y = dot(zhWeightL1y, surfaceIntegral);
float l1z = dot(zhWeightL1z, surfaceIntegral);
float l1x = dot(zhWeightL1x, surfaceIntegral);
// The l0, l1y, l1z, l1x are raw SH coefficients for radiance from the polygon.
// We need to apply some more transformations before we are done:
// (1) We want the coefficients for irradiance, so we need to convolve with the
// clamped cosine kernel, as detailed in https://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf.
// The kernel has coefficients PI and 2/3*PI for L0 and L1 respectively.
// (2) Unity's area lights underestimate the irradiance by a factor of PI for historical reasons.
// We need to divide by PI to match this 'incorrect' behavior.
// (3) Unity stores SH coefficients (unity_SHAr..unity_SHC) pre-multiplied with the constant
// part of each SH basis function, so we need to multiply by constant part to match it.
const float cosineKernelL0 = LV_PI; // (1)
const float cosineKernelL1 = LV_PI2 / 3.0f; // (1)
const float oneOverPi = 1.0f / LV_PI; // (2)
const float normalizationL1 = 0.5f * sqrt(3.0f / LV_PI); // (3)
const float weightL0 = cosineKernelL0 * normalizationL0 * oneOverPi; // (1), (2), (3)
const float weightL1 = cosineKernelL1 * normalizationL1 * oneOverPi; // (1), (2), (3)
l0 *= weightL0;
l1y *= weightL1;
l1z *= weightL1;
l1x *= weightL1;
return float4(l1x, l1y, l1z, l0);
}
// Samples a quad light, including culling
void LV_QuadLight(float3 worldPos, float3 centroidPos, float4 rotationQuat, float2 size, float3 color, float sqMaxDist, float occlusion, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, inout uint count) {
float3 lightToWorldPos = worldPos - centroidPos;
// Normal culling
float3 normal = LV_MultiplyVectorByQuaternion(float3(0, 0, 1), rotationQuat);
[branch] if (dot(normal, lightToWorldPos) < 0.0) return;
// Attenuate the light based on distance to the bounding sphere, so we don't get hard seam at the edge.
float sqCutoffDist = sqMaxDist - dot(lightToWorldPos, lightToWorldPos);
color.rgb *= saturate(sqCutoffDist / sqMaxDist) * LV_PI * occlusion;
// Compute the vertices of the quad
float2 halfSize = size * 0.5f;
float3 xAxis = LV_MultiplyVectorByQuaternion(float3(1, 0, 0), rotationQuat);
float3 yAxis = cross(normal, xAxis);
float3 verts[4];
verts[0] = centroidPos + (-halfSize.x * xAxis) + ( halfSize.y * yAxis);
verts[1] = centroidPos + ( halfSize.x * xAxis) + ( halfSize.y * yAxis);
verts[2] = centroidPos + ( halfSize.x * xAxis) + (-halfSize.y * yAxis);
verts[3] = centroidPos + (-halfSize.x * xAxis) + (-halfSize.y * yAxis);
// Project irradiance from the area light
float4 areaLightSH = LV_ProjectQuadLightIrradianceSH(worldPos, verts);
// If the magnitude of L1 is greater than L0, we may get negative values
// when reconstructing. To avoid, normalize L1. This is effectively de-ringing.
float lenL1 = length(areaLightSH.xyz);
if (lenL1 > areaLightSH.w) areaLightSH.xyz *= areaLightSH.w / lenL1;
L0 += areaLightSH.w * color.rgb;
L1r += areaLightSH.xyz * color.r;
L1g += areaLightSH.xyz * color.g;
L1b += areaLightSH.xyz * color.b;
count++;
}
// Calculates point light attenuation. Returns false if it's culled
float3 LV_PointLightAttenuation(float sqdist, float sqlightSize, float3 color, float brightnessCutoff, float sqMaxDist) {
float mask = saturate(1 - sqdist / sqMaxDist);
return mask * mask * color * sqlightSize / (sqdist + sqlightSize);
}
// Calculates point light solid angle coefficient
float LV_PointLightSolidAngle(float sqdist, float sqlightSize) {
return saturate(sqrt(sqdist / (sqlightSize + sqdist)));
}
// Calculares a spherical light source
void LV_SphereLight(float sqdist, float3 dirN, float sqlightSize, float3 color, float occlusion, float sqMaxDist, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, inout uint count) {
float3 att = LV_PointLightAttenuation(sqdist, sqlightSize, color, _UdonLightBrightnessCutoff, sqMaxDist);
float3 l0 = att * occlusion;
float3 l1 = dirN * LV_PointLightSolidAngle(sqdist, sqlightSize);
L0 += l0;
L1r += l0.r * l1;
L1g += l0.g * l1;
L1b += l0.b * l1;
count++;
}
// Calculares a spherical spot light source
void LV_SphereSpotLight(float sqdist, float3 dirN, float sqlightSize, float3 att, float spotMask, float cosAngle, float coneFalloff, float occlusion, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, inout uint count) {
float smoothedCone = LV_Smoothstep01(saturate(spotMask * coneFalloff));
float3 l0 = att * (occlusion * smoothedCone);
float3 l1 = dirN * LV_PointLightSolidAngle(sqdist, sqlightSize * saturate(1 - cosAngle));
L0 += l0;
L1r += l0.r * l1;
L1g += l0.g * l1;
L1b += l0.b * l1;
count++;
}
// Calculares a spherical spot light source
void LV_SphereSpotLightCookie(float sqdist, float3 dirN, float sqlightSize, float3 att, float4 lightRot, float tanAngle, uint customId, float occlusion, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, inout uint count) {
float3 localDir = LV_MultiplyVectorByQuaternion(-dirN, lightRot);
float2 uv = localDir.xy * rcp(localDir.z * tanAngle);
[branch] if (
localDir.z <= 0.0 || // Culling by direction
abs(uv.x) > 1.0 || abs(uv.y) > 1.0 // Culling by UV
) return;
uint id = (uint) _UdonPointLightVolumeCubeCount * 5 - customId - 1;
float3 uvid = float3(uv * 0.5 + 0.5, id);
float angleSize = saturate(rsqrt(1 + tanAngle * tanAngle));
float4 cookie = LV_SAMPLE(_UdonPointLightVolumeTexture, uvid);
float3 l0 = att * cookie.rgb * (cookie.a * occlusion);
float3 l1 = dirN * LV_PointLightSolidAngle(sqdist, sqlightSize * (1 - angleSize));
L0 += l0;
L1r += l0.r * l1;
L1g += l0.g * l1;
L1b += l0.b * l1;
count++;
}
// Calculares a spherical spot light source
void LV_SphereSpotLightAttenuationLUT(float sqdist, float3 dirN, float sqlightSize, float3 color, float spotMask, float cosAngle, uint customId, float occlusion, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, inout uint count) {
float dirRadius = sqdist * abs(sqlightSize);
float spot = 1 - saturate(spotMask * rcp(1 - cosAngle));
uint id = (uint) _UdonPointLightVolumeCubeCount * 5 + customId - 1;
float3 uvid = float3(sqrt(float2(spot, dirRadius)), id);
float3 att = color.rgb * LV_SAMPLE(_UdonPointLightVolumeTexture, uvid).xyz * occlusion;
L0 += att;
L1r += dirN * att.r;
L1g += dirN * att.g;
L1b += dirN * att.b;
count++;
}
// Samples a spot light, point light or quad/area light
void LV_PointLight(uint id, float3 worldPos, float4 occlusion, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, inout uint count) {
// IDs and range data
float3 customID_data = _UdonPointLightVolumeCustomID[id];
int shadowId = (int) customID_data.y; // Shadowmask id
int customId = (int) customID_data.x; // Custom Texture ID
float sqrRange = customID_data.z; // Squared culling distance
float4 pos = _UdonPointLightVolumePosition[id]; // Light position and inversed squared range
float3 dir = pos.xyz - worldPos;
float sqlen = max(dot(dir, dir), 1e-6);
[branch] if (sqlen > sqrRange) return; // Early distance based culling
float3 dirN = dir * rsqrt(sqlen);
// Processing lights occlusion
float lightOcclusion = 1;
if (_UdonLightVolumeOcclusionCount != 0 && shadowId >= 0) {
lightOcclusion = dot(occlusion, float4(shadowId == 0, shadowId == 1, shadowId == 2, shadowId == 3));
}
float4 color = _UdonPointLightVolumeColor[id]; // Color, angle
float4 ldir = _UdonPointLightVolumeDirection[id]; // Dir + falloff or Rotation
[branch] if (pos.w < 0) { // It is a spot light
float angle = color.w;
float spotMask = dot(ldir.xyz, -dirN) - angle;
[branch] if(customId >= 0 && spotMask < 0) return; // Spot cone based culling
[branch] if (customId > 0) { // If it uses Attenuation LUT
LV_SphereSpotLightAttenuationLUT(sqlen, dirN, -pos.w, color.rgb, spotMask, angle, customId, lightOcclusion, L0, L1r, L1g, L1b, count);
} else { // If it uses default parametric attenuation
float3 att = LV_PointLightAttenuation(sqlen, -pos.w, color.rgb, _UdonLightBrightnessCutoff, sqrRange);
[branch] if (customId < 0) { // If uses cookie
LV_SphereSpotLightCookie(sqlen, dirN, -pos.w, att, ldir, angle, customId, lightOcclusion, L0, L1r, L1g, L1b, count);
} else { // If it uses default parametric attenuation
LV_SphereSpotLight(sqlen, dirN, -pos.w, att, spotMask, angle, ldir.w, lightOcclusion, L0, L1r, L1g, L1b, count);
}
}
} else if (color.w <= 1.5f) { // It is a point light
[branch] if (customId > 0) { // Using LUT
float invSqRange = abs(pos.w); // Sign of range defines if it's point light (positive) or a spot light (negative)
float dirRadius = sqlen * invSqRange;
uint id = (uint) _UdonPointLightVolumeCubeCount * 5 + customId;
float3 uvid = float3(sqrt(float2(0, dirRadius)), id);
float3 att = color.rgb * LV_SAMPLE(_UdonPointLightVolumeTexture, uvid).xyz * lightOcclusion;
L0 += att;
L1r += dirN * att.r;
L1g += dirN * att.g;
L1b += dirN * att.b;
count++;
} else { // If it uses default parametric attenuation
float3 l0 = 0, l1r = 0, l1g = 0, l1b = 0;
LV_SphereLight(sqlen, dirN, pos.w, color.rgb, lightOcclusion, sqrRange, l0, l1r, l1g, l1b, count);
float3 cubeColor = 1;
[branch] if (customId < 0) { // If it uses a cubemap
uint id = -customId - 1; // Cubemap ID starts from zero and should not take in count texture array slices count.
cubeColor = LV_SampleCubemapArray(id, LV_MultiplyVectorByQuaternion(dirN, ldir)).xyz;
}
L0 += l0 * cubeColor;
L1r += l1r * cubeColor.r;
L1g += l1g * cubeColor.g;
L1b += l1b * cubeColor.b;
}
} else { // It is an area light
LV_QuadLight(worldPos, pos.xyz, ldir, float2(pos.w, color.w - 2.0f), color.rgb, sqrRange, lightOcclusion, L0, L1r, L1g, L1b, count);
}
}
// Samples 3 SH textures and packing them into L1 channels
void LV_SampleLightVolumeTex(float3 uvw0, float3 uvw1, float3 uvw2, out float3 L0, out float3 L1r, out float3 L1g, out float3 L1b) {
// Sampling 3D Atlas
float4 tex0 = LV_SAMPLE(_UdonLightVolume, uvw0);
float4 tex1 = LV_SAMPLE(_UdonLightVolume, uvw1);
float4 tex2 = LV_SAMPLE(_UdonLightVolume, uvw2);
// Packing final data
L0 = tex0.rgb;
L1r = float3(tex1.r, tex2.r, tex0.a);
L1g = float3(tex1.g, tex2.g, tex1.a);
L1b = float3(tex1.b, tex2.b, tex2.a);
}
// Bounds mask for a volume rotated in world space, using local UVW
float LV_BoundsMask(float3 localUVW, float3 invLocalEdgeSmooth) {
float3 distToMin = (localUVW + 0.5) * invLocalEdgeSmooth;
float3 distToMax = (0.5 - localUVW) * invLocalEdgeSmooth;
float3 fade = saturate(min(distToMin, distToMax));
return fade.x * fade.y * fade.z;
}
// Default light probes SH components
void LV_SampleLightProbe(inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b) {
L0 += float3(unity_SHAr.w, unity_SHAg.w, unity_SHAb.w);
L1r += unity_SHAr.xyz;
L1g += unity_SHAg.xyz;
L1b += unity_SHAb.xyz;
}
// Applies deringing to light probes. Useful if they baked with Bakery L1
void LV_SampleLightProbeDering(inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b) {
L0 += float3(unity_SHAr.w, unity_SHAg.w, unity_SHAb.w);
L1r += unity_SHAr.xyz * 0.565f;
L1g += unity_SHAg.xyz * 0.565f;
L1b += unity_SHAb.xyz * 0.565f;
}
// Samples a Volume with ID and Local UVW
void LV_SampleVolume(uint id, float3 localUVW, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, out float4 occlusion) {
// Additive UVW
//uint uvwID = id * 3;
//float4 uvwPos0 = _UdonLightVolumeUvwScale[uvwID];
//float4 uvwPos1 = _UdonLightVolumeUvwScale[uvwID + 1];
//float4 uvwPos2 = _UdonLightVolumeUvwScale[uvwID + 2];
//float3 uvwScale = float3(uvwPos0.w, uvwPos1.w, uvwPos2.w);
//float3 uvwScaled = saturate(localUVW + 0.5) * uvwScale;
//float3 uvw0 = uvwPos0.xyz + uvwScaled;
//float3 uvw1 = uvwPos1.xyz + uvwScaled;
//float3 uvw2 = uvwPos2.xyz + uvwScaled;
// Legacy! Commented code above will be used in future releases! Legacy!
uint uvwID = id * 6;
float3 uvwScaled = saturate(localUVW + 0.5) * (_UdonLightVolumeUvw[uvwID + 1].xyz - _UdonLightVolumeUvw[uvwID].xyz);
float3 uvw0 = uvwScaled + _UdonLightVolumeUvw[uvwID].xyz;
float3 uvw1 = uvwScaled + _UdonLightVolumeUvw[uvwID + 2].xyz;
float3 uvw2 = uvwScaled + _UdonLightVolumeUvw[uvwID + 4].xyz;
// Sample additive
float3 l0, l1r, l1g, l1b;
LV_SampleLightVolumeTex(uvw0, uvw1, uvw2, l0, l1r, l1g, l1b);
// Sample occlusion
float4 uvwOcclusion = _UdonLightVolumeOcclusionUvw[id];
[branch] if (uvwOcclusion.x >= 0) {
occlusion = 1.0f - LV_SAMPLE(_UdonLightVolume, uvwOcclusion.xyz + uvwScaled * uvwOcclusion.w);
} else {
occlusion = 1;
}
// Color correction
float4 color = _UdonLightVolumeColor[id];
L0 += l0 * color.rgb;
l1r *= color.r;
l1g *= color.g;
l1b *= color.b;
// Rotate if needed
if (color.a != 0) {
//float4 r = _UdonLightVolumeRotationQuaternion[id];
//L1r = LV_MultiplyVectorByQuaternion(L1r, r);
//L1g = LV_MultiplyVectorByQuaternion(L1g, r);
//L1b = LV_MultiplyVectorByQuaternion(L1b, r);
// Legacy to support older light volumes worlds! Commented code above will be used in future releases! Legacy!
float3 r0 = _UdonLightVolumeRotation[id * 2].xyz;
float3 r1 = _UdonLightVolumeRotation[id * 2 + 1].xyz;
L1r += LV_MultiplyVectorByMatrix2x3(l1r, r0, r1);
L1g += LV_MultiplyVectorByMatrix2x3(l1g, r0, r1);
L1b += LV_MultiplyVectorByMatrix2x3(l1b, r0, r1);
} else {
L1r += l1r;
L1g += l1g;
L1b += l1b;
}
}
float4 LV_SampleVolumeOcclusion(uint id, float3 localUVW) {
// Sample occlusion
float4 uvwOcclusion = _UdonLightVolumeOcclusionUvw[id];
[branch] if (uvwOcclusion.x >= 0) {
//uint uvwID = id * 3;
//float4 uvwPos0 = _UdonLightVolumeUvwScale[uvwID];
//float4 uvwPos1 = _UdonLightVolumeUvwScale[uvwID + 1];
//float4 uvwPos2 = _UdonLightVolumeUvwScale[uvwID + 2];
//float3 uvwScale = float3(uvwPos0.w, uvwPos1.w, uvwPos2.w);
//float3 uvwScaled = saturate(localUVW + 0.5) * uvwScale;
// Legacy to support older light volumes worlds! Commented code above will be used in future releases! Legacy!
uint uvwID = id * 6;
float3 uvwScaled = saturate(localUVW + 0.5) * (_UdonLightVolumeUvw[uvwID + 1].xyz - _UdonLightVolumeUvw[uvwID].xyz);
return 1.0f - LV_SAMPLE(_UdonLightVolume, uvwOcclusion.xyz + uvwScaled * uvwOcclusion.w);
} else {
return 1;
}
}
// Calculates L1 SH based on the world position and occlusion factor. Only samples point lights, not light volumes.
void LV_PointLightVolumeSH(float3 worldPos, float4 occlusion, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b) {
uint pointCount = min((uint) _UdonPointLightVolumeCount, VRCLV_MAX_LIGHTS_COUNT);
[branch] if (pointCount == 0) return;
uint maxOverdraw = min((uint) _UdonLightVolumeAdditiveMaxOverdraw, VRCLV_MAX_LIGHTS_COUNT);
uint pcount = 0; // Point lights counter
[loop] for (uint pid = 0; pid < pointCount && pcount < maxOverdraw; pid++) {
LV_PointLight(pid, worldPos, occlusion, L0, L1r, L1g, L1b, pcount);
}
}
// Calculates L1 SH and occlusion based on the world position. Only samples light volumes, not point lights.
void LV_LightVolumeSH(float3 worldPos, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, out float4 occlusion) {
// Initializing output variables
occlusion = 1;
float4 mOcclusion = 1; // Multiplicative occlusion. Applies on top of regular occlusion
// Clamping gloabal iteration counts
uint volumesCount = min((uint) _UdonLightVolumeCount, VRCLV_MAX_VOLUMES_COUNT);
//if (_UdonLightVolumeVersion < VRCLV_VERSION || volumesCount == 0 ) { // Fallback to default light probes if Light Volume are not enabled or a version is too old to have a support
[branch] if (volumesCount == 0) { // Legacy! Fallback to default light probes if Light Volume are not enabled or a version is too old to have a support. Legacy!
LV_SampleLightProbe(L0, L1r, L1g, L1b);
return;
}
uint maxOverdraw = min((uint) _UdonLightVolumeAdditiveMaxOverdraw, VRCLV_MAX_VOLUMES_COUNT);
uint additiveCount = min((uint) _UdonLightVolumeAdditiveCount, VRCLV_MAX_VOLUMES_COUNT);
bool lightProbesBlend = _UdonLightVolumeProbesBlend;
uint volumeID_A = -1; // Main, dominant volume ID
uint volumeID_B = -1; // Secondary volume ID to blend main with
float3 localUVW = 0; // Last local UVW to use in disabled Light Probes mode
float3 localUVW_A = 0; // Main local UVW
float3 localUVW_B = 0; // Secondary local UVW
// Are A and B volumes NOT found?
bool isNoA = true;
bool isNoB = true;
// Additive volumes variables
uint addVolumesCount = 0;
// Iterating through all light volumes with simplified algorithm requiring Light Volumes to be sorted by weight in descending order
[loop] for (uint id = 0; id < volumesCount; id++) {
localUVW = LV_LocalFromVolume(id, worldPos);
[branch] if (LV_PointLocalAABB(localUVW)) { // Intersection test
[branch] if (id < additiveCount) { // Sampling additive volumes
[branch] if (addVolumesCount < maxOverdraw) {
float4 occ; // Multiplicative occlusion
LV_SampleVolume(id, localUVW, L0, L1r, L1g, L1b, occ);
mOcclusion *= occ;
addVolumesCount++;
}
} else if (isNoA) { // First, searching for volume A
volumeID_A = id;
localUVW_A = localUVW;
isNoA = false;
} else { // Next, searching for volume B if A found
volumeID_B = id;
localUVW_B = localUVW;
isNoB = false;
break;
}
}
}
// If no volumes found, using Light Probes as fallback
[branch] if (isNoA && lightProbesBlend) {
LV_SampleLightProbe(L0, L1r, L1g, L1b);
occlusion *= mOcclusion;
return;
}
// Fallback to lowest weight light volume if outside of every volume
localUVW_A = isNoA ? localUVW : localUVW_A;
volumeID_A = isNoA ? volumesCount - 1 : volumeID_A;
// Volume A SH components, occlusion, and mask to blend volume sides
float3 L0_A = 0;
float3 L1r_A = 0;
float3 L1g_A = 0;
float3 L1b_A = 0;
float4 occlusion_A = 1;
// Sampling Light Volume A
LV_SampleVolume(volumeID_A, localUVW_A, L0_A, L1r_A, L1g_A, L1b_A, occlusion_A);
float mask = LV_BoundsMask(localUVW_A, _UdonLightVolumeInvLocalEdgeSmooth[volumeID_A]);
[branch] if (mask == 1 || isNoA || (_UdonLightVolumeSharpBounds && isNoB)) { // Returning SH A result if it's the center of mask or out of bounds
L0 += L0_A;
L1r += L1r_A;
L1g += L1g_A;
L1b += L1b_A;
occlusion = occlusion_A;
occlusion *= mOcclusion;
return;
}
// Volume B SH components and occlusion
float3 L0_B = 0;
float3 L1r_B = 0;
float3 L1g_B = 0;
float3 L1b_B = 0;
float4 occlusion_B = 1;
[branch] if (isNoB && lightProbesBlend) { // No Volume found and light volumes blending enabled
// Sample Light Probes B
LV_SampleLightProbe(L0_B, L1r_B, L1g_B, L1b_B);
} else { // Blending Volume A and Volume B
// If no volume b found, use last one found to fallback
localUVW_B = isNoB ? localUVW : localUVW_B;
volumeID_B = isNoB ? volumesCount - 1 : volumeID_B;
// Sampling Light Volume B
LV_SampleVolume(volumeID_B, localUVW_B, L0_B, L1r_B, L1g_B, L1b_B, occlusion_B);
}
// Lerping occlusion
occlusion = lerp(occlusion_B, occlusion_A, mask);
occlusion *= mOcclusion;
// Lerping SH components
L0 += lerp(L0_B, L0_A, mask);
L1r += lerp(L1r_B, L1r_A, mask);
L1g += lerp(L1g_B, L1g_A, mask);
L1b += lerp(L1b_B, L1b_A, mask);
}
// Calculates L1 SH based on the world position from additive volumes only. Only samples light volumes, not point lights.
// Also returns an occlusion factor, which may be used for point light shadows.
void LV_LightVolumeAdditiveSH(float3 worldPos, inout float3 L0, inout float3 L1r, inout float3 L1g, inout float3 L1b, out float4 occlusion) {
// Initializing output variables
occlusion = 1;
float4 mOcclusion = 1; // Multiplicative occlusion. Applies on top of regular occlusion
// Clamping gloabal iteration counts
uint additiveCount = min((uint) _UdonLightVolumeAdditiveCount, VRCLV_MAX_VOLUMES_COUNT);
//if (_UdonLightVolumeVersion < VRCLV_VERSION || (additiveCount == 0 && pointCount == 0)) return;
[branch] if (additiveCount == 0 && (uint) _UdonPointLightVolumeCount == 0) return; // Legacy!
uint volumesCount = min((uint) _UdonLightVolumeCount, VRCLV_MAX_VOLUMES_COUNT);
uint maxOverdraw = min((uint) _UdonLightVolumeAdditiveMaxOverdraw, VRCLV_MAX_VOLUMES_COUNT);
uint volumeID_A = -1; // Main, dominant volume ID
uint volumeID_B = -1; // Secondary volume ID to blend main with
float3 localUVW = 0; // Last local UVW to use in disabled Light Probes mode
float3 localUVW_A = 0; // Main local UVW for Y Axis and Free rotations
float3 localUVW_B = 0; // Secondary local UVW
// Are A and B volumes NOT found?
bool isNoA = true;
bool isNoB = true;
// Additive volumes variables
uint addVolumesCount = 0;
// Iterating through all light volumes with simplified algorithm requiring Light Volumes to be sorted by weight in descending order
uint count = min(_UdonLightVolumeOcclusionCount == 0 ? additiveCount : volumesCount, VRCLV_MAX_VOLUMES_COUNT); // Only use all volumes if occlusion volumes are enabled
[loop] for (uint id = 0; id < count; id++) {
localUVW = LV_LocalFromVolume(id, worldPos);
[branch] if (LV_PointLocalAABB(localUVW)) { // Intersection test
[branch] if (id < additiveCount) { // Sampling additive volumes
[branch] if (addVolumesCount < maxOverdraw) {
float4 occ; // Multiplicative occlusion
LV_SampleVolume(id, localUVW, L0, L1r, L1g, L1b, occ);
mOcclusion *= occ;
addVolumesCount++;
}
} else if (isNoA) { // First, searching for volume A
volumeID_A = id;
localUVW_A = localUVW;
isNoA = false;
} else { // Next, searching for volume B if A found
volumeID_B = id;
localUVW_B = localUVW;
isNoB = false;
break;
}
}
}
// If no volumes found, or we don't need the occlusion data, we are done
[branch] if (isNoA || _UdonLightVolumeOcclusionCount == 0) {
occlusion *= mOcclusion;
return;
}
// Fallback to lowest weight light volume if outside of every volume
localUVW_A = isNoA ? localUVW : localUVW_A;
volumeID_A = isNoA ? volumesCount - 1 : volumeID_A;
// Sampling Light Volume A
occlusion = LV_SampleVolumeOcclusion(volumeID_A, localUVW_A);
float mask = LV_BoundsMask(localUVW_A, _UdonLightVolumeInvLocalEdgeSmooth[volumeID_A]);
[branch] if (mask == 1 || (_UdonLightVolumeSharpBounds && isNoB)) {
occlusion *= mOcclusion;
return; // Returning A result if it's the center of mask or out of bounds
}
// Blending Volume A and Volume B
[branch] if (isNoB) occlusion = lerp(1, occlusion, mask);
else occlusion = lerp(LV_SampleVolumeOcclusion(volumeID_B, localUVW_B), occlusion, mask);
occlusion *= mOcclusion;
}
// Calculates speculars for light volumes or any SH L1 data with privided f0
float3 LightVolumeSpecular(float3 f0, float smoothness, float3 worldNormal, float3 viewDir, float3 L0, float3 L1r, float3 L1g, float3 L1b) {
float3 specColor = max(float3(dot(reflect(-L1r, worldNormal), viewDir), dot(reflect(-L1g, worldNormal), viewDir), dot(reflect(-L1b, worldNormal), viewDir)), 0);
float3 rDir = normalize(normalize(L1r) + viewDir);
float3 gDir = normalize(normalize(L1g) + viewDir);
float3 bDir = normalize(normalize(L1b) + viewDir);
float rNh = saturate(dot(worldNormal, rDir));
float gNh = saturate(dot(worldNormal, gDir));
float bNh = saturate(dot(worldNormal, bDir));
float roughness = 1 - smoothness * 0.9f;
float roughExp = roughness * roughness;
float rSpec = LV_DistributionGGX(rNh, roughExp);
float gSpec = LV_DistributionGGX(gNh, roughExp);
float bSpec = LV_DistributionGGX(bNh, roughExp);
float3 specs = (rSpec + gSpec + bSpec) * f0;
float3 coloredSpecs = specs * specColor;
float3 a = coloredSpecs + specs * L0;
float3 b = coloredSpecs * 3;
return max(lerp(a, b, smoothness) * 0.5f, 0.0);
}
// Calculates speculars for light volumes or any SH L1 data
float3 LightVolumeSpecular(float3 albedo, float smoothness, float metallic, float3 worldNormal, float3 viewDir, float3 L0, float3 L1r, float3 L1g, float3 L1b) {
float3 specularf0 = lerp(0.04f, albedo, metallic);
return LightVolumeSpecular(specularf0, smoothness, worldNormal, viewDir, L0, L1r, L1g, L1b);
}
// Calculates speculars for light volumes or any SH L1 data, but simplified, with only one dominant direction with provided f0
float3 LightVolumeSpecularDominant(float3 f0, float smoothness, float3 worldNormal, float3 viewDir, float3 L0, float3 L1r, float3 L1g, float3 L1b) {
float3 dominantDir = L1r + L1g + L1b;
float3 dir = normalize(normalize(dominantDir) + viewDir);
float nh = saturate(dot(worldNormal, dir));
float roughness = 1 - smoothness * 0.9f;
float roughExp = roughness * roughness;
float spec = LV_DistributionGGX(nh, roughExp);
return max(spec * L0 * f0, 0.0) * 1.5f;
}
// Calculates speculars for light volumes or any SH L1 data, but simplified, with only one dominant direction
float3 LightVolumeSpecularDominant(float3 albedo, float smoothness, float metallic, float3 worldNormal, float3 viewDir, float3 L0, float3 L1r, float3 L1g, float3 L1b) {
float3 specularf0 = lerp(0.04f, albedo, metallic);
return LightVolumeSpecularDominant(specularf0, smoothness, worldNormal, viewDir, L0, L1r, L1g, L1b);
}
// Calculate Light Volume Color based on all SH components provided and the world normal
float3 LightVolumeEvaluate(float3 worldNormal, float3 L0, float3 L1r, float3 L1g, float3 L1b) {
return float3(LV_EvaluateSH(L0.r, L1r, worldNormal), LV_EvaluateSH(L0.g, L1g, worldNormal), LV_EvaluateSH(L0.b, L1b, worldNormal));
}
// Calculates L1 SH based on the world position. Samples both light volumes and point lights.
void LightVolumeSH(float3 worldPos, out float3 L0, out float3 L1r, out float3 L1g, out float3 L1b, float3 worldPosOffset = 0) {
L0 = 0; L1r = 0; L1g = 0; L1b = 0;
if (_UdonLightVolumeEnabled == 0) {
LV_SampleLightProbeDering(L0, L1r, L1g, L1b);
} else {
float4 occlusion = 1;
LV_LightVolumeSH(worldPos + worldPosOffset, L0, L1r, L1g, L1b, occlusion);
LV_PointLightVolumeSH(worldPos, occlusion, L0, L1r, L1g, L1b);
}
}
// Calculates L1 SH based on the world position from additive volumes only. Samples both light volumes and point lights.
void LightVolumeAdditiveSH(float3 worldPos, out float3 L0, out float3 L1r, out float3 L1g, out float3 L1b, float3 worldPosOffset = 0) {
L0 = 0; L1r = 0; L1g = 0; L1b = 0;
if (_UdonLightVolumeEnabled != 0) {
float4 occlusion = 1;
LV_LightVolumeAdditiveSH(worldPos + worldPosOffset, L0, L1r, L1g, L1b, occlusion);
LV_PointLightVolumeSH(worldPos, occlusion, L0, L1r, L1g, L1b);
}
}
// Calculates L0 SH based on the world position. Samples both light volumes and point lights.
float3 LightVolumeSH_L0(float3 worldPos, float3 worldPosOffset = 0) {
if (_UdonLightVolumeEnabled == 0) {
return float3(unity_SHAr.w, unity_SHAg.w, unity_SHAb.w);
} else {
float3 L0 = 0; float4 occlusion = 1;
float3 unused_L1; // Let's just pray that compiler will strip everything x.x
LV_LightVolumeSH(worldPos + worldPosOffset, L0, unused_L1, unused_L1, unused_L1, occlusion);
LV_PointLightVolumeSH(worldPos, occlusion, L0, unused_L1, unused_L1, unused_L1);
return L0;
}
}
// Calculates L0 SH based on the world position from additive volumes only. Samples both light volumes and point lights.
float3 LightVolumeAdditiveSH_L0(float3 worldPos, float3 worldPosOffset = 0) {
if (_UdonLightVolumeEnabled == 0) {
return 0;
} else {
float3 L0 = 0; float4 occlusion = 1;
float3 unused_L1; // Let's just pray that compiler will strip everything x.x
LV_LightVolumeAdditiveSH(worldPos + worldPosOffset, L0, unused_L1, unused_L1, unused_L1, occlusion);
LV_PointLightVolumeSH(worldPos, occlusion, L0, unused_L1, unused_L1, unused_L1);
return L0;
}
}
// Checks if Light Volumes are used in this scene. Returns 0 if not, returns 1 if enabled
float LightVolumesEnabled() {
return _UdonLightVolumeEnabled;
}
// Returns the light volumes version
float LightVolumesVersion() {
return _UdonLightVolumeVersion == 0 ? _UdonLightVolumeEnabled : _UdonLightVolumeVersion;
}
#endif

View File

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

View File

@ -0,0 +1,47 @@
#ifndef SERVICE_FILTERING_INCLUDED
#define SERVICE_FILTERING_INCLUDED
half4 cubic(half v)
{
half4 n = half4(1.0, 2.0, 3.0, 4.0) - v;
half4 s = n * n * n;
half x = s.x;
half y = s.y - 4.0 * s.x;
half z = s.z - 4.0 * s.y + 6.0 * s.x;
half w = 6.0 - x - y - z;
return half4(x, y, z, w);
}
// Unity's SampleTexture2DBicubic doesn't exist in 2018, which is our target here.
// So this is a similar function with tweaks to have similar semantics.
half4 SampleTexture2DBicubicFilter(TEXTURE2D_PARAM(tex, smp), float2 coord, float4 texSize)
{
coord = coord * texSize.xy - 0.5;
half fx = frac(coord.x);
half fy = frac(coord.y);
coord.x -= fx;
coord.y -= fy;
half4 xcubic = cubic(fx);
half4 ycubic = cubic(fy);
float4 c = float4(coord.x - 0.5, coord.x + 1.5, coord.y - 0.5, coord.y + 1.5);
float4 s = float4(xcubic.x + xcubic.y, xcubic.z + xcubic.w, ycubic.x + ycubic.y, ycubic.z + ycubic.w);
float4 offset = c + float4(xcubic.y, xcubic.w, ycubic.y, ycubic.w) / s;
half4 sample0 = SAMPLE_TEXTURE2D(tex, smp, half2(offset.x, offset.z) * texSize.zw);
half4 sample1 = SAMPLE_TEXTURE2D(tex, smp, half2(offset.y, offset.z) * texSize.zw);
half4 sample2 = SAMPLE_TEXTURE2D(tex, smp, half2(offset.x, offset.w) * texSize.zw);
half4 sample3 = SAMPLE_TEXTURE2D(tex, smp, half2(offset.y, offset.w) * texSize.zw);
half sx = s.x / (s.x + s.y);
half sy = s.z / (s.z + s.w);
return lerp(
lerp(sample3, sample2, sx),
lerp(sample1, sample0, sx), sy);
}
#endif // SERVICE_FILTERING_INCLUDED

View File

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

View File

@ -0,0 +1,235 @@
#ifndef GLINTY_NDF_INCLUDED
#define GLINTY_NDF_INCLUDED
// "Evaluating and Sampling Glinty NDFs in Constant Time"
// Based on Kemppinen et al. 2025
#define GLINT_PI 3.14159265358979
#define GLINT_HALF_PI 3.14159265h
// --- Internal Utilities ---
half2 lambert_map(float3 v) {
return (half2)(v.xy / sqrt(1.0 + v.z));
}
// Maps GGX NDF to a 2D disk
float3 ndf_to_disk_ggx(float3 v, float alpha) {
float3 hemi = float3(v.xy / alpha, v.z);
float denom = dot(hemi, hemi);
half2 v_disk = lambert_map(normalize(hemi)) * 0.5h + 0.5h;
float jacobian_determinant = 1.0 / (alpha * alpha * denom * denom);
return float3(v_disk, jacobian_determinant);
}
// 2x2 Inverse
float2x2 inverse2x2(float2x2 m) {
float det = m._m00 * m._m11 - m._m01 * m._m10;
return float2x2(m._m11, -m._m01, -m._m10, m._m00) / det;
}
float2x2 inv_quadratic(float2x2 M) {
float D = determinant(M);
float2 col0 = float2(M._m00, M._m10) / D;
float2 col1 = float2(M._m01, M._m11) / D;
float A = dot(col0, col0);
float B = -dot(col0, col1);
float C = dot(col1, col1);
return float2x2(C, B, B, A);
}
// Converts UV Jacobian into an anisotropy-aware ellipsoid matrix
float2x2 get_uv_ellipsoid(float2x2 uv_J) {
float2x2 Q = inv_quadratic(transpose(uv_J));
float tr = 0.5 * (Q._m00 + Q._m11);
float D = sqrt(max(0.0, tr * tr - determinant(Q)));
float l1 = tr - D;
float l2 = tr + D;
float2 v1 = float2(l1 - Q._m11, Q._m10);
float2 v2 = float2(Q._m01, l2 - Q._m00);
float2 n = 1.0 / sqrt(float2(l1, l2));
float2 col0 = normalize(v1) * n.x;
float2 col1 = normalize(v2) * n.y;
// Constructing column-major equivalent for the math later
return float2x2(col0.x, col1.x, col0.y, col1.y);
}
float query_lod(float2x2 uv_J, float filter_size) {
float s0 = length(float2(uv_J._m00, uv_J._m10));
float s1 = length(float2(uv_J._m01, uv_J._m11));
return log2(max(s0, s1) * filter_size) + pow(2.0, filter_size);
}
uint2 shuffle_hash(uint2 v) {
v = v * 1664525u + 1013904223u;
v.x += v.y * 1664525u;
v.y += v.x * 1664525u;
v = v ^ (v >> 16u);
v.x += v.y * 1664525u;
v.y += v.x * 1664525u;
v = v ^ (v >> 16u);
return v;
}
half2 rand2d(float2 x, float2 y, float l, uint i) {
uint2 ux = asuint(x), uy = asuint(y);
uint ul = asuint(l);
uint2 seed = (ux >> 16u | ux << 16u) ^ uy ^ ul ^ (i * 0x124u);
// Cast to half2 since random output is strictly [0, 1]
return (half2)(float2(shuffle_hash(seed)) * pow(0.5, 32.0));
}
half rand1d(float2 x, float2 y, float l, uint i) {
return rand2d(x, y, l, i).x;
}
half fast_erf(half x) {
half e = exp(-x * x);
half sign_x = sign(x);
// Constants pre-calculated to half precision
half scale = sqrt((1.0h - e) / GLINT_HALF_PI);
half poly = 0.886226h + 0.155h * e - 0.042625h * e * e; // (sqrt(pi)/2), (31/200), (341/8000)
return sign_x * 2.0h * scale * poly;
}
half gaussian_cdf(float x, float mu, float sigma) {
float z = (x - mu) / (sigma * 1.41421356);
return 0.5h + 0.5h * fast_erf((half)z);
}
half integrate_interval(float x, float size, float mu, float stdev, float lower_limit, float upper_limit) {
return gaussian_cdf(min(x + size, upper_limit), mu, stdev) - gaussian_cdf(max(x - size, lower_limit), mu, stdev);
}
half integrate_box(float2 x, float2 size, float2 mu, float2x2 sigma, float2 lower_limit, float2 upper_limit) {
return integrate_interval(x.x, size.x, mu.x, sqrt(sigma._m00), lower_limit.x, upper_limit.x) *
integrate_interval(x.y, size.y, mu.y, sqrt(sigma._m11), lower_limit.y, upper_limit.y);
}
half glint_compensation(float2 x_a, float2x2 sigma_a, float res_a) {
half containing = integrate_box(0.5f.xx, 0.5f.xx, x_a, sigma_a, 0.0f.xx, 1.0f.xx);
half explicitly_evaluated = integrate_box(round(x_a * res_a) / res_a, (1.0 / res_a).xx, x_a, sigma_a, 0.0f.xx, 1.0f.xx);
return containing - explicitly_evaluated;
}
float eval_normal(float2x2 cov, float2 x) {
float2x2 inv_cov = inverse2x2(cov);
return exp(-0.5 * dot(x, mul(inv_cov, x))) / (sqrt(determinant(cov)) * 2.0 * GLINT_PI);
}
// --- Public Interface ---
/**
* Main Glinty NDF Function
* @param h Local space half-vector
* @param alpha Macro-roughness (standard GGX roughness)
* @param glint_alpha Micro-roughness (the size/sharpness of individual glints, e.g., 0.01)
* @param uv Surface UV coordinates
* @param uv_J Jacobian of the UVs (use get_uv_ellipsoid(float2x2(ddx(uv), ddy(uv))))
* @param glint_density Scaling factor for glint particles (e.g., 1000 to 1000000)
* @param filter_size Standard pixel filter size (e.g., 0.7 to 1.2)
*/
float EvaluateGlintyNDF(float3 h, float alpha, float glint_alpha, float2 uv, float2x2 uv_J, float glint_density, float filter_size) {
float res = sqrt(glint_density);
float2 x_s = uv;
float3 x_a_and_d = ndf_to_disk_ggx(h, alpha);
float2 x_a = x_a_and_d.xy;
float d = x_a_and_d.z;
float lambda = query_lod(res * uv_J, filter_size);
float D_filter = 0.0;
for(float m = 0.0; m < 2.0; m += 1.0) {
float l = floor(lambda) + m;
half w_lambda = (half)(1.0 - abs(lambda - l));
float res_s = res * exp2(-l);
float res_a = exp2(l);
float2x2 uv_J2 = filter_size * uv_J;
float2x2 sigma_s = mul(uv_J2, transpose(uv_J2));
float det_J2 = determinant(uv_J2);
float det_sigma_s = det_J2 * det_J2;
float2x2 inv_sigma_s = float2x2(sigma_s._m11, -sigma_s._m01, -sigma_s._m10, sigma_s._m00) / det_sigma_s;
float norm_s = 1.0 / (abs(det_J2) * 2.0 * GLINT_PI * glint_density);
float var_a = d * glint_alpha * glint_alpha;
float norm_a = 1.0 / (var_a * 2.0 * GLINT_PI);
float stdev_a = sqrt(var_a);
float2 base_i_a = clamp(round(x_a * res_a), 1.0, res_a - 1.0);
for(int j_a = 0; j_a < 4; ++j_a) {
half2 offset_a = (half2)(float2(j_a & 1, j_a >> 1) - 0.5);
float2 i_a = base_i_a + offset_a;
float2 base_i_s = round(x_s * res_s);
for(int j_s = 0; j_s < 4; ++j_s) {
half2 offset_s = (half2)(float2(j_s & 1, j_s >> 1) - 0.5);
float2 i_s = base_i_s + offset_s;
float2 g_s = (i_s + rand2d(i_s, i_a, l, 1u) - 0.5) / res_s;
float2 g_a = (i_a + rand2d(i_s, i_a, l, 2u) - 0.5) / res_a;
half r = rand1d(i_s, i_a, l, 4u);
half roulette = smoothstep(max(0.0h, r - 0.1h), min(1.0h, r + 0.1h), w_lambda);
float2 delta_a = x_a - g_a;
float eval_a = exp(-0.5 * dot(delta_a, delta_a) / var_a) * norm_a;
float2 delta_s = x_s - g_s;
float eval_s = exp(-0.5 * dot(delta_s, mul(inv_sigma_s, delta_s))) * norm_s;
D_filter += roulette * eval_a * eval_s;
}
}
D_filter += w_lambda * glint_compensation(x_a, stdev_a, res_a);
}
return D_filter * d / GLINT_PI;
}
/*** Sample implementation...
// 1. Setup Inputs
float3 V = normalize(_WorldSpaceCameraPos - input.worldPos);
float3 L = normalize(_MainLightPosition.xyz);
float3 H = normalize(V + L);
float3 N = normalize(input.normal);
// Transform H to local tangent space
float3 tangentH = WorldToTangent(H, input.tangent, input.bitangent, N);
// 2. Prepare Derivatives for Anisotropic Filtering
float2x2 Jacobian = float2x2(ddx(input.uv), ddy(input.uv));
float2x2 uv_ellipsoid = get_uv_ellipsoid(Jacobian);
// 3. Evaluate NDF
// alpha: standard roughness (0.1 - 0.8)
// glint_alpha: micro-roughness (0.005 - 0.05)
// glint_density: how many particles (10^4 to 10^9)
float D = EvaluateGlintyNDF(
tangentH,
_Roughness,
_GlintMicroRoughness,
input.uv,
uv_ellipsoid,
_GlintDensity,
0.8 // Filter size
);
// 4. Standard BRDF integration
// Use D instead of the standard GGX D term in: (D * F * G) / (4 * NoV * NoL)
float NoL = saturate(dot(N, L));
float NoV = saturate(dot(N, V));
float3 spec = (D * F * G) / max(1e-4, 4.0 * NoV * NoL);
return float4(spec * NoL * _LightColor.rgb, 1.0);
***/
#endif

View File

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

View File

@ -0,0 +1,324 @@
#ifndef COMMON_LIGHTMAP_INCLUDED
#define COMMON_LIGHTMAP_INCLUDED
#include "SharedSHLib.hlsl"
half4 UnityLightmap_ColorIntensitySeperated(half3 lightmap) {
lightmap += 0.000001;
return float4(lightmap.xyz / 1, 1);
}
half4 SampleLightmapBicubic(float2 uv)
{
#if defined(SHADER_API_D3D11)
float width, height;
unity_Lightmap.GetDimensions(width, height);
float4 unity_Lightmap_TexelSize = float4(width, height, 1.0/width, 1.0/height);
return SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(unity_Lightmap, samplerunity_Lightmap),
uv, unity_Lightmap_TexelSize);
#else
return SAMPLE_TEXTURE2D(unity_Lightmap, samplerunity_Lightmap, uv);
#endif
}
half4 SampleLightmapDirBicubic(float2 uv)
{
// We don't need to sample the directionality with bicubic filtering
#if defined(SHADER_API_D3D11) && false
float width, height;
unity_LightmapInd.GetDimensions(width, height);
float4 unity_LightmapInd_TexelSize = float4(width, height, 1.0/width, 1.0/height);
return SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(unity_LightmapInd, samplerunity_Lightmap),
uv, unity_LightmapInd_TexelSize);
#else
return SAMPLE_TEXTURE2D(unity_LightmapInd, samplerunity_Lightmap, uv);
#endif
}
half4 SampleDynamicLightmapBicubic(float2 uv)
{
#if defined(SHADER_API_D3D11)
float width, height;
unity_DynamicLightmap.GetDimensions(width, height);
float4 unity_DynamicLightmap_TexelSize = float4(width, height, 1.0/width, 1.0/height);
return SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(unity_DynamicLightmap, samplerunity_DynamicLightmap),
uv, unity_DynamicLightmap_TexelSize);
#else
return SAMPLE_TEXTURE2D(unity_DynamicLightmap, samplerunity_DynamicLightmap, uv);
#endif
}
half4 SampleDynamicLightmapDirBicubic(float2 uv)
{
// We don't need to sample the directionality with bicubic filtering
#if defined(SHADER_API_D3D11) && false
float width, height;
unity_DynamicDirectionality.GetDimensions(width, height);
float4 unity_DynamicDirectionality_TexelSize = float4(width, height, 1.0/width, 1.0/height);
return SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(unity_DynamicDirectionality, samplerunity_DynamicLightmap),
uv, unity_DynamicDirectionality_TexelSize);
#else
return SAMPLE_TEXTURE2D(unity_DynamicDirectionality, samplerunity_DynamicLightmap, uv);
#endif
}
inline half3 DecodeDirectionalLightmapSpecular(half3 color, half4 dirTex, half3 normalWorld,
const bool isRealtimeLightmap, fixed4 realtimeNormalTex, out Light o_light)
{
o_light = (Light)0;
o_light.colorIntensity = float4(color, 1.0);
o_light.l = dirTex.xyz * 2 - 1;
// The length of the direction vector is the light's "directionality", i.e. 1 for all light coming from this direction,
// lower values for more spread out, ambient light.
half directionality = max(0.001, length(o_light.l));
o_light.l /= directionality;
#ifdef DYNAMICLIGHTMAP_ON
if (isRealtimeLightmap)
{
// Realtime directional lightmaps' intensity needs to be divided by N.L
// to get the incoming light intensity. Baked directional lightmaps are already
// output like that (including the max() to prevent div by zero).
half3 realtimeNormal = realtimeNormalTex.xyz * 2 - 1;
o_light.colorIntensity /= max(0.125, dot(realtimeNormal, o_light.l));
}
#endif
// Split light into the directional and ambient parts, according to the directionality factor.
half3 ambient = o_light.colorIntensity * (1 - directionality);
o_light.colorIntensity = o_light.colorIntensity * directionality;
o_light.attenuation = directionality;
o_light.NoL = saturate(dot(normalWorld, o_light.l));
return color * lerp(1.0, o_light.NoL, directionality);
}
#if defined(USING_BAKERY) && defined(LIGHTMAP_ON)
// needs specular variant?
half3 DecodeRNMLightmap(half3 color, half2 lightmapUV, half3 normalTangent, float3x3 tangentToWorld, out Light o_light)
{
const float rnmBasis0 = float3(0.816496580927726f, 0, 0.5773502691896258f);
const float rnmBasis1 = float3(-0.4082482904638631f, 0.7071067811865475f, 0.5773502691896258f);
const float rnmBasis2 = float3(-0.4082482904638631f, -0.7071067811865475f, 0.5773502691896258f);
half3 irradiance;
o_light = (Light)0;
#if defined(SHADER_API_D3D11)
float width, height;
_RNM0.GetDimensions(width, height);
float4 rnm_TexelSize = float4(width, height, 1.0/width, 1.0/height);
half3 rnm0 = DecodeLightmap(SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(_RNM0, sampler_RNM0), lightmapUV, rnm_TexelSize));
half3 rnm1 = DecodeLightmap(SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(_RNM1, sampler_RNM0), lightmapUV, rnm_TexelSize));
half3 rnm2 = DecodeLightmap(SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(_RNM2, sampler_RNM0), lightmapUV, rnm_TexelSize));
#else
half3 rnm0 = DecodeLightmap(SAMPLE_TEXTURE2D(_RNM0, sampler_RNM0, lightmapUV));
half3 rnm1 = DecodeLightmap(SAMPLE_TEXTURE2D(_RNM1, sampler_RNM0, lightmapUV));
half3 rnm2 = DecodeLightmap(SAMPLE_TEXTURE2D(_RNM2, sampler_RNM0, lightmapUV));
#endif
normalTangent.g *= -1;
irradiance = saturate(dot(rnmBasis0, normalTangent)) * rnm0
+ saturate(dot(rnmBasis1, normalTangent)) * rnm1
+ saturate(dot(rnmBasis2, normalTangent)) * rnm2;
#if defined(LIGHTMAP_SPECULAR)
float3 dominantDirT = rnmBasis0 * luminance(rnm0) +
rnmBasis1 * luminance(rnm1) +
rnmBasis2 * luminance(rnm2);
half3 dominantDirTN = normalize(dominantDirT);
half3 specColor = saturate(dot(rnmBasis0, dominantDirTN)) * rnm0 +
saturate(dot(rnmBasis1, dominantDirTN)) * rnm1 +
saturate(dot(rnmBasis2, dominantDirTN)) * rnm2;
o_light.l = normalize(mul(tangentToWorld, dominantDirT));
half directionality = max(0.001, length(o_light.l));
o_light.l /= directionality;
// Split light into the directional and ambient parts, according to the directionality factor.
o_light.colorIntensity = float4(specColor * directionality, 1.0);
o_light.attenuation = directionality;
o_light.NoL = saturate(dot(normalTangent, dominantDirTN));
#endif
return irradiance;
}
half3 DecodeSHLightmap(half3 L0, half2 lightmapUV, half3 normalWorld, out Light o_light)
{
half3 irradiance;
o_light = (Light)0;
#if defined(SHADER_API_D3D11)
float width, height;
_RNM0.GetDimensions(width, height);
float4 rnm_TexelSize = float4(width, height, 1.0/width, 1.0/height);
half3 nL1x = SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(_RNM0, sampler_RNM0), lightmapUV, rnm_TexelSize);
half3 nL1y = SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(_RNM1, sampler_RNM0), lightmapUV, rnm_TexelSize);
half3 nL1z = SampleTexture2DBicubicFilter(TEXTURE2D_ARGS(_RNM2, sampler_RNM0), lightmapUV, rnm_TexelSize);
#else
half3 nL1x = SAMPLE_TEXTURE2D(_RNM0, sampler_RNM0, lightmapUV);
half3 nL1y = SAMPLE_TEXTURE2D(_RNM1, sampler_RNM0, lightmapUV);
half3 nL1z = SAMPLE_TEXTURE2D(_RNM2, sampler_RNM0, lightmapUV);
#endif
nL1x = nL1x * 2 - 1;
nL1y = nL1y * 2 - 1;
nL1z = nL1z * 2 - 1;
half3 L1x = nL1x * L0 * 2;
half3 L1y = nL1y * L0 * 2;
half3 L1z = nL1z * L0 * 2;
#ifdef BAKERY_SHNONLINEAR
half lumaL0 = dot(L0, half(1));
half lumaL1x = dot(L1x, half(1));
half lumaL1y = dot(L1y, half(1));
half lumaL1z = dot(L1z, half(1));
half lumaSH = shEvaluateDiffuseL1Geomerics_local(lumaL0, float3(lumaL1x, lumaL1y, lumaL1z), normalWorld);
#if (SPHERICAL_HARMONICS == SPHERICAL_HARMONICS_ZH3)
lumaSH = SHEvalLinearL0L1_ZH3Hallucinate(float4(lumaL0, lumaL1y, lumaL1z, lumaL1x), normalWorld);
#endif
irradiance = L0 + normalWorld.x * L1x + normalWorld.y * L1y + normalWorld.z * L1z;
half regularLumaSH = dot(irradiance, 1);
irradiance *= lerp(1, lumaSH / regularLumaSH, saturate(regularLumaSH*16));
#else
irradiance = L0 + normalWorld.x * L1x + normalWorld.y * L1y + normalWorld.z * L1z;
#endif
#if defined(LIGHTMAP_SPECULAR)
half3 dominantDir = float3(luminance(nL1x), luminance(nL1y), luminance(nL1z));
o_light.l = dominantDir;
half directionality = max(0.001, length(o_light.l));
o_light.l /= directionality;
// Split light into the directional and ambient parts, according to the directionality factor.
o_light.colorIntensity = float4(irradiance * directionality, 1.0);
o_light.attenuation = directionality;
o_light.NoL = saturate(dot(normalWorld, o_light.l));
#endif
return irradiance;
}
#endif // USING_BAKERY
#if defined(USING_BAKERY_VERTEXLMSH)
half3 DecodeSHLightmapVertex(half3 L0, half3 ambientSH[3], half3 normalWorld, out Light o_light)
{
half3 irradiance;
o_light = (Light)0;
half3 nL1x = ambientSH[0];
half3 nL1y = ambientSH[1];
half3 nL1z = ambientSH[2];
nL1x = nL1x * 2 - 1;
nL1y = nL1y * 2 - 1;
nL1z = nL1z * 2 - 1;
half3 L1x = nL1x * L0 * 2;
half3 L1y = nL1y * L0 * 2;
half3 L1z = nL1z * L0 * 2;
#ifdef BAKERY_SHNONLINEAR
half lumaL0 = dot(L0, half(1));
half lumaL1x = dot(L1x, half(1));
half lumaL1y = dot(L1y, half(1));
half lumaL1z = dot(L1z, half(1));
half lumaSH = shEvaluateDiffuseL1Geomerics_local(lumaL0, half3(lumaL1x, lumaL1y, lumaL1z), normalWorld);
#if (SPHERICAL_HARMONICS == SPHERICAL_HARMONICS_ZH3)
lumaSH = SHEvalLinearL0L1_ZH3Hallucinate(float4(lumaL0, lumaL1y, lumaL1z, lumaL1x), normalWorld);
#endif
irradiance = L0 + normalWorld.x * L1x + normalWorld.y * L1y + normalWorld.z * L1z;
half regularLumaSH = dot(irradiance, 1);
irradiance *= lerp(1, lumaSH / regularLumaSH, saturate(regularLumaSH*16));
#else
irradiance = L0 + normalWorld.x * L1x + normalWorld.y * L1y + normalWorld.z * L1z;
#endif
#if defined(LIGHTMAP_SPECULAR)
half3 dominantDir = half3(luminance(nL1x), luminance(nL1y), luminance(nL1z));
o_light.l = dominantDir;
half directionality = max(0.001, length(o_light.l));
o_light.l /= directionality;
// Split light into the directional and ambient parts, according to the directionality factor.
o_light.colorIntensity = float4(irradiance * directionality, 1.0);
o_light.attenuation = directionality;
o_light.NoL = saturate(dot(normalWorld, o_light.l));
#endif
return irradiance;
}
#endif // USING_BAKERY_VERTEXLMSH
#if defined(_BAKERY_MONOSH)
half3 DecodeMonoSHLightmap(half3 L0, half3 dominantDir, half3 normalWorld, out Light o_light, const bool remapDir = true)
{
o_light = (Light)0;
// Vertex mode is already in -1 to 1 range.
half3 nL1 = remapDir? dominantDir * 2 - 1 : dominantDir;
half3 L1x = nL1.x * L0 * 2;
half3 L1y = nL1.y * L0 * 2;
half3 L1z = nL1.z * L0 * 2;
half3 sh;
#if BAKERY_SHNONLINEAR
half lumaL0 = dot(L0, 1);
half lumaL1x = dot(L1x, 1);
half lumaL1y = dot(L1y, 1);
half lumaL1z = dot(L1z, 1);
half lumaSH = shEvaluateDiffuseL1Geomerics_local(lumaL0, half3(lumaL1x, lumaL1y, lumaL1z), normalWorld);
#if (SPHERICAL_HARMONICS == SPHERICAL_HARMONICS_ZH3)
lumaSH = SHEvalLinearL0L1_ZH3Hallucinate(half4(lumaL0, lumaL1y, lumaL1z, lumaL1x), normalWorld);
#endif
sh = L0 + normalWorld.x * L1x + normalWorld.y * L1y + normalWorld.z * L1z;
half regularLumaSH = dot(sh, 1);
sh *= lerp(1, lumaSH / regularLumaSH, saturate(regularLumaSH*16));
#else
sh = L0 + normalWorld.x * L1x + normalWorld.y * L1y + normalWorld.z * L1z;
#endif
#if defined(LIGHTMAP_SPECULAR)
dominantDir = nL1;
o_light.l = dominantDir;
half directionality = max(0.001, length(o_light.l));
o_light.l /= directionality;
// Split light into the directional and ambient parts, according to the directionality factor.
o_light.colorIntensity = float4(L0 * directionality, 1.0);
o_light.attenuation = directionality;
o_light.NoL = saturate(dot(normalWorld, o_light.l));
#endif
return sh;
}
#endif // _BAKERY_MONOSH
#endif // COMMON_LIGHTMAP_INCLUDED

View File

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

View File

@ -0,0 +1,58 @@
#ifndef SERVICE_NORMALSHADOW_INCLUDED
#define SERVICE_NORMALSHADOW_INCLUDED
// Ref: Normal Mapping Shadows by Boris Vorontsov
// Please define a NormalMapShadowsParam parameter
// and SampleNormalMap function to sample the normal map.
half NormalMapShadows (half3 lightDirTangent, NormalMapShadowsParam nmsParam, half noise,
half heightScale, half shadowHardness)
{
const half screenShadowSamples = 20;
const half hardness = heightScale * shadowHardness;
const half sampleStep = 1.0 / screenShadowSamples;
if (lightDirTangent.z <= 0.0) return 0.0;
half2 dir = lightDirTangent.xy * heightScale;
// Redundancy can't be helped
half3 normal = SampleNormalMap(nmsParam, 0);
lightDirTangent = normalize(lightDirTangent);
half tangentNdotL = saturate(dot(lightDirTangent, normal));
half currentSample = sampleStep - sampleStep * noise;
// Skip on backfaces
currentSample += (tangentNdotL <= 0.0);
/*
From the PDF:
Trace from hit point to light direction and compute sum of dot products
between normal map and light direction.
If slope is bigger than 0, pixel is shadowed. If slope is also bigger
than previous maximal value, increase hardness of shadow.
*/
half result = 0;
half slope = -tangentNdotL;
half maxslope = 0.0;
while (currentSample <= 1.0)
{
normal = SampleNormalMap(nmsParam, dir * currentSample);
tangentNdotL = dot(lightDirTangent, normal);
slope = slope - tangentNdotL;
if (slope > maxslope)
{
result += hardness * (1.0-currentSample);
}
maxslope = max(maxslope, slope);
currentSample += sampleStep;
}
return result * sampleStep;
}
#endif // SERVICE_NORMALSHADOW_INCLUDED

View File

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

View File

@ -0,0 +1,164 @@
#ifndef SERVICE_PARALLAX_INCLUDED
#define SERVICE_PARALLAX_INCLUDED
// Please define a PerPixelHeightDisplacementParam parameter
// and ComputePerPixelHeightDisplacement function to sample the heightmap.
float2 ParallaxRaymarching(float2 viewDir, PerPixelHeightDisplacementParam ppdParam,
float strength, out float outHeight)
{
const float raymarch_steps = 10;
float2 uvOffset = 0;
const float stepSize = 1.0 / raymarch_steps;
float2 uvDelta = viewDir * (stepSize * strength);
float stepHeight = 1;
float surfaceHeight = ComputePerPixelHeightDisplacement(0, 0, ppdParam);
float2 prevUVOffset = uvOffset;
float prevStepHeight = stepHeight;
float prevSurfaceHeight = surfaceHeight;
for (int i = 1; i < raymarch_steps && stepHeight > surfaceHeight; i++)
{
prevUVOffset = uvOffset;
prevStepHeight = stepHeight;
prevSurfaceHeight = surfaceHeight;
uvOffset -= uvDelta;
stepHeight -= stepSize;
surfaceHeight = ComputePerPixelHeightDisplacement(uvOffset, 0, ppdParam);
}
float prevDifference = prevStepHeight - prevSurfaceHeight;
float difference = surfaceHeight - stepHeight;
float t = prevDifference / (prevDifference + difference);
uvOffset = prevUVOffset -uvDelta * t;
outHeight = surfaceHeight;
return uvOffset;
}
float2 ParallaxRaymarchingDynamic(float3 viewDir, PerPixelHeightDisplacementParam ppdParam,
float strength, float lod)
{
const float minLayers = 8.0;
const float maxLayers = 48.0;
// lod should be dot(normalWS, viewDirWS)
float numLayers = lerp(maxLayers, minLayers, clamp(lod, 0, 1));
if (viewDir.z < 0.001) return 0;
float heightScale = _Parallax; // 0.05
float layerDepth = 1.0 / numLayers;
float currLayerDepth = 0.0;
float2 deltaUV = viewDir.xy * heightScale / (viewDir.z * numLayers);
float2 uvOffset = 0;
float height = 1.0 - ComputePerPixelHeightDisplacement(0, 0, ppdParam);
for (int i = 0; i < numLayers; i++) {
currLayerDepth += layerDepth;
uvOffset -= deltaUV;
height = 1.0 - ComputePerPixelHeightDisplacement(uvOffset, 0, ppdParam);
if (height < currLayerDepth) {
break;
}
}
float2 prevOffset = uvOffset + deltaUV;
float nextDepth = height - currLayerDepth;
float prevDepth = 1.0 - ComputePerPixelHeightDisplacement(prevOffset, 0, ppdParam) -
currLayerDepth + layerDepth;
float2 parallaxUVs = lerp(uvOffset, prevOffset, nextDepth / (nextDepth - prevDepth));
return parallaxUVs;
}
float2 ParallaxRaymarchingDynamicOffset(float3 viewDir, PerPixelHeightDisplacementParam ppdParam,
float strength, float lod)
{
const float minLayers = 8.0;
const float maxLayers = 48.0;
float numLayers = lerp(maxLayers, minLayers, clamp(lod, 0, 1));
if (viewDir.z < 0.001) return 0;
float heightScale = _Parallax;
float refPlane = 0.5;
float layerDepth = 1.0 / numLayers;
float currLayerDepth = 0.0;
float2 totalDelta = viewDir.xy * heightScale / viewDir.z;
float2 deltaUV = totalDelta / numLayers;
// Shift the starting UVs forward so that the ray starts above the surface
float2 uvOffset = totalDelta * refPlane;
float height = 1.0 - ComputePerPixelHeightDisplacement(uvOffset, 0, ppdParam);
for (int i = 0; i < numLayers; i++) {
if (height < currLayerDepth) break;
currLayerDepth += layerDepth;
uvOffset -= deltaUV;
height = 1.0 - ComputePerPixelHeightDisplacement(uvOffset, 0, ppdParam);
}
float2 prevOffset = uvOffset + deltaUV;
float nextDepth = height - currLayerDepth;
float prevDepth = (1.0 - ComputePerPixelHeightDisplacement(prevOffset, 0, ppdParam)) -
(currLayerDepth - layerDepth);
float weight = nextDepth / (nextDepth - prevDepth);
float2 parallaxUVs = lerp(uvOffset, prevOffset, weight);
return parallaxUVs;
}
float GetParallaxSelfShadow(float3 lightDir, float2 uv, PerPixelHeightDisplacementParam ppdParam, float noise)
{
// lightDir.z is the cosine of the angle between the light and the tangent surface.
// If it's 0, we are at the horizon.
if (lightDir.z <= 0.0) return 0.0;
const int numSamples = 16;
float initialHeight = ComputePerPixelHeightDisplacement(0, 0, ppdParam);
// Scale the penumbra by the surface depth.
float shadowHardness = 1.0 / (_BumpShadowHardness);
float heightToTravel = 1.0 - initialHeight;
float2 uvStep = (lightDir.xy * _Parallax) / (lightDir.z * numSamples);
float stepHeight = heightToTravel / numSamples;
float2 currentOffset = uvStep * noise;
float currentRayHeight = initialHeight + (stepHeight * noise);
float shadowFactor = 1.0;
[unroll(numSamples)]
for(int i = 0; i < numSamples; i++)
{
float mipLOD = (float(i) / float(numSamples)) * 7.0;
float sampledHeight = ComputePerPixelHeightDisplacement(currentOffset, mipLOD, ppdParam);
if (sampledHeight > currentRayHeight)
{
float distanceAlongRay = (float)i / (float)numSamples;
float penetration = (sampledHeight - currentRayHeight) * (1.0 - distanceAlongRay);
shadowFactor = min(shadowFactor, saturate(1.0 - penetration * shadowHardness * numSamples));
}
if (shadowFactor <= 0.0) break;
currentOffset += uvStep;
currentRayHeight += stepHeight;
}
return shadowFactor;
}
#endif // SERVICE_PARALLAX_INCLUDED

View File

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

View File

@ -0,0 +1,158 @@
#ifndef COMMON_SH_INCLUDED
#define COMMON_SH_INCLUDED
/* http://www.geomerics.com/wp-content/uploads/2015/08/CEDEC_Geomerics_ReconstructingDiffuseLighting1.pdf */
half shEvaluateDiffuseL1Geomerics_local(half L0, half3 L1, float3 n)
{
// average energy
// Add max0 to fix an issue caused by probes having a negative ambient component (???)
// I'm not sure how normal that is but this can't handle it
half R0 = max(L0, 0);
// avg direction of incoming light
half3 R1 = 0.5f * L1;
// directional brightness
half lenR1 = length(R1);
// linear angle between normal and direction 0-1
half q = dot(normalize(R1), n) * 0.5 + 0.5;
q = saturate(q); // Thanks to ScruffyRuffles for the bug identity.
// power for q
// lerps from 1 (linear) to 3 (cubic) based on directionality
half p = 1.0f + 2.0f * lenR1 / R0;
// dynamic range constant
// should vary between 4 (highly directional) and 0 (ambient)
half a = (1.0f - lenR1 / R0) / (1.0f + lenR1 / R0);
return R0 * (a + (1.0f - a) * (p + 1.0f) * pow(q, p));
}
/*
// Paper: ZH3: Quadratic Zonal Harmonics, i3D 2024. https://torust.me/ZH3.pdf
// Code based on paper and demo https://www.shadertoy.com/view/Xfj3RK
// https://gist.github.com/pema99/f735ca33d1299abe0e143ee94fc61e73
*/
// L1 radiance = L1 irradiance * PI / Y_1 / AHat_1
// PI / (sqrt(3 / PI) / 2) / ((2 * PI) / 3) = sqrt(3 * PI)
const static float L0IrradianceToRadiance = 2 * sqrt(UNITY_PI);
// L0 radiance = L0 irradiance * PI / Y_0 / AHat_0
// PI / (sqrt(1 / PI) / 2) / PI = 2 * sqrt(PI)
const static float L1IrradianceToRadiance = sqrt(3 * UNITY_PI);
const static float4 L0L1IrradianceToRadiance = float4(L0IrradianceToRadiance, L1IrradianceToRadiance, L1IrradianceToRadiance, L1IrradianceToRadiance);
half SHEvalLinearL0L1_ZH3Hallucinate(half4 sh, float3 normal)
{
float4 radiance = sh * L0L1IrradianceToRadiance;
float3 zonalAxis = float3(radiance.w, radiance.y, radiance.z);
float l1Length = length(zonalAxis);
zonalAxis /= l1Length;
float ratio = l1Length / radiance.x;
float zonalL2Coeff = radiance.x * ratio * (0.08 + 0.6 * ratio); // Curve-fit.
float fZ = dot(zonalAxis, normal);
float zhNormal = sqrt(5.0f / (16.0f * UNITY_PI)) * (3.0f * fZ * fZ - 1.0f);
float result = dot(sh, float4(1, float3(normal.y, normal.z, normal.x)));
result += 0.25f * zhNormal * zonalL2Coeff;
return result;
}
// Evaluate irradiance in direction normal from the linear SH sh,
// hallucinating the ZH3 coefficient and then using that and linear SH
// for reconstruction.
half3 SHEvalLinearL0L1_ZH3Hallucinate(float3 normal)
{
float3 shL0 = float3(unity_SHAr.w, unity_SHAg.w, unity_SHAb.w) +
float3(unity_SHBr.z, unity_SHBg.z, unity_SHBb.z) / 3.0;
float3 shL1_1 = float3(unity_SHAr.y, unity_SHAg.y, unity_SHAb.y);
float3 shL1_2 = float3(unity_SHAr.z, unity_SHAg.z, unity_SHAb.z);
float3 shL1_3 = float3(unity_SHAr.x, unity_SHAg.x, unity_SHAb.x);
float3 result = 0.0;
float4 a = float4(shL0.r, shL1_1.r, shL1_2.r, shL1_3.r);
float4 b = float4(shL0.g, shL1_1.g, shL1_2.g, shL1_3.g);
float4 c = float4(shL0.b, shL1_1.b, shL1_2.b, shL1_3.b);
result.r = SHEvalLinearL0L1_ZH3Hallucinate(a, normal);
result.g = SHEvalLinearL0L1_ZH3Hallucinate(b, normal);
result.b = SHEvalLinearL0L1_ZH3Hallucinate(c, normal);
return result;
}
float3 SHEvalLinearL0L1_ZH3Hallucinate(float3 normal, float3 L0,
float3 L1r, float3 L1g, float3 L1b)
{
float3 shL0 = L0;
float3 shL1_1 = float3(L1r.y, L1g.y, L1b.y);
float3 shL1_2 = float3(L1r.z, L1g.z, L1b.z);
float3 shL1_3 = float3(L1r.x, L1g.x, L1b.x);
float3 result = 0.0;
float4 a = float4(shL0.r, shL1_1.r, shL1_2.r, shL1_3.r);
float4 b = float4(shL0.g, shL1_1.g, shL1_2.g, shL1_3.g);
float4 c = float4(shL0.b, shL1_1.b, shL1_2.b, shL1_3.b);
result.r = SHEvalLinearL0L1_ZH3Hallucinate(a, normal);
result.g = SHEvalLinearL0L1_ZH3Hallucinate(b, normal);
result.b = SHEvalLinearL0L1_ZH3Hallucinate(c, normal);
return result;
}
// Evaluate irradiance in direction normal from the linear SH sh,
// computing a shared luminance axis from the linear components,
// hallucinating the ZH3 coefficients along that axis,
// and then using ZH3 and linear SH for reconstruction in the direction normal.
float3 SHEvalLinearL0L1_ZH3Hallucinate_LumAxis(float3 direction)
{
// Get linear SH coefficients from Unity shader uniforms (without L2 folded into L0)
float3 shL0 = float3(unity_SHAr.w, unity_SHAg.w, unity_SHAb.w) +
float3(unity_SHBr.z, unity_SHBg.z, unity_SHBb.z) / 3.0;
float3 shL1_1 = float3(unity_SHAr.y, unity_SHAg.y, unity_SHAb.y);
float3 shL1_2 = float3(unity_SHAr.z, unity_SHAg.z, unity_SHAb.z);
float3 shL1_3 = float3(unity_SHAr.x, unity_SHAg.x, unity_SHAb.x);
float3 sh[4] = { shL0, shL1_1, shL1_2, shL1_3 };
// Deconvolve irradiance -> radiance
float3 radianceSH[4];
for (int i = 0; i < 3; i++)
{
radianceSH[0][i] = sh[0][i] * L0IrradianceToRadiance;
radianceSH[1][i] = sh[1][i] * L1IrradianceToRadiance;
radianceSH[2][i] = sh[2][i] * L1IrradianceToRadiance;
radianceSH[3][i] = sh[3][i] * L1IrradianceToRadiance;
}
// Use the zonal axis from the luminance SH.
const float3 lumCoeffs = float3(0.2126f, 0.7152f, 0.0722f); // sRGB luminance.
float3 zonalAxis = normalize(float3(dot(radianceSH[3], lumCoeffs), dot(radianceSH[1], lumCoeffs), dot(radianceSH[2], lumCoeffs)));
float3 ratio = 0.0;
ratio.r = abs(dot(float3(radianceSH[3].r, radianceSH[1].r, radianceSH[2].r), zonalAxis));
ratio.g = abs(dot(float3(radianceSH[3].g, radianceSH[1].g, radianceSH[2].g), zonalAxis));
ratio.b = abs(dot(float3(radianceSH[3].b, radianceSH[1].b, radianceSH[2].b), zonalAxis));
ratio /= radianceSH[0];
float3 zonalL2Coeff = radianceSH[0] * (0.08f * ratio + 0.6f * ratio * ratio); // Curve-fit; Section 3.4.3
float fZ = dot(zonalAxis, direction);
float zhDir = sqrt(5.0f / (16.0f * UNITY_PI)) * (3.0f * fZ * fZ - 1.0f);
// Evaluate irradiance from linear SH in the given direction.
float4 shDir = float4(1, direction.y, direction.z, direction.x);
float3 result = float3(0.0, 0.0, 0.0);
result += sh[0] * shDir[0];
result += sh[1] * shDir[1];
result += sh[2] * shDir[2];
result += sh[3] * shDir[3];
// Add irradiance from the ZH3 term. zonalL2Coeff is the ZH3 coefficient for a radiance signal, so we need to
// multiply by 1/4 (the L2 zonal scale for a normalized clamped cosine kernel) to evaluate irradiance.
result += 0.25f * zonalL2Coeff * zhDir;
return result;
}
#endif

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -0,0 +1,219 @@
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
Shader "Silent/Filamented"
{
Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
_GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0
[Enum(Metallic Alpha,0,Albedo Alpha,1)] _SmoothnessTextureChannel ("Smoothness texture channel", Float) = 0
[Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
_MetallicGlossMap("Metallic", 2D) = "white" {}
[ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
[ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0
_BumpScale("Scale", Float) = 1.0
[Normal] _BumpMap("Normal Map", 2D) = "bump" {}
_Parallax ("Height Scale", Range (0.005, 0.25)) = 0.02
_ParallaxMap ("Height Map", 2D) = "black" {}
_OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
_OcclusionMap("Occlusion", 2D) = "white" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
[Normal] _DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec ("UV Set for secondary textures", Float) = 0
// New settings
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 0.9
[Toggle(_NORMALMAP_SHADOW)]_NormalMapShadows("Normal Map Shadows", Range(0, 1)) = 0
_BumpShadowHeightScale("Height Scale", Range(0, 1)) = 0.2
_BumpShadowHardness("Shadow Hardness", Range(0, 100)) = 50
_specularAntiAliasingVariance("Specular AA Variance", Range(0, 1)) = 0.15
_specularAntiAliasingThreshold("Specular AA Threshold", Range(0, 1)) = 0.25
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[Toggle(_BAKERY_VERTEXLM)]_BakeryVertexLM ("Use Bakery Vertex Lightmaps", Range(0, 1)) = 0
_RNM0("RNM0", 2D) = "black" {}
_RNM1("RNM1", 2D) = "black" {}
_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[ToggleUI]_AlphaToMaskMode("Alpha to Coverage", Int) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _Mode ("__mode", Float) = 0.0
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
}
CGINCLUDE
// OcclusionMap is always defined
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// Use specular AA controls
#define USE_GEOMETRIC_SPECULAR_AA
// _DFG is present
#define USE_DFG_LUT
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
Cull [_CullMode]
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature_local _METALLICGLOSSMAP
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _BAKERY_VERTEXLM
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend [_SrcBlend] One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest LEqual
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _METALLICGLOSSMAP
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _METALLICGLOSSMAP
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _PARALLAXMAP
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
// Meta not implemented
UsePass "Standard/META"
}
FallBack "VertexLit"
CustomEditor "SilentTools.FilamentedStandardShaderGUI"
}

View File

@ -0,0 +1,22 @@
fileFormatVersion: 2
guid: 9829e18681954944a8b25de9b080a0b6
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _MetallicGlossMap: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _ParallaxMap: {instanceID: 0}
- _OcclusionMap: {instanceID: 0}
- _EmissionMap: {instanceID: 0}
- _DetailMask: {instanceID: 0}
- _DetailAlbedoMap: {instanceID: 0}
- _DetailNormalMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,221 @@
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
Shader "Silent/Filamented (Cloth setup)"
{
Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
_GlossMapScale("Smoothness Factor", Range(0.0, 1.0)) = 1.0
[Enum(Specular Alpha,0,Albedo Alpha,1)] _SmoothnessTextureChannel ("Smoothness texture channel", Float) = 0
_SpecColor("Sheen", Color) = (0.2,0.2,0.2)
_SpecGlossMap("Sheen Map", 2D) = "white" {}
[ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
[ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0
_BumpScale("Scale", Float) = 1.0
[Normal] _BumpMap("Normal Map", 2D) = "bump" {}
_Parallax ("Height Scale", Range (0.005, 0.25)) = 0.02
_ParallaxMap ("Height Map", 2D) = "black" {}
_OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
_OcclusionMap("Occlusion", 2D) = "white" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
[Normal] _DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec ("UV Set for secondary textures", Float) = 0
// New settings
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 0.9
[Toggle(_NORMALMAP_SHADOW)]_NormalMapShadows("Normal Map Shadows", Range(0, 1)) = 0
_BumpShadowHeightScale("Height Scale", Range(0, 1)) = 0.2
_BumpShadowHardness("Shadow Hardness", Range(0, 100)) = 50
_specularAntiAliasingVariance("Specular AA Variance", Range(0, 1)) = 0.15
_specularAntiAliasingThreshold("Specular AA Threshold", Range(0, 1)) = 0.25
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[Toggle(_BAKERY_VERTEXLM)]_BakeryVertexLM ("Use Bakery Vertex Lightmaps", Range(0, 1)) = 0
_RNM0("RNM0", 2D) = "black" {}
_RNM1("RNM1", 2D) = "black" {}
_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[ToggleUI]_AlphaToMaskMode("Alpha to Coverage", Int) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
[HideInInspector] _ShaderType_Cloth("__cloth", Float) = 1.0
// Blending state
[HideInInspector] _Mode ("__mode", Float) = 0.0
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
}
CGINCLUDE
#define SHADING_MODEL_CLOTH
#define MATERIAL_HAS_SHEEN_COLOR
//#define MATERIAL_HAS_SUBSURFACE_COLOR
// OcclusionMap is always defined
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// Use specular AA controls
#define USE_GEOMETRIC_SPECULAR_AA
// _DFG is present
#define USE_DFG_LUT
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
Cull [_CullMode]
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _BAKERY_VERTEXLM
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend [_SrcBlend] One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest LEqual
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _PARALLAXMAP
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
// Meta not implemented
UsePass "Standard/META"
}
FallBack "VertexLit"
CustomEditor "SilentTools.FilamentedStandardShaderGUI"
}

View File

@ -0,0 +1,22 @@
fileFormatVersion: 2
guid: deca4036fd687004ca874acb20f3fd5f
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _SpecGlossMap: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _ParallaxMap: {instanceID: 0}
- _OcclusionMap: {instanceID: 0}
- _EmissionMap: {instanceID: 0}
- _DetailMask: {instanceID: 0}
- _DetailAlbedoMap: {instanceID: 0}
- _DetailNormalMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,219 @@
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
Shader "Silent/Filamented (Roughness setup)"
{
Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Roughness", Range(0.0, 1.0)) = 0.5
_SpecGlossMap("Roughness Map", 2D) = "white" {}
[Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
_MetallicGlossMap("Metallic", 2D) = "white" {}
[ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
[ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0
_BumpScale("Scale", Float) = 1.0
[Normal] _BumpMap("Normal Map", 2D) = "bump" {}
_Parallax ("Height Scale", Range (0.005, 0.25)) = 0.02
_ParallaxMap ("Height Map", 2D) = "black" {}
_OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
_OcclusionMap("Occlusion", 2D) = "white" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
[Normal] _DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec ("UV Set for secondary textures", Float) = 0
// New settings
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 0.9
[Toggle(_NORMALMAP_SHADOW)]_NormalMapShadows("Normal Map Shadows", Range(0, 1)) = 0
_BumpShadowHeightScale("Height Scale", Range(0, 1)) = 0.2
_BumpShadowHardness("Shadow Hardness", Range(0, 100)) = 50
_specularAntiAliasingVariance("Specular AA Variance", Range(0, 1)) = 0.15
_specularAntiAliasingThreshold("Specular AA Threshold", Range(0, 1)) = 0.25
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[Toggle(_BAKERY_VERTEXLM)]_BakeryVertexLM ("Use Bakery Vertex Lightmaps", Range(0, 1)) = 0
_RNM0("RNM0", 2D) = "black" {}
_RNM1("RNM1", 2D) = "black" {}
_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[ToggleUI]_AlphaToMaskMode("Alpha to Coverage", Int) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _Mode ("__mode", Float) = 0.0
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
}
CGINCLUDE
#define SHADING_MODEL_METALLIC_ROUGHNESS
// OcclusionMap is always defined
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// Use specular AA controls
#define USE_GEOMETRIC_SPECULAR_AA
// _DFG is present
#define USE_DFG_LUT
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
Cull [_CullMode]
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature_local _METALLICGLOSSMAP
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _BAKERY_VERTEXLM
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend [_SrcBlend] One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest LEqual
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _METALLICGLOSSMAP
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _METALLICGLOSSMAP
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _PARALLAXMAP
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
// Meta not implemented
UsePass "Standard/META"
}
FallBack "VertexLit"
CustomEditor "SilentTools.FilamentedStandardShaderGUI"
}

View File

@ -0,0 +1,23 @@
fileFormatVersion: 2
guid: 075dbc3edcecd8747919086245d79325
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _SpecGlossMap: {instanceID: 0}
- _MetallicGlossMap: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _ParallaxMap: {instanceID: 0}
- _OcclusionMap: {instanceID: 0}
- _EmissionMap: {instanceID: 0}
- _DetailMask: {instanceID: 0}
- _DetailAlbedoMap: {instanceID: 0}
- _DetailNormalMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,218 @@
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
Shader "Silent/Filamented (Specular setup)"
{
Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
_GlossMapScale("Smoothness Factor", Range(0.0, 1.0)) = 1.0
[Enum(Specular Alpha,0,Albedo Alpha,1)] _SmoothnessTextureChannel ("Smoothness texture channel", Float) = 0
_SpecColor("Specular", Color) = (0.2,0.2,0.2)
_SpecGlossMap("Specular", 2D) = "white" {}
[ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
[ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0
_BumpScale("Scale", Float) = 1.0
[Normal] _BumpMap("Normal Map", 2D) = "bump" {}
_Parallax ("Height Scale", Range (0.005, 0.25)) = 0.02
_ParallaxMap ("Height Map", 2D) = "black" {}
_OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
_OcclusionMap("Occlusion", 2D) = "white" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
[Normal] _DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec ("UV Set for secondary textures", Float) = 0
// New settings
_ExposureOcclusion("Lightmap Occlusion Sensitivity", Range(0, 1)) = 0.2
[Toggle(_LIGHTMAPSPECULAR)]_LightmapSpecular("Lightmap Specular", Range(0, 1)) = 1
_LightmapSpecularMaxSmoothness("Lightmap Specular Max Smoothness", Range(0, 1)) = 0.9
[Toggle(_NORMALMAP_SHADOW)]_NormalMapShadows("Normal Map Shadows", Range(0, 1)) = 0
_BumpShadowHeightScale("Height Scale", Range(0, 1)) = 0.2
_BumpShadowHardness("Shadow Hardness", Range(0, 100)) = 50
_specularAntiAliasingVariance("Specular AA Variance", Range(0, 1)) = 0.15
_specularAntiAliasingThreshold("Specular AA Threshold", Range(0, 1)) = 0.25
[KeywordEnum(None, SH, RNM, MonoSH)] _Bakery ("Bakery Mode", Int) = 0
[Toggle(_BAKERY_VERTEXLM)]_BakeryVertexLM ("Use Bakery Vertex Lightmaps", Range(0, 1)) = 0
_RNM0("RNM0", 2D) = "black" {}
_RNM1("RNM1", 2D) = "black" {}
_RNM2("RNM2", 2D) = "black" {}
[Toggle(_LTCGI)] _LTCGI ("LTCGI", Int) = 0
[Toggle(_VRCLV)] _VRCLV ("VRC Light Volumes", Int) = 0
[IfDef(_VRCLV)] _VRCLVSurfaceBias("Light Volume Surface Bias", Range(0, 0.5)) = 0.05
[Enum(UnityEngine.Rendering.CullMode)]_CullMode("Cull Mode", Int) = 2
[ToggleUI]_AlphaToMaskMode("Alpha to Coverage", Int) = 0
[NonModifiableTextureData][HideInInspector] _DFG("DFG", 2D) = "white" {}
// Blending state
[HideInInspector] _Mode ("__mode", Float) = 0.0
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
}
CGINCLUDE
#define SHADING_MODEL_SPECULAR_GLOSSINESS
// OcclusionMap is always defined
#define MATERIAL_HAS_AMBIENT_OCCLUSION
// Use specular AA controls
#define USE_GEOMETRIC_SPECULAR_AA
// _DFG is present
#define USE_DFG_LUT
ENDCG
SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" "LTCGI" = "_LTCGI" }
LOD 300
Cull [_CullMode]
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _GLOSSYREFLECTIONS_OFF
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _LIGHTMAPSPECULAR
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma shader_feature_local _ _BAKERY_RNM _BAKERY_SH _BAKERY_MONOSH
#pragma shader_feature_local _BAKERY_VERTEXLM
#pragma shader_feature_local _LTCGI
#pragma shader_feature_local _VRCLV
#pragma multi_compile_fwdbase
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertBase
#pragma fragment fragBase
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Additive forward pass (one light per pass)
Pass
{
Name "FORWARD_DELTA"
Tags { "LightMode" = "ForwardAdd" }
Blend [_SrcBlend] One
Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest LEqual
AlphaToMask [_AlphaToMaskMode]
CGPROGRAM
#pragma target 4.0
// -------------------------------------
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature_local _DETAIL_MULX2
#pragma shader_feature_local _PARALLAXMAP
#pragma shader_feature_local _NORMALMAP_SHADOW
#pragma multi_compile_fwdadd_fullshadows
#pragma multi_compile_fog
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertAdd
#pragma fragment fragAdd
#include "UnityStandardCoreForward.cginc"
ENDCG
}
// ------------------------------------------------------------------
// Shadow rendering pass
Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature_local _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature_local _SPECGLOSSMAP
#pragma shader_feature_local _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature_local _PARALLAXMAP
#pragma multi_compile_shadowcaster
#pragma multi_compile_instancing
// Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
//#pragma multi_compile _ LOD_FADE_CROSSFADE
#pragma vertex vertShadowCaster
#pragma fragment fragShadowCaster
#include "UnityStandardShadow.cginc"
ENDCG
}
// Deferred not implemented
UsePass "Standard/DEFERRED"
// Meta not implemented
UsePass "Standard/META"
}
FallBack "VertexLit"
CustomEditor "SilentTools.FilamentedStandardShaderGUI"
}

View File

@ -0,0 +1,22 @@
fileFormatVersion: 2
guid: d1e71c1f97670b843a43924d87ceb04b
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _SpecGlossMap: {instanceID: 0}
- _BumpMap: {instanceID: 0}
- _ParallaxMap: {instanceID: 0}
- _OcclusionMap: {instanceID: 0}
- _EmissionMap: {instanceID: 0}
- _DetailMask: {instanceID: 0}
- _DetailAlbedoMap: {instanceID: 0}
- _DetailNormalMap: {instanceID: 0}
- _RNM0: {instanceID: 0}
- _RNM1: {instanceID: 0}
- _RNM2: {instanceID: 0}
nonModifiableTextures:
- _DFG: {fileID: 2800000, guid: b6b1f1fa6be1ce54f8bcd5428c160a28, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,207 @@
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
#ifndef UNITY_GLOBAL_ILLUMINATION_INCLUDED
#define UNITY_GLOBAL_ILLUMINATION_INCLUDED
// Functions sampling light environment data (lightmaps, light probes, reflection probes), which is then returned as the UnityGI struct.
#include "UnityImageBasedLighting.cginc"
#include "UnityStandardUtils.cginc"
#include "UnityShadowLibrary.cginc"
inline half3 DecodeDirectionalSpecularLightmap (half3 color, half4 dirTex, half3 normalWorld, bool isRealtimeLightmap, fixed4 realtimeNormalTex, out UnityLight o_light)
{
o_light.color = color;
o_light.dir = dirTex.xyz * 2 - 1;
o_light.ndotl = 0; // Not use;
// The length of the direction vector is the light's "directionality", i.e. 1 for all light coming from this direction,
// lower values for more spread out, ambient light.
half directionality = max(0.001, length(o_light.dir));
o_light.dir /= directionality;
#ifdef DYNAMICLIGHTMAP_ON
if (isRealtimeLightmap)
{
// Realtime directional lightmaps' intensity needs to be divided by N.L
// to get the incoming light intensity. Baked directional lightmaps are already
// output like that (including the max() to prevent div by zero).
half3 realtimeNormal = realtimeNormalTex.xyz * 2 - 1;
o_light.color /= max(0.125, dot(realtimeNormal, o_light.dir));
}
#endif
// Split light into the directional and ambient parts, according to the directionality factor.
half3 ambient = o_light.color * (1 - directionality);
o_light.color = o_light.color * directionality;
// Technically this is incorrect, but helps hide jagged light edge at the object silhouettes and
// makes normalmaps show up.
ambient *= saturate(dot(normalWorld, o_light.dir));
return ambient;
}
inline void ResetUnityLight(out UnityLight outLight)
{
outLight.color = half3(0, 0, 0);
outLight.dir = half3(0, 1, 0); // Irrelevant direction, just not null
outLight.ndotl = 0; // Not used
}
inline half3 SubtractMainLightWithRealtimeAttenuationFromLightmap (half3 lightmap, half attenuation, half4 bakedColorTex, half3 normalWorld)
{
// Let's try to make realtime shadows work on a surface, which already contains
// baked lighting and shadowing from the main sun light.
half3 shadowColor = unity_ShadowColor.rgb;
half shadowStrength = _LightShadowData.x;
// Summary:
// 1) Calculate possible value in the shadow by subtracting estimated light contribution from the places occluded by realtime shadow:
// a) preserves other baked lights and light bounces
// b) eliminates shadows on the geometry facing away from the light
// 2) Clamp against user defined ShadowColor.
// 3) Pick original lightmap value, if it is the darkest one.
// 1) Gives good estimate of illumination as if light would've been shadowed during the bake.
// Preserves bounce and other baked lights
// No shadows on the geometry facing away from the light
half ndotl = LambertTerm (normalWorld, _WorldSpaceLightPos0.xyz);
half3 estimatedLightContributionMaskedByInverseOfShadow = ndotl * (1- attenuation) * _LightColor0.rgb;
half3 subtractedLightmap = lightmap - estimatedLightContributionMaskedByInverseOfShadow;
// 2) Allows user to define overall ambient of the scene and control situation when realtime shadow becomes too dark.
half3 realtimeShadow = max(subtractedLightmap, shadowColor);
realtimeShadow = lerp(realtimeShadow, lightmap, shadowStrength);
// 3) Pick darkest color
return min(lightmap, realtimeShadow);
}
inline void ResetUnityGI(out UnityGI outGI)
{
ResetUnityLight(outGI.light);
outGI.indirect.diffuse = 0;
outGI.indirect.specular = 0;
}
inline UnityGI UnityGI_Base(UnityGIInput data, inout half occlusion, half3 normalWorld)
{
UnityGI o_gi;
ResetUnityGI(o_gi);
// Base pass with Lightmap support is responsible for handling ShadowMask / blending here for performance reason
#if defined(HANDLE_SHADOWS_BLENDING_IN_GI)
half bakedAtten = UnitySampleBakedOcclusion(data.lightmapUV.xy, data.worldPos);
float zDist = dot(_WorldSpaceCameraPos - data.worldPos, UNITY_MATRIX_V[2].xyz);
float fadeDist = UnityComputeShadowFadeDistance(data.worldPos, zDist);
data.atten = UnityMixRealtimeAndBakedShadows(data.atten, bakedAtten, UnityComputeShadowFade(fadeDist));
#endif
o_gi.light = data.light;
o_gi.light.color *= data.atten;
#if UNITY_SHOULD_SAMPLE_SH
o_gi.indirect.diffuse = ShadeSHPerPixel(normalWorld, data.ambient, data.worldPos);
#endif
#if defined(LIGHTMAP_ON)
// Baked lightmaps
half4 bakedColorTex = UNITY_SAMPLE_TEX2D(unity_Lightmap, data.lightmapUV.xy);
half3 bakedColor = DecodeLightmap(bakedColorTex);
// Derive specular occlusion
half bakedOcclusion = saturate(dot(bakedColor * 3.0, 1.0));
occlusion *= bakedOcclusion;
#ifdef DIRLIGHTMAP_COMBINED
fixed4 bakedDirTex = UNITY_SAMPLE_TEX2D_SAMPLER (unity_LightmapInd, unity_Lightmap, data.lightmapUV.xy);
o_gi.indirect.diffuse += DecodeDirectionalLightmap (bakedColor, bakedDirTex, normalWorld);
#if defined(LIGHTMAP_SHADOW_MIXING) && !defined(SHADOWS_SHADOWMASK) && defined(SHADOWS_SCREEN)
ResetUnityLight(o_gi.light);
o_gi.indirect.diffuse = SubtractMainLightWithRealtimeAttenuationFromLightmap (o_gi.indirect.diffuse, data.atten, bakedColorTex, normalWorld);
#endif
#else // not directional lightmap
o_gi.indirect.diffuse += bakedColor;
#if defined(LIGHTMAP_SHADOW_MIXING) && !defined(SHADOWS_SHADOWMASK) && defined(SHADOWS_SCREEN)
ResetUnityLight(o_gi.light);
o_gi.indirect.diffuse = SubtractMainLightWithRealtimeAttenuationFromLightmap(o_gi.indirect.diffuse, data.atten, bakedColorTex, normalWorld);
#endif
#endif
#endif
#ifdef DYNAMICLIGHTMAP_ON
// Dynamic lightmaps
fixed4 realtimeColorTex = UNITY_SAMPLE_TEX2D(unity_DynamicLightmap, data.lightmapUV.zw);
half3 realtimeColor = DecodeRealtimeLightmap (realtimeColorTex);
#ifdef DIRLIGHTMAP_COMBINED
half4 realtimeDirTex = UNITY_SAMPLE_TEX2D_SAMPLER(unity_DynamicDirectionality, unity_DynamicLightmap, data.lightmapUV.zw);
o_gi.indirect.diffuse += DecodeDirectionalLightmap (realtimeColor, realtimeDirTex, normalWorld);
#else
o_gi.indirect.diffuse += realtimeColor;
#endif
#endif
o_gi.indirect.diffuse *= occlusion;
return o_gi;
}
inline half3 UnityGI_IndirectSpecular(UnityGIInput data, half occlusion, Unity_GlossyEnvironmentData glossIn)
{
half3 specular;
#ifdef UNITY_SPECCUBE_BOX_PROJECTION
// we will tweak reflUVW in glossIn directly (as we pass it to Unity_GlossyEnvironment twice for probe0 and probe1), so keep original to pass into BoxProjectedCubemapDirection
half3 originalReflUVW = glossIn.reflUVW;
glossIn.reflUVW = BoxProjectedCubemapDirection (originalReflUVW, data.worldPos, data.probePosition[0], data.boxMin[0], data.boxMax[0]);
#endif
#ifdef _GLOSSYREFLECTIONS_OFF
specular = unity_IndirectSpecColor.rgb;
#else
half3 env0 = Unity_GlossyEnvironment (UNITY_PASS_TEXCUBE(unity_SpecCube0), data.probeHDR[0], glossIn);
#ifdef UNITY_SPECCUBE_BLENDING
const float kBlendFactor = 0.99999;
float blendLerp = data.boxMin[0].w;
UNITY_BRANCH
if (blendLerp < kBlendFactor)
{
#ifdef UNITY_SPECCUBE_BOX_PROJECTION
glossIn.reflUVW = BoxProjectedCubemapDirection (originalReflUVW, data.worldPos, data.probePosition[1], data.boxMin[1], data.boxMax[1]);
#endif
half3 env1 = Unity_GlossyEnvironment (UNITY_PASS_TEXCUBE_SAMPLER(unity_SpecCube1,unity_SpecCube0), data.probeHDR[1], glossIn);
specular = lerp(env1, env0, blendLerp);
}
else
{
specular = env0;
}
#else
specular = env0;
#endif
#endif
return specular * occlusion;
}
inline UnityGI UnityGlobalIllumination (UnityGIInput data, half occlusion, half3 normalWorld)
{
return UnityGI_Base(data, occlusion, normalWorld);
}
inline UnityGI UnityGlobalIllumination (UnityGIInput data, half occlusion, half3 normalWorld, Unity_GlossyEnvironmentData glossIn)
{
UnityGI o_gi = UnityGI_Base(data, occlusion, normalWorld);
o_gi.indirect.specular = UnityGI_IndirectSpecular(data, occlusion, glossIn);
return o_gi;
}
#endif

View File

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

View File

@ -0,0 +1,72 @@
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
#ifndef UNITY_IMAGE_BASED_LIGHTING_INCLUDED
#define UNITY_IMAGE_BASED_LIGHTING_INCLUDED
#include "UnityStandardUtils.cginc"
// ----------------------------------------------------------------------------
// GlossyEnvironment - Function to integrate the specular lighting with default sky or reflection probes
// ----------------------------------------------------------------------------
struct Unity_GlossyEnvironmentData
{
// - Deferred case have one cubemap
// - Forward case can have two blended cubemap (unusual should be deprecated).
// Surface properties use for cubemap integration
half roughness; // CAUTION: This is perceptualRoughness but because of compatibility this name can't be change :(
half3 reflUVW;
};
// ----------------------------------------------------------------------------
Unity_GlossyEnvironmentData UnityGlossyEnvironmentSetup(half Smoothness, half3 worldViewDir, half3 Normal, half3 fresnel0)
{
Unity_GlossyEnvironmentData g;
g.roughness /* perceptualRoughness */ = SmoothnessToPerceptualRoughness(Smoothness);
g.reflUVW = reflect(-worldViewDir, Normal);
return g;
}
// ----------------------------------------------------------------------------
half perceptualRoughnessToMipmapLevel(half perceptualRoughness)
{
return perceptualRoughness * UNITY_SPECCUBE_LOD_STEPS;
}
// ----------------------------------------------------------------------------
half mipmapLevelToPerceptualRoughness(half mipmapLevel)
{
return mipmapLevel / UNITY_SPECCUBE_LOD_STEPS;
}
// ----------------------------------------------------------------------------
half3 Unity_GlossyEnvironment (UNITY_ARGS_TEXCUBE(tex), half4 hdr, Unity_GlossyEnvironmentData glossIn)
{
half perceptualRoughness = glossIn.roughness /* perceptualRoughness */ ;
// TODO: CAUTION: remap from Morten may work only with offline convolution, see impact with runtime convolution!
// For now disabled
#if 0
float m = PerceptualRoughnessToRoughness(perceptualRoughness); // m is the real roughness parameter
const float fEps = 1.192092896e-07F; // smallest such that 1.0+FLT_EPSILON != 1.0 (+1e-4h is NOT good here. is visibly very wrong)
float n = (2.0/max(fEps, m*m))-2.0; // remap to spec power. See eq. 21 in --> https://dl.dropboxusercontent.com/u/55891920/papers/mm_brdf.pdf
n /= 4; // remap from n_dot_h formulatino to n_dot_r. See section "Pre-convolved Cube Maps vs Path Tracers" --> https://s3.amazonaws.com/docs.knaldtech.com/knald/1.0.0/lys_power_drops.html
perceptualRoughness = pow( 2/(n+2), 0.25); // remap back to square root of real roughness (0.25 include both the sqrt root of the conversion and sqrt for going from roughness to perceptualRoughness)
#else
// MM: came up with a surprisingly close approximation to what the #if 0'ed out code above does.
perceptualRoughness = perceptualRoughness*(1.7 - 0.7*perceptualRoughness);
#endif
half mip = perceptualRoughnessToMipmapLevel(perceptualRoughness);
half3 R = glossIn.reflUVW;
half4 rgbm = UNITY_SAMPLE_TEXCUBE_LOD(tex, R, mip);
return DecodeHDR(rgbm, hdr);
}
#endif // UNITY_IMAGE_BASED_LIGHTING_INCLUDED

View File

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

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