Files
ichni_Creator_Studio/Assets/Shaders/Grid.shader

90 lines
3.2 KiB
Plaintext
Raw Normal View History

Shader "Custom/SimpleGrid"
2025-04-04 15:29:03 -04:00
{
Properties
{
_MainColor ("Sub Grid Color", Color) = (0.5, 0.5, 0.5, 0.2)
_AxisColor ("Major Grid Color", Color) = (0.8, 0.8, 0.8, 0.5)
_GridSpacing ("Grid Spacing", Float) = 1.0
_LineWidth ("Line Width", Range(0.001, 0.1)) = 0.02
_FadeDist ("Fade Distance", Float) = 100.0
2025-04-04 15:29:03 -04:00
}
SubShader
{
Tags { "RenderType"="Transparent" "Queue"="Transparent-1" } // -1 保证在普通物体后面
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
Cull Off
2025-04-04 15:29:03 -04:00
Pass
{
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes { float4 vertex : POSITION; };
struct Varyings { float4 position : SV_POSITION; float3 worldPos : TEXCOORD0; };
2025-04-04 15:29:03 -04:00
CBUFFER_START(UnityPerMaterial)
float4 _MainColor;
float4 _AxisColor;
float _GridSpacing;
float _LineWidth;
float _FadeDist;
2025-04-04 15:29:03 -04:00
CBUFFER_END
Varyings vert(Attributes IN)
{
Varyings OUT;
OUT.position = TransformObjectToHClip(IN.vertex);
OUT.worldPos = TransformObjectToWorld(IN.vertex).xyz;
return OUT;
}
// 优化的网格计算
float gridAlpha(float2 worldPos, float spacing, float width)
2025-04-04 15:29:03 -04:00
{
float2 coord = worldPos / spacing;
// fwidth 用于保持线条在屏幕上的像素宽度一致
float2 grid = abs(frac(coord - 0.5) - 0.5) / fwidth(coord);
float lineVal = min(grid.x, grid.y);
// 1.0 - smoothstep 提供抗锯齿
return 1.0 - smoothstep(width, width + 1.0, lineVal);
2025-04-04 15:29:03 -04:00
}
half4 frag(Varyings IN) : SV_Target
{
// 距离裁剪:太远直接 discard节省后续计算
float dist = distance(IN.worldPos, _WorldSpaceCameraPos);
if (dist > _FadeDist) discard;
2025-04-04 15:29:03 -04:00
float alphaFade = 1.0 - (dist / _FadeDist);
// 二次衰减让边缘更柔和
alphaFade *= alphaFade;
float2 pos = IN.worldPos.xz;
// 计算两层网格
float baseGrid = gridAlpha(pos, _GridSpacing, _LineWidth);
float largeGrid = gridAlpha(pos, _GridSpacing * 10.0, _LineWidth); // 10倍格
// 混合
float4 finalColor = _MainColor;
finalColor.a *= baseGrid;
// 叠加高亮网格
// 使用 max 避免 alpha 混合错误
finalColor = lerp(finalColor, _AxisColor, largeGrid);
finalColor.a = max(finalColor.a, _AxisColor.a * largeGrid);
2025-04-04 15:29:03 -04:00
finalColor.a *= alphaFade;
2025-04-04 15:29:03 -04:00
// 极低 Alpha 剔除
if (finalColor.a < 0.01) discard;
return finalColor;
2025-04-04 15:29:03 -04:00
}
ENDHLSL
}
}
}