normalize
Returns a unit vector in the same direction.
Test normalize in a live shader
Open the playground, start from a visual preset, and wire normalize into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The normalize function returns a unit vector (length 1) pointing in the same direction as the input vector.
Signature
normalize :: (vecN v) -> vecN {...}
Where vecN can be float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
v | vecN | The vector to normalize |
Return Value
Returns v / length(v), a unit vector in the direction of v.
Example
pipeline BasicLighting {
fragment {
// Normalize interpolated vectors
float3 normal = normalize(input.normal);
float3 viewDir = normalize(cameraPos - input.worldPos);
float3 lightDir = normalize(lightPos - input.worldPos);
// Calculate lighting with normalized vectors
float diffuse = max(dot(normal, lightDir), 0.0);
float3 halfDir = normalize(lightDir + viewDir);
float specular = pow(max(dot(normal, halfDir), 0.0), 32.0);
float3 color = ambient + diffuse * diffuseColor + specular * specularColor;
output.color = float4(color, 1.0);
}
}Common Use Cases
Direction Vectors
// Get direction from A to B
float3 direction = normalize(targetPos - currentPos);Lighting Calculations
// All lighting vectors should be normalized
float3 N = normalize(normal);
float3 L = normalize(lightDirection);
float3 V = normalize(viewDirection);Reflection/Refraction
// Normalize before reflection
float3 incident = normalize(rayDir);
float3 normal = normalize(surfaceNormal);
float3 reflected = reflect(incident, normal);Spherical Coordinates
// Normalize to get point on unit sphere
float3 spherePoint = normalize(position);
float2 uv = float2(atan2(spherePoint.z, spherePoint.x), asin(spherePoint.y));Interpolation of Directions
// Renormalize after linear interpolation
float3 blendedNormal = lerp(normal1, normal2, t);
blendedNormal = normalize(blendedNormal);Zero Vector
Normalizing a zero-length vector produces undefined results (typically NaN or infinity). Check for zero vectors: if (length(v) > 0.0001) v = normalize(v);
Interpolated Normals
Normals interpolated across a surface may not be unit length. Always normalize interpolated normals in the fragment shader before lighting calculations.
Compiled Output
When compiled to GLSL:
normalize(v)
When compiled to HLSL:
normalize(v)