# Cel-Shading, Shadow Ramps & Width-Compensated Outlines in Unity 6 URP

> Two-pass URP stylized cel shader combining main-light shadow-attenuated diffuse ramps, crisp specular/rim accents, and clip-space distance-compensated inverted-hull outlines.

- **Canonical page:** https://gamecrew.ai/techniques/unity/cel-shading-outlines
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Unity 6
- **Category:** shaders
- **Tags:** `toon`, `cel`, `outline`, `stylized`, `anime`, `npr`, `rim-light`, `ramp`, `shader`, `urp`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Built-in `Universal Render Pipeline/Lit` uses smooth Lambert/GGX falloff that can make low-poly procedural characters and props read like shiny plastic. Stylized games (*Hi-Fi Rush*, *Sable*, *Wind Waker*, *Guilty Gear*) achieve crisp illustration clarity through:
1. **Terminator Ramp with Shadow Attenuation**: Multiply half-Lambert or `dot(N, L)` with URP's realtime shadow attenuation (`GetMainLight(shadowCoord).shadowAttenuation`) *before* stepping through a 2-band or 3-band `smoothstep` terminator (`width` $\approx 0.03$ prevents pixel shimmering without blurring the cel edge).
2. **Colored Shadow Tint (Never Multiply by Black)**: Tinting the shadow band toward cool indigo/violet (`_ShadowTint`) while keeping sunlit surfaces warm preserves color vibrancy and avoids `VERY DARK` capture flags.
3. **Sun-Gated Rim Highlight**: Multiply Fresnel rim $(1 - \mathbf{N}\cdot\mathbf{V})^p$ by $\mathrm{saturate}(\mathbf{N}\cdot\mathbf{L} + 0.2)$ so rims highlight the sunlit silhouette instead of glowing unnaturally inside dark caves.
4. **Clip-Space Screen-Consistent Inverted Hull**: Extruding `Cull Front` vertices in clip space scaled by $\min(w, w_{\max})$ keeps silhouettes crisp close up without swallowing characters into black blobs at distance.

## Mathematical & Algorithmic Core

- **Shadowed Cel Band**:
  $$i = (\max(0, \mathbf{N}\cdot\mathbf{L})) \cdot a_{\text{shadow}}, \qquad b_1 = \mathrm{smoothstep}(\tau_1 - \epsilon, \tau_1 + \epsilon, i)$$
- **Clip-Space Outline Extrusion**: Transform normal to view/clip space $\mathbf{n}_{\text{clip}} = \mathbf{P}_{\text{proj}} (\mathbf{V} \mathbf{n}_w)$, normalize XY corrected by aspect ratio (`_ScaledScreenParams.x / _ScaledScreenParams.y`), and offset:
  $$\mathbf{p}_{\text{clip}}.xy \mathrel{+}= \mathbf{n}_{\text{ndc}} \cdot \frac{\text{widthPx}}{\text{screenHeight}} \cdot \min(\mathbf{p}_{\text{clip}}.w, w_{\text{cap}})$$

## Engine Implementation

### Two-Pass URP Cel + Outline Shader (`Assets/Game/Resources/Shaders/CelOutline.shader`)

URP executes both `UniversalForward` and `SRPDefaultUnlit` passes automatically in a single material with **zero custom `ScriptableRendererFeature` boilerplate** — plus `ShadowCaster` and `DepthOnly` passes so shadows and shoreline water depth work seamlessly.

```hlsl
Shader "Custom/CelOutline"
{
    Properties
    {
        _BaseMap ("Base Map", 2D) = "white" {}
        _BaseColor ("Base Color", Color) = (0.92, 0.42, 0.28, 1.0)
        _ShadowColor ("Shadow Tint", Color) = (0.38, 0.30, 0.52, 1.0)
        _RimColor ("Rim Color", Color) = (1.00, 0.90, 0.72, 0.55)
        _OutlineColor ("Outline Color", Color) = (0.10, 0.08, 0.14, 1.0)
        _CelParams ("Threshold, Feather, SpecSize, RimPower", Vector) = (0.15, 0.03, 0.985, 3.5)
        _OutlineParams ("Width Px, Max Distance Scale, ZBias, Unused", Vector) = (2.2, 12.0, 0.0005, 0.0)
    }
    SubShader
    {
        Tags { "RenderPipeline" = "UniversalPipeline" "RenderType" = "Opaque" "Queue" = "Geometry" }

        Pass
        {
            Name "CelForward"
            Tags { "LightMode" = "UniversalForward" }
            Cull Back
            ZWrite On

            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_instancing

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

            TEXTURE2D(_BaseMap);
            SAMPLER(sampler_BaseMap);

            CBUFFER_START(UnityPerMaterial)
                float4 _BaseMap_ST;
                half4 _BaseColor;
                half4 _ShadowColor;
                half4 _RimColor;
                half4 _OutlineColor;
                float4 _CelParams;
                float4 _OutlineParams;
            CBUFFER_END

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                float2 uv : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float3 positionWS : TEXCOORD0;
                float3 normalWS : TEXCOORD1;
                float2 uv : TEXCOORD2;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            Varyings vert(Attributes input)
            {
                Varyings o;
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_TRANSFER_INSTANCE_ID(input, o);
                VertexPositionInputs pos = GetVertexPositionInputs(input.positionOS.xyz);
                o.positionCS = pos.positionCS;
                o.positionWS = pos.positionWS;
                o.normalWS = TransformObjectToWorldNormal(input.normalOS);
                o.uv = TRANSFORM_TEX(input.uv, _BaseMap);
                return o;
            }

            half4 frag(Varyings input) : SV_Target
            {
                UNITY_SETUP_INSTANCE_ID(input);
                half4 albedo = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, input.uv) * _BaseColor;
                float3 N = normalize(input.normalWS);
                float3 V = normalize(GetCameraPositionWS() - input.positionWS);

                float4 shadowCoord = TransformWorldToShadowCoord(input.positionWS);
                Light mainLight = GetMainLight(shadowCoord);
                float3 L = normalize(mainLight.direction);

                float ndl = dot(N, L) * 0.5 + 0.5;
                float litSignal = ndl * lerp(0.35, 1.0, mainLight.shadowAttenuation);
                float band = smoothstep(_CelParams.x + 0.35 - _CelParams.y, _CelParams.x + 0.35 + _CelParams.y, litSignal);

                float3 ramp = lerp(_ShadowColor.rgb, mainLight.color, band);
                float3 H = normalize(L + V);
                float spec = smoothstep(_CelParams.z - 0.01, _CelParams.z + 0.01, saturate(dot(N, H))) * band * 0.35;

                float rim = pow(1.0 - saturate(dot(N, V)), _CelParams.w) * saturate(dot(N, L) + 0.25);
                float rimStep = smoothstep(0.38, 0.46, rim) * _RimColor.a;

                float3 addLight = 0.0;
                #ifdef _ADDITIONAL_LIGHTS
                uint count = GetAdditionalLightsCount();
                for (uint li = 0u; li < count; li++)
                {
                    Light al = GetAdditionalLight(li, input.positionWS);
                    float att = al.distanceAttenuation * al.shadowAttenuation;
                    float celAdd = smoothstep(0.15, 0.25, saturate(dot(N, al.direction)) * att);
                    addLight += al.color * celAdd * 0.65;
                }
                #endif

                float3 color = albedo.rgb * (ramp + addLight) + mainLight.color * spec + _RimColor.rgb * rimStep;
                return half4(color, 1.0);
            }
            ENDHLSL
        }

        Pass
        {
            Name "InvertedHullOutline"
            Tags { "LightMode" = "SRPDefaultUnlit" }
            Cull Front
            ZWrite On

            HLSLPROGRAM
            #pragma vertex vertOutline
            #pragma fragment fragOutline
            #pragma multi_compile_instancing

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            CBUFFER_START(UnityPerMaterial)
                float4 _BaseMap_ST;
                half4 _BaseColor;
                half4 _ShadowColor;
                half4 _RimColor;
                half4 _OutlineColor;
                float4 _CelParams;
                float4 _OutlineParams;
            CBUFFER_END

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
            };

            Varyings vertOutline(Attributes input)
            {
                Varyings o;
                UNITY_SETUP_INSTANCE_ID(input);
                float4 clipPos = TransformObjectToHClip(input.positionOS.xyz);
                float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
                float3 normalVS = TransformWorldToViewDir(normalWS, true);
                float2 clipNormal = normalize(TransformWViewToHClip(normalVS).xy + float2(1e-5, 1e-5));
                float aspect = _ScaledScreenParams.x / max(1.0, _ScaledScreenParams.y);
                clipNormal.x /= aspect;

                float distScale = min(max(0.5, clipPos.w), _OutlineParams.y);
                float width = (_OutlineParams.x / max(360.0, _ScaledScreenParams.y)) * distScale;
                clipPos.xy += clipNormal * width;
                clipPos.z -= _OutlineParams.z;
                o.positionCS = clipPos;
                return o;
            }

            half4 fragOutline(Varyings input) : SV_Target
            {
                return _OutlineColor;
            }
            ENDHLSL
        }

        UsePass "Universal Render Pipeline/Lit/ShadowCaster"
        UsePass "Universal Render Pipeline/Lit/DepthOnly"
    }
}
```

## Browser, Mobile & Software-Renderer Budgets

- **Hard-Edged Cubes**: Standard inverted-hull extrusion splits across unshared cube face normals unless vertices have smoothed normals (spheres, capsules, cylinders, imported organic models) or you bake averaged smooth normals into `TEXCOORD3` for sharp-edged procedural meshes.
- **SRP Batcher Identical `CBUFFER`**: Keep the exact same `UnityPerMaterial` layout across `CelForward` and `InvertedHullOutline` passes so URP's SRP Batcher batches every cel-shaded prop cleanly.
- **Outline Width on 390 px Phones**: Scaling by `_ScaledScreenParams.y` keeps a `2.2 px` outline crisp on both 1080p desktops and 390 px portrait phones.

## Verification Checklist

1. Verify `UsePass "Universal Render Pipeline/Lit/ShadowCaster"` casts ground shadows and `DepthOnly` registers in shoreline water depth.
2. Check `_ShadowColor` brightness ($\ge 0.25$ luminance) in `Captures/*.png` so shadowed sides remain readable and colorful.

## Official references

- Junya Christopher Motomura (GDC 2015 — Guilty Gear Xrd's Art Style: The X Factor Between 2D and 3D)
- Valve (SIGGRAPH 2007 — Illustrative Rendering in Team Fortress 2)
- Colin Barré-Brisebois & Marc Bouchard (URP Multi-Pass & Inverted Hull Outlines)
