namespace XFEWarframe.Client; /// Recovers the original card's transparency from two native draws on known opaque backgrounds. public static class NativeCardPixels { public static byte[] Encode(byte[] dark, byte[] light, int frameWidth, int frameHeight, int left, int top, int width, int height, bool trimTransparentMargin = false) { if (dark.Length != light.Length || frameWidth is < 1 or > 8192 || frameHeight is < 1 or > 8192 || (long)frameWidth * frameHeight * 4 != dark.LongLength || width is < 1 or > 4096 || height is < 1 or > 4096 || left < 0 || top < 0 || (long)left + width > frameWidth || (long)top + height > frameHeight) throw new InvalidDataException("Invalid native card render rectangle."); var rgba = new byte[checked(width * height * 4)]; var transparent = 0; var visible = 0; var levels = new HashSet(); var minX = width; var maxX = -1; var minY = height; var maxY = -1; var edgeMinX = width; var edgeMaxX = -1; var edgeMinY = height; var edgeMaxY = -1; for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) { var source = ((top + y) * frameWidth + left + x) * 4; var target = (y * width + x) * 4; var difference = (light[source] - dark[source] + light[source + 1] - dark[source + 1] + light[source + 2] - dark[source + 2]) / 3; var alpha = Math.Clamp(255 - difference, 0, 255); if (alpha <= 3) { transparent++; continue; } edgeMinX = Math.Min(edgeMinX, x); edgeMaxX = Math.Max(edgeMaxX, x); edgeMinY = Math.Min(edgeMinY, y); edgeMaxY = Math.Max(edgeMaxY, y); rgba[target + 3] = (byte)alpha; for (var c = 0; c < 3; c++) rgba[target + c] = (byte)Math.Clamp((dark[source + c] * 255 + alpha / 2) / alpha, 0, 255); if (alpha > 96) { visible++; minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); minY = Math.Min(minY, y); maxY = Math.Max(maxY, y); levels.Add((rgba[target] >> 4) | (rgba[target + 1] >> 4) << 4 | (rgba[target + 2] >> 4) << 8); } } // A hidden/unpainted movie, a stale frame or gameplay/background pixels are // failures, never a successful cache entry. Leave the request retryable. if (transparent < width * height / 40 || visible < width * height / 4 || levels.Count < 12 || maxX - minX < width * .65 || maxY - minY < height * .4) throw new InvalidDataException($"Native card has not finished rendering (transparent={transparent}, visible={visible}, colors={levels.Count})."); if (!trimTransparentMargin) return PngImages.CropRgba(rgba, width, height, 0, 0, width, height); // Remove only fully transparent padding, preserving every native edge, // shadow, crest and rank light; no rescaling or reconstruction occurs. var cropLeft = Math.Max(0, edgeMinX - 2); var cropTop = Math.Max(0, edgeMinY - 2); var cropRight = Math.Min(width - 1, edgeMaxX + 2); var cropBottom = Math.Min(height - 1, edgeMaxY + 2); return PngImages.CropRgba(rgba, width, height, cropLeft, cropTop, cropRight - cropLeft + 1, cropBottom - cropTop + 1); } }