# Cg Programming/Unity/Brushed Metal

Brushed aluminium. Note the form of the specular highlights, which is far from being round.

This tutorial covers anisotropic specular highlights.

It is one of several tutorials about lighting that go beyond the Phong reflection model. However, it is based on lighting with the Phong reflection model as described in Section “Specular Highlights” (for per-vertex lighting) and Section “Smooth Specular Highlights” (for per-pixel lighting). If you haven't read those tutorials yet, you should read them first.

While the Phong reflection model is reasonably good for paper, plastics, and some other materials with isotropic reflection (i.e. round highlights), this tutorial looks specifically at materials with anisotropic reflection (i.e. non-round highlights), for example brushed aluminium as in the photo to the left.

In addition to most of the vectors used by the Phong reflection model, we require the normalized halfway vector H, which is the direction exactly between the direction to the viewer V and the direction to the light source L.

## Ward's Model of Anisotropic Reflection

Gregory Ward published a suitable model of anisotropic reflection in his work “Measuring and Modeling Anisotropic Reflection”, Computer Graphics (SIGGRAPH ’92 Proceedings), pp. 265–272, July 1992. (A copy of the paper is available online.) This model describes the reflection in terms of a BRDF (bidrectional reflectance distribution function), which is a four-dimensional function that describes how a light ray from any direction is reflected into any other direction. His BRDF model consists of two terms: a diffuse reflectance term, which is ${\displaystyle \rho _{d}/\pi }$, and a more complicated specular reflectance term.

Let's have a look at the diffuse term ${\displaystyle \rho _{d}/\pi }$ first: ${\displaystyle \pi }$ is just a constant (about 3.14159) and ${\displaystyle \rho _{d}}$ specifies the diffuse reflectance. In principle, a reflectance for each wave length is necessary; however, usually one reflectance for each of the three color components (red, green, and blue) is specified. If we include the constant ${\displaystyle \pi }$, ${\displaystyle \rho _{d}/\pi }$ just represents the diffuse material color ${\displaystyle k_{\text{diffuse}}}$, which we have first seen in Section “Diffuse Reflection” but which also appears in the Phong reflection model (see Section “Specular Highlights”). You might wonder why the factor max(0, L·N) doesn't appear in the BRDF. The answer is that the BRDF is defined in such a way that this factor is not included in it (because it isn't really a property of the material) but it should be multiplied with the BRDF when doing any lighting computation.

Thus, in order to implement a given BRDF for opaque materials, we have to multiply all terms of the BRDF with max(0, L·N) and − unless we want to implement physically correct lighting − we can replace any constant factors by user-specified colors, which usually are easier to control than physical quantities.

For the specular term of his BRDF model, Ward presents an approximation in equation 5b of his paper. I adapted it slightly such that it uses the normalized surface normal vector N, the normalized direction to the viewer V, the normalized direction to the light source L, and the normalized halfway vector H which is (V + L) / |V + L|. Using these vectors, Ward's approximation for the specular term becomes:

${\displaystyle \rho _{s}{\frac {1}{\sqrt {(\mathbf {L} \cdot \mathbf {N} )(\mathbf {V} \cdot \mathbf {N} )}}}\cdot {\frac {1}{4\pi \alpha _{x}\alpha _{y}}}\exp \left(-2{\frac {\left((\mathbf {H} \cdot \mathbf {T} )/\alpha _{x}\right)^{2}+\left((\mathbf {H} \cdot \mathbf {B} )/\alpha _{y}\right)^{2}}{1+\mathbf {H} \cdot \mathbf {N} }}\right)}$

Here, ${\displaystyle \rho _{s}}$ is the specular reflectance, which describes the color and intensity of the specular highlights; ${\displaystyle \alpha _{x}}$ and ${\displaystyle \alpha _{y}}$ are material constants that describe the shape and size of the highlights. Since all these variables are material constants, we can combine them in one constant ${\displaystyle k_{\text{specular}}}$. Thus, we get a slightly shorter version:

${\displaystyle k_{\text{specular}}{\frac {1}{\sqrt {(\mathbf {L} \cdot \mathbf {N} )(\mathbf {V} \cdot \mathbf {N} )}}}\exp \left(-2{\frac {\left((\mathbf {H} \cdot \mathbf {T} )/\alpha _{x}\right)^{2}+\left((\mathbf {H} \cdot \mathbf {B} )/\alpha _{y}\right)^{2}}{1+\mathbf {H} \cdot \mathbf {N} }}\right)}$

Remember that we still have to multiply this BRDF term with L·N when implementing it in a shader and set it to 0 if L·N is less than 0. Furthermore, it should also be 0 if V·N is less than 0, i.e., if we are looking at the surface from the “wrong” side.

There are two vectors that haven't been described yet: T and B. T is the brush direction on the surface and B is orthogonal to T but also on the surface. Unity provides us with a tangent vector on the surface as a vertex attribute (see Section “Debugging of Shaders”), which we will use as the vector T. Computing the cross product of N and T generates a vector B, which is orthogonal to N and T, as it should be.

## Implementation of Ward's BRDF Model

We base our implementation on the shader for per-pixel lighting in Section “Smooth Specular Highlights”. We need another vertex output parameter tangentDir for the tangent vector T (i.e. the brush direction) and we also compute viewDir in the vertex shader to save some instructions in the fragment shader. In the fragment shader, we compute two more directions: halfwayVector for the halfway vector H and binormalDirection for the binormal vector B. The properties are _Color for ${\displaystyle k_{\text{diffuse}}}$, _SpecColor for ${\displaystyle k_{\text{specular}}}$, _AlphaX for ${\displaystyle \alpha _{x}}$, and _AlphaY for ${\displaystyle \alpha _{y}}$.

The fragment shader is then very similar to the version in Section “Smooth Specular Highlights” except that it computes halfwayVector and binormalDirection, and implements a different equation for the specular part. Furthermore, this shader computes the dot product L·N only once and stores it in dotLN such that it can be reused without having to recompute it. It looks like this:

         float4 frag(vertexOutput input) : COLOR
{
float3 lightDirection;
float attenuation;

if (0.0 == _WorldSpaceLightPos0.w) // directional light?
{
attenuation = 1.0; // no attenuation
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else // point or spot light
{
float3 vertexToLightSource =
_WorldSpaceLightPos0.xyz - input.posWorld.xyz;
float distance = length(vertexToLightSource);
attenuation = 1.0 / distance; // linear attenuation
lightDirection = normalize(vertexToLightSource);
}

float3 halfwayVector =
normalize(lightDirection + input.viewDir);
float3 binormalDirection =
cross(input.normalDir, input.tangentDir);
float dotLN = dot(lightDirection, input.normalDir);
// compute this dot product only once

float3 ambientLighting =
UNITY_LIGHTMODEL_AMBIENT.rgb * _Color.rgb;

float3 diffuseReflection =
attenuation * _LightColor0.rgb * _Color.rgb
* max(0.0, dotLN);

float3 specularReflection;
if (dotLN < 0.0) // light source on the wrong side?
{
specularReflection = float3(0.0, 0.0, 0.0);
// no specular reflection
}
else // light source on the right side
{
float dotHN = dot(halfwayVector, input.normalDir);
float dotVN = dot(input.viewDir, input.normalDir);
float dotHTAlphaX =
dot(halfwayVector, input.tangentDir) / _AlphaX;
float dotHBAlphaY = dot(halfwayVector,
binormalDirection) / _AlphaY;

specularReflection =
attenuation * _LightColor0.rgb * _SpecColor.rgb
* sqrt(max(0.0, dotLN / dotVN))
* exp(-2.0 * (dotHTAlphaX * dotHTAlphaX
+ dotHBAlphaY * dotHBAlphaY) / (1.0 + dotHN));
}
return float4(ambientLighting + diffuseReflection
+ specularReflection, 1.0);
}


Note the term sqrt(max(0, dotLN / dotVN)) which resulted from ${\displaystyle {\frac {1}{\sqrt {(\mathbf {L} \cdot \mathbf {N} )(\mathbf {V} \cdot \mathbf {N} )}}}}$ multiplied with ${\displaystyle (\mathbf {L} \cdot \mathbf {N} )}$. This makes sure that everything is greater than 0.

The complete shader code just defines the appropriate properties and adds another vertex input parameter for the tangent. Also, it requires a second pass with additive blending but without ambient lighting for additional light sources.

Shader "Cg anisotropic per-pixel lighting" {
Properties {
_Color ("Diffuse Material Color", Color) = (1,1,1,1)
_SpecColor ("Specular Material Color", Color) = (1,1,1,1)
_AlphaX ("Roughness in Brush Direction", Float) = 1.0
_AlphaY ("Roughness orthogonal to Brush Direction", Float) = 1.0
}
Pass {
Tags { "LightMode" = "ForwardBase" }
// pass for ambient light and first light source

CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"
uniform float4 _LightColor0;
// color of light source (from "Lighting.cginc")

// User-specified properties
uniform float4 _Color;
uniform float4 _SpecColor;
uniform float _AlphaX;
uniform float _AlphaY;

struct vertexInput {
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 posWorld : TEXCOORD0;
// position of the vertex (and fragment) in world space
float3 viewDir : TEXCOORD1;
// view direction in world space
float3 normalDir : TEXCOORD2;
// surface normal vector in world space
float3 tangentDir : TEXCOORD3;
// brush direction in world space
};

vertexOutput vert(vertexInput input)
{
vertexOutput output;

float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;

output.posWorld = mul(modelMatrix, input.vertex);
output.viewDir = normalize(_WorldSpaceCameraPos
- output.posWorld.xyz);
output.normalDir = normalize(
mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
output.tangentDir = normalize(
mul(modelMatrix, float4(input.tangent.xyz, 0.0)).xyz);
output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
return output;
}

float4 frag(vertexOutput input) : COLOR
{
float3 lightDirection;
float attenuation;

if (0.0 == _WorldSpaceLightPos0.w) // directional light?
{
attenuation = 1.0; // no attenuation
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else // point or spot light
{
float3 vertexToLightSource =
_WorldSpaceLightPos0.xyz - input.posWorld.xyz;
float distance = length(vertexToLightSource);
attenuation = 1.0 / distance; // linear attenuation
lightDirection = normalize(vertexToLightSource);
}

float3 halfwayVector =
normalize(lightDirection + input.viewDir);
float3 binormalDirection =
cross(input.normalDir, input.tangentDir);
float dotLN = dot(lightDirection, input.normalDir);
// compute this dot product only once

float3 ambientLighting =
UNITY_LIGHTMODEL_AMBIENT.rgb * _Color.rgb;

float3 diffuseReflection =
attenuation * _LightColor0.rgb * _Color.rgb
* max(0.0, dotLN);

float3 specularReflection;
if (dotLN < 0.0) // light source on the wrong side?
{
specularReflection = float3(0.0, 0.0, 0.0);
// no specular reflection
}
else // light source on the right side
{
float dotHN = dot(halfwayVector, input.normalDir);
float dotVN = dot(input.viewDir, input.normalDir);
float dotHTAlphaX =
dot(halfwayVector, input.tangentDir) / _AlphaX;
float dotHBAlphaY = dot(halfwayVector,
binormalDirection) / _AlphaY;

specularReflection =
attenuation * _LightColor0.rgb * _SpecColor.rgb
* sqrt(max(0.0, dotLN / dotVN))
* exp(-2.0 * (dotHTAlphaX * dotHTAlphaX
+ dotHBAlphaY * dotHBAlphaY) / (1.0 + dotHN));
}
return float4(ambientLighting + diffuseReflection
+ specularReflection, 1.0);
}
ENDCG
}

Pass {
Tags { "LightMode" = "ForwardAdd" }
// pass for additional light sources
Blend One One // additive blending

CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"
uniform float4 _LightColor0;
// color of light source (from "Lighting.cginc")

// User-specified properties
uniform float4 _Color;
uniform float4 _SpecColor;
uniform float _AlphaX;
uniform float _AlphaY;

struct vertexInput {
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 posWorld : TEXCOORD0;
// position of the vertex (and fragment) in world space
float3 viewDir : TEXCOORD1;
// view direction in world space
float3 normalDir : TEXCOORD2;
// surface normal vector in world space
float3 tangentDir : TEXCOORD3;
// brush direction in world space
};

vertexOutput vert(vertexInput input)
{
vertexOutput output;

float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;

output.posWorld = mul(modelMatrix, input.vertex);
output.viewDir = normalize(_WorldSpaceCameraPos
- output.posWorld.xyz);
output.normalDir = normalize(
mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
output.tangentDir = normalize(
mul(modelMatrix, float4(input.tangent.xyz, 0.0)).xyz);
output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
return output;
}

float4 frag(vertexOutput input) : COLOR
{
float3 lightDirection;
float attenuation;

if (0.0 == _WorldSpaceLightPos0.w) // directional light?
{
attenuation = 1.0; // no attenuation
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else // point or spot light
{
float3 vertexToLightSource =
_WorldSpaceLightPos0.xyz - input.posWorld.xyz;
float distance = length(vertexToLightSource);
attenuation = 1.0 / distance; // linear attenuation
lightDirection = normalize(vertexToLightSource);
}

float3 halfwayVector =
normalize(lightDirection + input.viewDir);
float3 binormalDirection =
cross(input.normalDir, input.tangentDir);
float dotLN = dot(lightDirection, input.normalDir);
// compute this dot product only once

float3 diffuseReflection =
attenuation * _LightColor0.rgb * _Color.rgb
* max(0.0, dotLN);

float3 specularReflection;
if (dotLN < 0.0) // light source on the wrong side?
{
specularReflection = float3(0.0, 0.0, 0.0);
// no specular reflection
}
else // light source on the right side
{
float dotHN = dot(halfwayVector, input.normalDir);
float dotVN = dot(input.viewDir, input.normalDir);
float dotHTAlphaX =
dot(halfwayVector, input.tangentDir) / _AlphaX;
float dotHBAlphaY = dot(halfwayVector,
binormalDirection) / _AlphaY;

specularReflection =
attenuation * _LightColor0.rgb * _SpecColor.rgb
* sqrt(max(0.0, dotLN / dotVN))
* exp(-2.0 * (dotHTAlphaX * dotHTAlphaX
+ dotHBAlphaY * dotHBAlphaY) / (1.0 + dotHN));
}
return float4(diffuseReflection
+ specularReflection, 1.0);
}
ENDCG
}
}
Fallback "Specular"
}


## Summary

Congratulations, you finished a rather advanced tutorial! We have seen:

• What a BRDF (bidirectional reflectance distribution function) is.
• What Ward's BRDF model for anisotropic reflection is.
• How to implement Ward's BRDF model.