Intrinsics1 min read
cos
Computes the cosine of an angle in radians.
Reading Time
1 min
Word Count
110
Sections
12
Try It Live
Test cos in a live shader
Open the playground, start from a visual preset, and wire cos into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The cos function returns the cosine of an angle specified in radians.
Signature
bwsl
cos :: (T x) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | Angle in radians |
Return Value
Returns the cosine of x, in the range [-1, 1].
Example
bwsl
pipeline SpotlightCone {
fragment {
float3 lightDir = normalize(lightPos - input.worldPos);
float3 spotDir = normalize(spotDirection);
// Calculate angle from spotlight axis
float cosAngle = dot(lightDir, -spotDir);
// Soft spotlight falloff
float spotFactor = smoothstep(cos(outerConeAngle), cos(innerConeAngle), cosAngle);
float3 lighting = lightColor * spotFactor;
output.color = float4(lighting, 1.0);
}
}Common Use Cases
Circular Motion
bwsl
// Point moving in circle (cos for x, sin for y)
float2 circlePos = float2(cos(angle), sin(angle)) * radius;Rotation Matrix
bwsl
// 2D rotation
float c = cos(angle);
float s = sin(angle);
float2 rotated = float2(
point.x * c - point.y * s,
point.x * s + point.y * c
);Lighting Calculations
bwsl
// Lambert diffuse (cosine of angle between normal and light)
float NdotL = max(dot(normal, lightDir), 0.0); // Equivalent to cos(theta)Pulsing Effects
bwsl
// Smooth pulse animation
float pulse = cos(time * speed) * 0.5 + 0.5;
float3 color = baseColor * (0.5 + pulse * 0.5);Spiral Pattern
bwsl
// Spiral UV coordinates
float angle = atan2(uv.y - 0.5, uv.x - 0.5);
float radius = length(uv - 0.5);
float spiral = cos(angle * arms + radius * twist);Relationship to sin
cos(x) equals sin(x + π/2). Cosine leads sine by 90 degrees (π/2 radians).
Compiled Output
When compiled to GLSL:
glsl
cos(x)
When compiled to HLSL:
hlsl
cos(x)