# 4. Inverted Hull Outlines
Part of [[Stylized Toon and Outline Shading]]. Prev: [[3. Ramps Rim and Specular Bands]]. Next: [[5. Screen-Space Edge Outlines with Full Screen Pass]].
> [!warning] Code not compiled
> Shaders and Editor scripts were written against the 6000.5 docs and the URP shader library but not compiled.
## 1. The technique
Draw the object a second time:
1. push every vertex **outward along its normal**,
2. render only the **back faces** (`Cull Front`),
3. in a flat outline color.
The front faces of the normal render cover the middle; only a rim of inflated back faces peeks out around the silhouette. Cheap, per-object, and it works on skinned characters.
Three implementation choices, all in this part:
| Option | How | Use when |
|---|---|---|
| A. Extra pass in the toon shader | `Pass { Tags { "LightMode"="SRPDefaultUnlit" } ... }` | Every object using `Tutorial/URP Toon Lit` should be outlined |
| B. Render Objects renderer feature | Override material on a layer | Outline *any* material (incl. Shader Graph) or toggle outlines by changing layers at runtime |
| C. Second material slot | (not covered) | Avoid in class - behaviour depends on submesh count |
Why not Shader Graph? The 6000.5 manual lists that Custom Function nodes cannot define extra passes or render state - and an outline needs both (`Cull Front` in its own pass).
URP draws passes tagged `UniversalForward` **and** passes tagged `SRPDefaultUnlit` (or untagged) - the manual's additional-lights example says so in a comment - which is what makes option A work.
## 2. `ToonOutline.hlsl` (shared by A and B)
Save as `Assets/_Toon/Shaders/ToonOutline.hlsl`.
```hlsl
#ifndef TOON_OUTLINE_INCLUDED
#define TOON_OUTLINE_INCLUDED
// Requires Core.hlsl and a UnityPerMaterial CBUFFER declaring:
// half4 _OutlineColor; half _OutlineWidth; half _OutlineUseTangents;
struct OutlineAttributes
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT; // holds smoothed normals when _OutlineUseTangents = 1
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct OutlineVaryings
{
float4 positionCS : SV_POSITION;
half fogFactor : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
OutlineVaryings OutlineVert(OutlineAttributes IN)
{
OutlineVaryings OUT = (OutlineVaryings)0;
UNITY_SETUP_INSTANCE_ID(IN);
UNITY_TRANSFER_INSTANCE_ID(IN, OUT);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
float3 normalOS = _OutlineUseTangents > 0.5 ? IN.tangentOS.xyz : IN.normalOS;
float4 positionCS = TransformObjectToHClip(IN.positionOS.xyz);
float3 normalWS = TransformObjectToWorldNormal(normalOS);
float2 normalCS = TransformWorldToHClipDir(normalWS).xy;
float len = length(normalCS);
if (len > 1e-5)
{
// _ScreenSize = (width, height, 1/width, 1/height). NDC spans 2 units across the screen,
// so N pixels = N * 2 / width. Multiplying by w cancels the perspective divide:
// the outline keeps the same pixel width at any distance.
float2 offsetNDC = (normalCS / len) * (_OutlineWidth * 2.0) * _ScreenSize.zw;
positionCS.xy += offsetNDC * positionCS.w;
}
OUT.positionCS = positionCS;
OUT.fogFactor = ComputeFogFactor(positionCS.z);
return OUT;
}
half4 OutlineFrag(OutlineVaryings IN) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(IN);
half3 color = MixFog(_OutlineColor.rgb, IN.fogFactor);
return half4(color, 1);
}
#endif // TOON_OUTLINE_INCLUDED
```
### Why extrude in clip space?
Extruding in object space (`positionOS + normalOS * width`) makes the line **thicker up close and vanish far away**, and depends on the object's scale. Projecting the normal to the screen and offsetting by a pixel amount gives a constant line weight, which is what 2D ink looks like. If you *want* distance scaling (thinner lines far away, a common style), multiply `_OutlineWidth` by `saturate(someDistance / positionCS.w)`.
## 3. Option A: outline pass inside `Tutorial/URP Toon Lit`
Paste this pass where part 3's shader says `// PART 4: paste the "Outline" pass here.`:
```hlsl
Pass
{
Name "Outline"
Tags { "LightMode"="SRPDefaultUnlit" }
Cull Front
ZWrite On
ZTest LEqual
HLSLPROGRAM
#pragma vertex OutlineVert
#pragma fragment OutlineFrag
#pragma multi_compile_fog
#pragma multi_compile_instancing
#include "Assets/_Toon/Shaders/ToonOutline.hlsl"
ENDHLSL
}
```
The CBUFFER in part 3 already declares `_OutlineColor`, `_OutlineWidth` and `_OutlineUseTangents`, so the pass shares the material's properties. Set `Outline Width` to 0 on materials that should not be outlined (the pass still draws but adds nothing visible; use option B if you want zero cost).
## 4. Option B: Render Objects on an "Outlined" layer
### 4.1 `ToonOutline.shader` (standalone)
```hlsl
Shader "Tutorial/Toon Outline"
{
Properties
{
_OutlineColor ("Outline Color", Color) = (0.05, 0.05, 0.08, 1)
_OutlineWidth ("Outline Width (px)", Range(0, 8)) = 3
[Toggle] _OutlineUseTangents ("Smoothed normals in tangents", Float) = 0
}
SubShader
{
Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" "Queue"="Geometry" }
HLSLINCLUDE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
CBUFFER_START(UnityPerMaterial)
half4 _OutlineColor;
half _OutlineWidth;
half _OutlineUseTangents;
CBUFFER_END
ENDHLSL
Pass
{
Name "Outline"
Cull Front
ZWrite On
ZTest LEqual
HLSLPROGRAM
#pragma vertex OutlineVert
#pragma fragment OutlineFrag
#pragma multi_compile_fog
#pragma multi_compile_instancing
#include "Assets/_Toon/Shaders/ToonOutline.hlsl"
ENDHLSL
}
}
}
```
Create material **`M_ToonOutline`** from it.
### 4.2 Renderer setup
1. *Project Settings > Tags and Layers*: add layer **`Outlined`**.
2. Select your **Universal Renderer Data** asset (the one your URP Asset uses) > **Add Renderer Feature > Render Objects**. Name it `Outline Layer`.
3. **Event**: *AfterRenderingOpaques*.
4. **Filters**: Queue **Opaque**, Layer Mask **Outlined**.
5. **Overrides**: Override Mode **Material**, Material **M_ToonOutline**, pass index 0.
6. **Depth**: Write Depth on, Depth Test **Less Equal**.
7. Keep the **Opaque Layer Mask** of the renderer including `Outlined`, so these objects are still drawn normally *and* get the extra outline draw.
Now any object - Shader Graph toon, URP Lit, anything opaque - gets an outline when you put it on the `Outlined` layer. Part 6 switches layers at runtime to highlight interactables.
## 5. Closing gaps: smoothed normals in tangents
On hard-edged meshes (a cube, a low-poly sword) each corner has several vertices with *different* normals. Extruding along them splits the hull at the edges: gaps appear in the outline.
Fix: for outlines only, use a normal **averaged across all vertices at the same position**. Store it in the **tangent** channel, because Unity's skinning transforms tangents along with positions and normals, so it stays correct on animated characters (UV channels would not be rotated by bones).
Trade-off: the mesh loses real tangents, so **normal maps break** on those meshes. Toon materials rarely use normal maps; if yours does, store the smoothed normal in a UV channel instead and accept that it is only correct for rigid meshes.
### `Assets/_Toon/Editor/ToonOutlineNormalsPostprocessor.cs`
```csharp
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
/// <summary>
/// For models whose file name contains "_Toon", bakes smoothed normals into the tangent channel
/// during import, for gap-free inverted-hull outlines (set Smoothed normals in tangents = 1).
/// Runs on every (re)import, so artists just re-export the FBX.
/// </summary>
public class ToonOutlineNormalsPostprocessor : AssetPostprocessor
{
const string Marker = "_Toon";
void OnPostprocessModel(GameObject root)
{
if (!assetPath.Contains(Marker)) return;
foreach (MeshFilter mf in root.GetComponentsInChildren<MeshFilter>(true))
if (mf.sharedMesh != null) BakeSmoothedNormalsIntoTangents(mf.sharedMesh);
foreach (SkinnedMeshRenderer smr in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
if (smr.sharedMesh != null) BakeSmoothedNormalsIntoTangents(smr.sharedMesh);
}
public static void BakeSmoothedNormalsIntoTangents(Mesh mesh)
{
Vector3[] vertices = mesh.vertices;
Vector3[] normals = mesh.normals;
if (normals == null || normals.Length != vertices.Length)
{
mesh.RecalculateNormals();
normals = mesh.normals;
}
// Group vertices by (quantized) position and sum their normals.
var sums = new Dictionary<Vector3Int, Vector3>(vertices.Length);
for (int i = 0; i < vertices.Length; i++)
{
Vector3Int key = Quantize(vertices[i]);
sums.TryGetValue(key, out Vector3 sum);
sums[key] = sum + normals[i];
}
var tangents = new Vector4[vertices.Length];
for (int i = 0; i < vertices.Length; i++)
{
Vector3 n = sums[Quantize(vertices[i])].normalized;
if (n == Vector3.zero) n = normals[i];
tangents[i] = new Vector4(n.x, n.y, n.z, 1f);
}
mesh.tangents = tangents;
}
// 0.0001 units tolerance: vertices closer than this are treated as the same corner.
static Vector3Int Quantize(Vector3 v) =>
new Vector3Int(Mathf.RoundToInt(v.x * 10000f), Mathf.RoundToInt(v.y * 10000f), Mathf.RoundToInt(v.z * 10000f));
}
```
Use: rename the model file to include `_Toon` (e.g. `Hero_Toon.fbx`) or re-export it with that name, let Unity re-import, then tick **Smoothed normals in tangents** on the outline material.
> [!note] Why a postprocessor and not a "bake" button?
> A button that writes new mesh assets creates copies that drift from the FBX. The postprocessor changes the *imported* mesh every time the model is imported, so re-exports from Blender just work. See [[Custom Inspectors and Editor Tooling]] for more Editor automation.
## 6. Check
- [ ] A sphere with `Tutorial/URP Toon Lit` shows an even 2 px line at any distance.
- [ ] A cube shows gaps at corners; `Cube_Toon.fbx` (exported cube) with tangents enabled shows none.
- [ ] Put a URP Lit barrel on layer `Outlined`: outline appears via Render Objects; move it back to Default: gone.
- [ ] Frame Debugger: outlined objects have an extra draw (`Outline` pass or the Render Objects event).
- [ ] An animated character keeps a clean outline while moving (tangents are skinned).
## Exercise
Make outlines colored per object: instead of black, use a darkened, saturated version of the albedo (common in anime styles). Which option (A or B) can do this without a new material per color, and why?
## Sources
- Introduction to custom lighting in URP, Custom Function limitations (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/lighting-overview/lighting/custom-lighting/introduction
- Render additional lights (example shader comment about `SRPDefaultUnlit`) (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/lighting-overview/lighting/custom-lighting/use-built-in-shader-methods-additional-lights-fplus
- Render Objects Renderer Feature (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/render-pipelines/universal-render-pipeline/customizing-urp/urp-renderer-feature/renderer-feature-render-objects
- `AssetPostprocessor.OnPostprocessModel` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/AssetPostprocessor.OnPostprocessModel.html
- `Mesh.tangents` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Mesh-tangents.html
- `TransformWorldToHClipDir` (SRP Core SpaceTransforms.hlsl): https://github.com/Unity-Technologies/Graphics/blob/master/Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl
- Related: [[Custom URP Renderer Features]], [[1. Renderer Features and Render Graph]]