# 3. Ramps Rim and Specular Bands Part of [[Stylized Toon and Outline Shading]]. Prev: [[2. Cel Lighting Custom Function in Shader Graph]]. Next: [[4. Inverted Hull Outlines]]. > [!warning] Code not compiled > The Editor script, graph steps and shader were written against the 6000.5 docs and URP shader library but not compiled. ## 1. Why a ramp texture? Bands from a formula are uniform. A **ramp** is a 1D texture indexed by the light term (0 = facing away/shadowed, 1 = facing the light): - Artists paint the transition: a warm rim of saturated color at the terminator, cool shadows, a tiny mid-tone. - Swapping ramps changes mood (day, night, poisoned) without touching the shader - *data, not code*. - Point filtering gives perfectly crisp bands; bilinear gives soft ones. ## 2. `ToonRampBaker.cs` (Editor) Save as `Assets/_Toon/Editor/ToonRampBaker.cs`. ```csharp using System.IO; using UnityEditor; using UnityEngine; /// <summary>Bakes a Gradient into a small ramp PNG for toon shaders.</summary> public class ToonRampBaker : EditorWindow { const string Folder = "Assets/_Toon/Ramps"; Gradient gradient; int width = 256; bool crisp = true; string fileName = "Ramp_Toon"; [MenuItem("Tools/Toon/Ramp Baker")] static void Open() => GetWindow<ToonRampBaker>("Toon Ramp Baker"); void OnEnable() { if (gradient != null) return; gradient = new Gradient { mode = GradientMode.Fixed }; gradient.SetKeys( new[] { new GradientColorKey(new Color(0.42f, 0.42f, 0.62f), 0.45f), // cool shadow new GradientColorKey(new Color(0.85f, 0.75f, 0.75f), 0.55f), // warm terminator new GradientColorKey(Color.white, 1f) // lit }, new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(1f, 1f) }); } void OnGUI() { EditorGUILayout.HelpBox("Left = shadow (light term 0), right = fully lit (1).", MessageType.Info); gradient = EditorGUILayout.GradientField("Ramp", gradient); width = EditorGUILayout.IntSlider("Width (px)", width, 16, 512); crisp = EditorGUILayout.Toggle(new GUIContent("Crisp (Point filter)", "Off = bilinear, softer band edges"), crisp); fileName = EditorGUILayout.TextField("File name", fileName); if (GUILayout.Button("Bake Ramp PNG")) Bake(); } void Bake() { var tex = new Texture2D(width, 4, TextureFormat.RGBA32, false); for (int x = 0; x < width; x++) { Color c = gradient.Evaluate((x + 0.5f) / width); for (int y = 0; y < 4; y++) tex.SetPixel(x, y, c); } tex.Apply(); Directory.CreateDirectory(Folder); // Unique path: never overwrites an existing ramp. string path = AssetDatabase.GenerateUniqueAssetPath(quot;{Folder}/{fileName}.png"); File.WriteAllBytes(path, tex.EncodeToPNG()); DestroyImmediate(tex); AssetDatabase.ImportAsset(path); var importer = (TextureImporter)AssetImporter.GetAtPath(path); importer.textureType = TextureImporterType.Default; importer.wrapMode = TextureWrapMode.Clamp; // no bleeding from the other end importer.filterMode = crisp ? FilterMode.Point : FilterMode.Bilinear; importer.mipmapEnabled = false; // a ramp is never minified meaningfully importer.sRGBTexture = true; // it stores colors importer.textureCompression = TextureImporterCompression.Uncompressed; // compression smears bands importer.SaveAndReimport(); Selection.activeObject = AssetDatabase.LoadAssetAtPath<Texture2D>(path); Debug.Log(quot;Baked ramp {path}"); } } ``` Settings that matter: **Clamp** (with Repeat, a light term of exactly 1 samples the left edge = shadow color on the brightest pixels), **no mipmaps**, **uncompressed** (block compression blends neighbouring colors into muddy bands). ## 3. Ramp, rim and specular in `SG_Toon` Continue the graph from part 2. ### Ramp 1. Add properties `Ramp Map` Texture2D [`_RampMap`] and `Ramp Blend` Float [`_RampBlend`] slider 0-1. 2. `Vector2` node: X = LightTerm (from part 2 step 7), Y = 0.5. Feed into the UV of a `Sample Texture 2D` (Ramp Map). Result *RampColor*. 3. `Lerp` (A = the part 2 band Lerp result, B = Albedo x RampColor x main light Color, T = Ramp Blend). Use this instead of the old band result. Now `Ramp Blend = 0` is formula bands, `1` is the ramp. ### Lit-side rim 1. `View Direction` node (Space World; it is normalized in current Shader Graph versions - add a `Normalize` if unsure). 2. `Dot Product` (View Direction, Normal Vector) -> `One Minus` -> *RimDot* (0 facing camera, 1 at the silhouette). 3. `Smoothstep` (Edge1 = RimThreshold - RimSoftness, Edge2 = RimThreshold + RimSoftness, In = RimDot). Properties `Rim Threshold` (0.7), `Rim Softness` (0.02), `Rim Color` (HDR, light warm). 4. *LitMask*: `Step` (Edge 0.5, In = LightTerm) - 1 on the lit band only. 5. `Multiply` rim x LitMask x Rim Color x main light Color, `Add` to the final color. Why lit-side only: a rim on the shadow side looks like a second light source and flattens the form; restricting it to the lit side reads as "backlight wrapping around". ### Hard specular blob 1. `Add` (main light Direction, View Direction) -> `Normalize` -> *H*. 2. `Dot Product` (Normal Vector, H) -> `Saturate` -> *NdotH*. 3. `Smoothstep` (Edge1 = 1 - SpecSize - SpecSoftness, Edge2 = 1 - SpecSize + SpecSoftness, In = NdotH). Properties `Spec Size` (0.03), `Spec Softness` (0.005), `Spec Color` (white). 4. `Multiply` by LitMask, Spec Color and main light Color; `Add` to the final color. Use spec only on materials that should look glossy (eyes, metal, wet surfaces); set `Spec Size` to 0 elsewhere. ## 4. The same look in HLSL: `Tutorial/URP Toon Lit` Shader Graph cannot add passes, so for the per-material outline in part 4 you need a hand-written shader. This one builds on *URP Simple Lit* from [[URP Shaders and Shader Graph]] (same keywords, Forward+ loop and `UsePass` approach) and reuses `ToonLighting.hlsl` from part 2. Save as `Assets/_Toon/Shaders/ToonLit.shader`. ```hlsl Shader "Tutorial/URP Toon Lit" { Properties { [MainTexture] _BaseMap ("Base Map", 2D) = "white" {} [MainColor] _BaseColor ("Base Color", Color) = (1,1,1,1) [Header(Bands)] _Bands ("Bands", Range(2, 5)) = 2 _BandSoftness ("Band Softness", Range(0, 0.1)) = 0.02 _ShadowTint ("Shadow Tint", Color) = (0.55, 0.55, 0.75, 1) _RampMap ("Ramp Map", 2D) = "white" {} _RampBlend ("Ramp Blend (0 bands, 1 ramp)", Range(0, 1)) = 0 [Header(Specular)] _SpecColor ("Spec Color", Color) = (1,1,1,1) _SpecSize ("Spec Size", Range(0, 0.5)) = 0.03 _SpecSoftness ("Spec Softness", Range(0, 0.05)) = 0.005 [Header(Rim)] [HDR] _RimColor ("Rim Color", Color) = (1, 0.9, 0.8, 1) _RimThreshold ("Rim Threshold", Range(0, 1)) = 0.7 _RimSoftness ("Rim Softness", Range(0, 0.1)) = 0.02 [Header(Ambient)] _AmbientStrength ("Ambient Strength", Range(0, 1)) = 0.35 [Header(Outline (used by the Outline pass in part 4))] _OutlineColor ("Outline Color", Color) = (0.05, 0.05, 0.08, 1) _OutlineWidth ("Outline Width (px)", Range(0, 8)) = 2 [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" // Every pass of this shader shares one UnityPerMaterial buffer (SRP Batcher rule). CBUFFER_START(UnityPerMaterial) float4 _BaseMap_ST; half4 _BaseColor; half _Bands; half _BandSoftness; half4 _ShadowTint; float4 _RampMap_ST; half _RampBlend; half4 _SpecColor; half _SpecSize; half _SpecSoftness; half4 _RimColor; half _RimThreshold; half _RimSoftness; half _AmbientStrength; half4 _OutlineColor; half _OutlineWidth; half _OutlineUseTangents; CBUFFER_END ENDHLSL Pass { Name "ForwardLit" Tags { "LightMode"="UniversalForward" } HLSLPROGRAM #pragma vertex vert #pragma fragment frag #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN #pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS #pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile _ _CLUSTER_LIGHT_LOOP #pragma multi_compile_fog #pragma multi_compile_instancing // Pulls in Lighting.hlsl and ToonBandValue / ToonAdditionalLight. #include "Assets/_Toon/Shaders/ToonLighting.hlsl" TEXTURE2D(_BaseMap); SAMPLER(sampler_BaseMap); TEXTURE2D(_RampMap); SAMPLER(sampler_RampMap); struct Attributes { float4 positionOS : POSITION; float3 normalOS : NORMAL; float2 uv : TEXCOORD0; UNITY_VERTEX_INPUT_INSTANCE_ID }; struct Varyings { float4 positionCS : SV_POSITION; float2 uv : TEXCOORD0; float3 normalWS : TEXCOORD1; float3 positionWS : TEXCOORD2; half fogFactor : TEXCOORD3; UNITY_VERTEX_INPUT_INSTANCE_ID }; Varyings vert(Attributes IN) { Varyings OUT = (Varyings)0; UNITY_SETUP_INSTANCE_ID(IN); UNITY_TRANSFER_INSTANCE_ID(IN, OUT); VertexPositionInputs p = GetVertexPositionInputs(IN.positionOS.xyz); OUT.positionCS = p.positionCS; OUT.positionWS = p.positionWS; OUT.normalWS = TransformObjectToWorldNormal(IN.normalOS); OUT.uv = TRANSFORM_TEX(IN.uv, _BaseMap); OUT.fogFactor = ComputeFogFactor(p.positionCS.z); return OUT; } // Diffuse multiplier from formula bands or the ramp texture. half3 ToonDiffuse(float lightTerm) { float band = ToonBandValue(lightTerm, _Bands, _BandSoftness); half3 bands = lerp(_ShadowTint.rgb, half3(1, 1, 1), band); half3 ramp = SAMPLE_TEXTURE2D(_RampMap, sampler_RampMap, float2(saturate(lightTerm), 0.5)).rgb; return lerp(bands, ramp, _RampBlend); } half3 ShadeMainLight(Light light, float3 N, float3 V, half3 albedo) { float ndotl = dot(N, light.direction); float lightTerm = (ndotl * 0.5 + 0.5) * light.shadowAttenuation; half3 color = albedo * ToonDiffuse(lightTerm) * light.color; float litMask = step(0.5, lightTerm); // Hard specular blob (Blinn half vector, thresholded). float3 H = normalize(light.direction + V); float ndoth = saturate(dot(N, H)); float specEdge = 1.0 - _SpecSize; float spec = smoothstep(specEdge - _SpecSoftness, specEdge + _SpecSoftness, ndoth) * litMask; color += _SpecColor.rgb * spec * light.color * step(0.0001, _SpecSize); // Lit-side rim. float rimDot = 1.0 - saturate(dot(V, N)); float rim = smoothstep(_RimThreshold - _RimSoftness, _RimThreshold + _RimSoftness, rimDot) * litMask; color += _RimColor.rgb * rim * light.color; return color; } half4 frag(Varyings IN) : SV_Target { UNITY_SETUP_INSTANCE_ID(IN); half3 albedo = (SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, IN.uv) * _BaseColor).rgb; float3 N = normalize(IN.normalWS); float3 V = GetWorldSpaceNormalizeViewDir(IN.positionWS); // Main light with shadows. float4 shadowCoord = TransformWorldToShadowCoord(IN.positionWS); Light mainLight = GetMainLight(shadowCoord); half3 color = ShadeMainLight(mainLight, N, V, albedo); // Ambient (light probes / skybox SH). color += albedo * SampleSH(N) * _AmbientStrength; // Additional lights: Forward and Forward+ (manual's light loop pattern). InputData inputData = (InputData)0; inputData.positionWS = IN.positionWS; inputData.normalWS = N; inputData.viewDirectionWS = V; inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(IN.positionCS); #if defined(_ADDITIONAL_LIGHTS) #if USE_CLUSTER_LIGHT_LOOP UNITY_LOOP for (uint lightIndex = 0; lightIndex < min(URP_FP_DIRECTIONAL_LIGHTS_COUNT, MAX_VISIBLE_LIGHTS); lightIndex++) { Light dl = GetAdditionalLight(lightIndex, IN.positionWS, half4(1,1,1,1)); color += albedo * ToonAdditionalLight(dl, N, _Bands, _BandSoftness); } #endif uint lightCount = GetAdditionalLightsCount(); LIGHT_LOOP_BEGIN(lightCount) Light l = GetAdditionalLight(lightIndex, IN.positionWS, half4(1,1,1,1)); color += albedo * ToonAdditionalLight(l, N, _Bands, _BandSoftness); LIGHT_LOOP_END #endif color = MixFog(color, IN.fogFactor); return half4(color, 1); } ENDHLSL } // PART 4: paste the "Outline" pass here. // Shadows, depth prepass and the normals texture (needed by part 5's edge outlines). // Same approach and the same SRP Batcher caveat as the existing URP Simple Lit example. UsePass "Universal Render Pipeline/Lit/ShadowCaster" UsePass "Universal Render Pipeline/Lit/DepthOnly" UsePass "Universal Render Pipeline/Lit/DepthNormals" } } ``` ### Notes on the shader - **`#include "Assets/_Toon/Shaders/ToonLighting.hlsl"`** - project-relative include path; if you move the file, update it. Because `SHADERGRAPH_PREVIEW` is not defined here, the include pulls in URP's `Lighting.hlsl`. - **`_ADDITIONAL_LIGHTS_VERTEX`** is compiled but per-vertex lighting is not implemented; set *Additional Lights* to **Per Pixel** in the URP Asset (or the additional lights disappear in that mode). - **CBUFFER contains the outline properties** so the outline pass added in part 4 shares the same per-material buffer. - **`UsePass` borrows URP Lit's passes**, which read their own property layout; as the URP Simple Lit note explains, this costs SRP Batcher compatibility. If the Inspector reports the shader as not SRP Batcher compatible and you need batching, port URP's shadow/depth passes into this file. ## Exercise Bake three ramps (day, dusk, poisoned) and swap them on one material at runtime with `material.SetTexture("_RampMap", ...)` in a trigger volume. Then do it with three *materials* instead and compare in the Frame Debugger which keeps batching. ## Sources - Use lighting in a custom URP shader (6000.5): https://docs.unity.com/en-us/engine/6000.5/manual/materials-and-shaders/shaders/writing-custom-shaders-urp/use-built-in-shader-methods/lighting - Render additional lights in Forward and Forward+ (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 - `TextureImporter` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/TextureImporter.html - `EditorGUILayout.GradientField` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/EditorGUILayout.GradientField.html - `AssetDatabase.GenerateUniqueAssetPath` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/AssetDatabase.GenerateUniqueAssetPath.html - Smoothstep / Step / Fresnel nodes (Shader Graph 17.5): https://docs.unity3d.com/Packages/[email protected]/manual/Fresnel-Effect-Node.html - Related: [[URP Shaders and Shader Graph]], [[Custom Inspectors and Editor Tooling]]