stride icon indicating copy to clipboard operation
stride copied to clipboard

[Math] UInt -> Color might not behave as users might expect

Open Eideren opened this issue 5 years ago • 1 comments

Release Type: GitHub

Version: Latest

Platform(s): Any

Describe the bug The format for string and ints to convert from and to colors are different from what most users might expect and what summaries for those functions implies:

var c = Color.FromRgba(ColorExtensions.StringToRgba("#FF119900"));
System.Console.WriteLine( $"R:{c.R:X} G:{c.G:X} B:{c.B:X} A:{c.A:X}" );
// Prints R:11 G:99 B:00 A:FF

c = Color.FromRgba(0xFF119900);
System.Console.WriteLine( $"R:{c.R:X} G:{c.G:X} B:{c.B:X} A:{c.A:X}" );
// Prints R:00 G:99 B:11 A:FF

To Reproduce See above

Expected behavior Mention that input string must be in ARGB format or change implementation to parse as an RGBA strings. Should Color.FromRgba be changed to handle like most people would expect from an hex literal? Try to avoid breaking changes if possible.

Additional context #746 #693

Eideren avatar Jun 03 '20 19:06 Eideren


  static int Vector3ToRGBA(Vector3 rgb)
  {
      //Clamp to [0;1]
      rgb.X = Math.Clamp(rgb.X, 0f, 1f);
      rgb.Y = Math.Clamp(rgb.Y, 0f, 1f);
      rgb.Z = Math.Clamp(rgb.Z, 0f, 1f);

      // Scale RGB values to the range [0, 255]
      int r = (int)(rgb.X * 255);
      int g = (int)(rgb.Y * 255);
      int b = (int)(rgb.Z * 255);

      // Combine values into an int32 RGBA format
      //int rgba = (r << 24) | (g << 16) | (b << 8) | 255;
      int rgba = (255 << 24) | (b << 16) | (g << 8) | r;

      return rgba;
  }

just writted this function with chat GPT, but it was not working good. (commented line) So i inverted the byte order and it worked (uncommented line)

//Stride.Core.Mathematics color constructor :
public Color(int rgba)
{
    A = (byte)((rgba >> 24) & 255);
    B = (byte)((rgba >> 16) & 255);
    G = (byte)((rgba >> 8) & 255);
    R = (byte)(rgba & 255);
}

Should probably be

    R = (byte)((rgba >> 24) & 255);
    G = (byte)((rgba >> 16) & 255);
    B = (byte)((rgba >> 8) & 255);
    A = (byte)(rgba & 255);

(Same for some others constructors)

Nicogo1705 avatar Jan 12 '24 14:01 Nicogo1705