Files
Perekyp-2.0/Assets/Shaders/CarPaint_Rust.shader
2026-11-19 23:24:44 +03:00

266 lines
11 KiB
Plaintext

Shader "Universal Render Pipeline/CarPaint_Rust"
{
Properties
{
_BaseColor("Цвет кузова (Base Color)", Color) = (0.1, 0.1, 0.55, 1.0)
_PaintSmoothness("Глянец лака (Smoothness)", Range(0.0, 1.0)) = 0.88
_NoiseTexture("Текстура шума (Noise Texture)", 2D) = "white" {}
_NoiseScale("Масштаб шума (Noise Scale)", Float) = 4.0
_RustTexture("Текстура ржавчины (Rust Texture)", 2D) = "white" {}
_RustAmount("Текущая ржавчина (Rust Amount)", Range(0.0, 1.0)) = 0.0
_RustInitial("Исходное повреждение (Rust Initial)", Range(0.0, 1.0)) = 0.0
_PuttyProgress("Шпаклевка (Putty Progress)", Range(0.0, 1.0)) = 0.0
_SandProgress("Шлифовка (Sand Progress)", Range(0.0, 1.0)) = 0.0
_PaintProgress("Покраска (Paint Progress)", Range(0.0, 1.0)) = 0.0
_EdgeRustBoost("Усиление ржавчины на торцах", Range(0.0, 2.0)) = 1.0
}
SubShader
{
Tags
{
"RenderType" = "Opaque"
"RenderPipeline" = "UniversalPipeline"
"Queue" = "Geometry"
}
LOD 300
HLSLINCLUDE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _BaseColor;
float4 _NoiseTexture_ST;
float4 _RustTexture_ST;
float _PaintSmoothness;
float _NoiseScale;
float _RustAmount;
float _RustInitial;
float _PuttyProgress;
float _SandProgress;
float _PaintProgress;
float _EdgeRustBoost;
CBUFFER_END
TEXTURE2D(_NoiseTexture);
SAMPLER(sampler_NoiseTexture);
TEXTURE2D(_RustTexture);
SAMPLER(sampler_RustTexture);
void CalculateCarSurface(
float2 uv,
float edgeFactor,
float3 posOS,
out float3 outAlbedo,
out float outMetallic,
out float outSmoothness)
{
const float e = 0.035;
const float3 bareMetal = float3(0.58, 0.59, 0.62);
const float3 puttyRaw = float3(0.65, 0.60, 0.50);
const float3 puttySanded = float3(0.76, 0.73, 0.68);
// 1. Если деталь полностью целая — возвращаем зеркально чистый заводской лак
if (_RustInitial <= 0.001)
{
outAlbedo = _BaseColor.rgb;
outMetallic = 0.0;
outSmoothness = _PaintSmoothness;
return;
}
// 2. Семплируем шум и реальную фототекстуру ржавчины
float rawNoise = SAMPLE_TEXTURE2D(_NoiseTexture, sampler_NoiseTexture, uv * _NoiseScale).r;
float3 sampledRust = SAMPLE_TEXTURE2D(_RustTexture, sampler_RustTexture, uv * 3.5).rgb;
float3 rustToned = lerp(float3(0.42, 0.22, 0.12), sampledRust, 0.65);
// 3. Формируем комбинированный шум с концентрацией на торцах деталей
// Торцы имеют edgeFactor ~ 1.0 (нижняя кромка двери, арка крыла, край капота/багажника)
float edge = saturate(edgeFactor * _EdgeRustBoost);
// На торцах шум сдвигается вверх: ржавчина проявляется при минимальном RustAmount
float N = lerp(rawNoise * 0.48, rawNoise * 0.42 + 0.58, edge);
N = saturate(N);
// 4. Очаги повреждения
float zone = smoothstep(1.0 - _RustInitial, 1.0 - _RustInitial + e, N);
// 5. Шпаклёвка (наносится от центра к краям зоны повреждения)
float fillEdge = 1.0 - saturate(_PuttyProgress) * (_RustInitial + e);
float puttyMask = smoothstep(fillEdge + e, fillEdge, N) * step(0.001, _PuttyProgress);
if (_PuttyProgress >= 0.98) puttyMask = 1.0;
float sand = saturate(_SandProgress);
float3 underColor = lerp(bareMetal, lerp(puttyRaw, puttySanded, sand), puttyMask);
float underSmooth = lerp(0.45, lerp(0.08, 0.32, sand), puttyMask);
float underMetal = lerp(0.85, 0.0, puttyMask);
// 6. Нанесение новой краски (перекрывает зашлифованное место)
float paintEdge = (1.0 - _RustInitial) + saturate(_PaintProgress) * (_RustInitial + e);
float paintMask = (1.0 - smoothstep(paintEdge, paintEdge + e, N)) * step(0.001, _PaintProgress);
if (_PaintProgress >= 0.98) paintMask = 1.0;
float damageVisible = zone * (1.0 - paintMask);
// 7. Текущий видимый слой ржавчины
float rustMask = zone * smoothstep(1.0 - _RustAmount, 1.0 - _RustAmount + e, N) * step(0.001, _RustAmount);
// 8. Смешивание слоев
float3 col = lerp(_BaseColor.rgb, underColor, damageVisible);
float sm = lerp(_PaintSmoothness, underSmooth, damageVisible);
float met = lerp(0.0, underMetal, damageVisible);
// Поверх накладываем очаги коррозии с матовой шершавой фактурой
col = lerp(col, rustToned, rustMask);
sm = lerp(sm, 0.08, rustMask);
met = lerp(met, 0.0, rustMask);
outAlbedo = col;
outMetallic = met;
outSmoothness = sm;
}
ENDHLSL
// -------------------------------------------------------------
// Pass 1: Forward Lit (PBR освещение кузова)
// -------------------------------------------------------------
Pass
{
Name "ForwardLit"
Tags { "LightMode" = "UniversalForward" }
ZWrite On
ZTest LEqual
Cull Back
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS
#pragma multi_compile _ _SHADOWS_SOFT
#pragma multi_compile_fog
struct Attributes
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
float2 uv : TEXCOORD0;
float4 color : COLOR;
};
struct Varyings
{
float4 positionCS : SV_POSITION;
float2 uv : TEXCOORD0;
float3 positionWS : TEXCOORD1;
float3 normalWS : TEXCOORD2;
float4 color : COLOR;
float3 positionOS : TEXCOORD3;
float fogFactor : TEXCOORD4;
};
Varyings vert(Attributes input)
{
Varyings output;
VertexPositionInputs vertexInputs = GetVertexPositionInputs(input.positionOS.xyz);
VertexNormalInputs normalInputs = GetVertexNormalInputs(input.normalOS, input.tangentOS);
output.positionCS = vertexInputs.positionCS;
output.positionWS = vertexInputs.positionWS;
output.positionOS = input.positionOS.xyz;
output.normalWS = normalInputs.normalWS;
output.uv = input.uv;
output.color = input.color;
output.fogFactor = ComputeFogFactor(output.positionCS.z);
return output;
}
half4 frag(Varyings input) : SV_Target
{
float3 albedo;
float metallic;
float smoothness;
// Передаем фактор торца из цвета вершины (R)
float edgeFactor = input.color.r;
CalculateCarSurface(input.uv, edgeFactor, input.positionOS, albedo, metallic, smoothness);
// Настройка физического шейдинга Universal RP
InputData inputData;
inputData.positionWS = input.positionWS;
inputData.normalWS = NormalizeNormalPerPixel(input.normalWS);
inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
inputData.shadowCoord = TransformWorldToShadowCoord(input.positionWS);
inputData.fogCoord = input.fogFactor;
inputData.vertexLighting = half3(0, 0, 0);
inputData.bakedGI = SampleSH(inputData.normalWS);
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
inputData.shadowMask = half4(1, 1, 1, 1);
SurfaceData surfaceData;
surfaceData.albedo = albedo;
surfaceData.metallic = metallic;
surfaceData.specular = half3(0.04, 0.04, 0.04);
surfaceData.smoothness = smoothness;
surfaceData.normalTS = half3(0, 0, 1);
surfaceData.emission = half3(0, 0, 0);
surfaceData.occlusion = 1.0;
surfaceData.alpha = 1.0;
surfaceData.clearCoatMask = (1.0 - metallic) * smoothness * step(0.6, smoothness);
surfaceData.clearCoatSmoothness = smoothness;
half4 color = UniversalFragmentPBR(inputData, surfaceData);
color.rgb = MixFog(color.rgb, input.fogFactor);
return color;
}
ENDHLSL
}
// -------------------------------------------------------------
// Pass 2: Shadow Caster (Тени от кузова и съемных деталей)
// -------------------------------------------------------------
Pass
{
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On
ZTest LEqual
ColorMask 0
Cull Back
HLSLPROGRAM
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "Packages/com.unity.render-pipelines.universal/Shaders/ShadowCasterPass.hlsl"
ENDHLSL
}
// -------------------------------------------------------------
// Pass 3: Depth Only
// -------------------------------------------------------------
Pass
{
Name "DepthOnly"
Tags { "LightMode" = "DepthOnly" }
ZWrite On
ColorMask R
Cull Back
HLSLPROGRAM
#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
#include "Packages/com.unity.render-pipelines.universal/Shaders/DepthOnlyPass.hlsl"
ENDHLSL
}
}
FallBack "Universal Render Pipeline/Lit"
}