[clang] [HLSL] Implement D3DCOLORtoUBYTE4 intrinsic (PR #122202)

Deric Cheung via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 9 11:11:42 PST 2025


================
@@ -33,6 +33,14 @@ constexpr enable_if_t<sizeof(U) == sizeof(T), U> bit_cast(T F) {
   return __builtin_bit_cast(U, F);
 }
 
+constexpr vector<uint, 4> d3d_color_to_ubyte4(vector<float, 4> V) {
+  // Use the same scaling factor used by FXC (i.e., 255.001953)
+  // Excerpt from stackoverflow discussion:
+  // "Built-in rounding, necessary because of truncation. 0.001953 * 256 = 0.5"
+  // https://stackoverflow.com/questions/52103720/why-does-d3dcolortoubyte4-multiplies-components-by-255-001953f
+  return V.zyxw * 255.001953f;
----------------
Icohedron wrote:

This implementation of `D3DCOLORtoUBYTE4` scales the vector by `255.001953`. This matches the way it was done in [DXC](https://github.com/microsoft/DirectXShaderCompiler/blob/070d0d5a2beacef9eeb51037a9b04665716fd6f3/lib/HLSL/HLOperationLower.cpp#L666C1-L697C2).
However, it differs from the [SPIRV custom implementation](https://github.com/microsoft/DirectXShaderCompiler/blob/070d0d5a2beacef9eeb51037a9b04665716fd6f3/tools/clang/lib/SPIRV/SpirvEmitter.cpp#L11647C1-L11663C2) which scales the vector by `255.002`.


https://github.com/llvm/llvm-project/pull/122202


More information about the cfe-commits mailing list