lengthSq
Calculates the squared length of a vector, providing a high-performance alternative to `length` for distance comparisons.
Core Advantages
Its core advantage is performance. By avoiding the expensive square root operation, it is significantly faster for any task that only requires comparing distances, not knowing the exact distance. It also improves code clarity and intent with its explicit name.
Common Uses
Efficient range checking (e.g., light culling)
Physically-based light attenuation (inverse square law)
Creating non-linear radial gradients (parabolic shape)
How to adjust
Its output grows quadratically (like y=x²), unlike the linear growth of `length`. This creates effects that are very soft near the origin and change rapidly further away. Scaling its input vector by a factor of `s` will scale the output value by `s²`, allowing for precise control over the size and falloff of distance-based effects.
Code Examples
1// Use squared distance for a more physically accurate light attenuation
2const distSq = lengthSq( pixelPos.sub( lightPos ) );
3const attenuation = float(1.0).div( float(1.0).add( distSq ) );