countLeadingZeros
Returns the number of consecutive 0 bits starting from the most significant bit (MSB) of a 32-bit integer. It works on uint/int and their vector variants and is intended for low-level inspection of integer bit patterns.
Core Advantages
Exposes the GPU’s native (or emulated) countLeadingZeros capability to the WebGPU shading pipeline, so you can drive branches, indices or hierarchical logic directly from the effective bit width of an integer. This is often more efficient and precise than approximating the same behavior with floating-point log2 or manual loops.
Common Uses
Deriving the magnitude or effective bit width of an integer via the MSB position (for example: msbIndex = 31 - clz(x)), then using it to build LOD, mip level or stepwise functions.
Bucketizing hash outputs or random integers at the bit level: mapping different counts of leading zeros to different color, roughness or intensity ranges in procedural materials or VFX.
Quickly evaluating the sparsity or high-bit usage of bitmasks, e.g. deciding between different branches or effect strengths depending on whether significant bits live in high or low ranges.
Debugging or visualizing integer bit patterns by normalizing the number of leading zeros to 0–1 and using it as brightness, mask, or blend factor to check whether encoding / hashing behaves as expected.
How to adjust
The output of countLeadingZeros is a discrete integer in the range 0–32, so it does not produce smooth transitions by itself. In practice: (1) make sure the input is an integer type (uint/int or their vector variants); if you start from floats, first convert them to an integer or bitmask according to your own rules; (2) be aware that by convention an input of 0 returns 32, which can be used as a special case in your logic; (3) it is common to cast the result to float and divide by 32 to obtain a 0–1 factor for LOD, weights, or indexing; (4) according to the documentation this node is intended for use with WebGPURenderer and a WebGPU backend, so pay attention to compatibility and performance if you try to use it elsewhere.
Code Examples
1// A 32-bit unsigned integer bitmask encoding some state
2const mask = uint( 0x0000FFFF );
3
4// Count the number of consecutive 0 bits from the most significant bit (0–32)
5// For vector types (uvec2 / uvec3 / ...) this is done component-wise
6const leadingZeros = countLeadingZeros( mask );
7
8// Normalize the result to 0–1 and use it as an intensity or blend factor
9const intensity = float( leadingZeros ).div( 32.0 );
10
11// Drive the material color with that factor (example)
12material.colorNode = vec3( intensity );