CSharpImageLibrary.DDS.DDSGeneral.EnsureMipInImage C# (CSharp) Method

EnsureMipInImage() public static method

Checks image file size to ensure requested mipmap is present in image. Header mip count can be incorrect or missing. Use this method to validate the mip you're after.
public static EnsureMipInImage ( long streamLength, int mainWidth, int mainHeight, int desiredMipDimension, ImageEngineFormat format, int &mipOffset ) : bool
streamLength long Image file stream length.
mainWidth int Width of image.
mainHeight int Height of image.
desiredMipDimension int Max dimension of desired mip.
format ImageEngineFormat Format of image.
mipOffset int Offset of desired mipmap in image.
return bool
        public static bool EnsureMipInImage(long streamLength, int mainWidth, int mainHeight, int desiredMipDimension, ImageEngineFormat format, out int mipOffset)
        {
            if (mainWidth <= desiredMipDimension && mainHeight <= desiredMipDimension)
            {
                mipOffset = 128;
                return true; // One mip only
                // TODO: DX10
            }

            int dependentDimension = mainWidth > mainHeight ? mainWidth : mainHeight;
            int mipIndex = (int)Math.Log((dependentDimension / desiredMipDimension), 2);
            if (mipIndex < -1)
                throw new InvalidDataException($"Invalid dimensions for mipmapping. Got desired: {desiredMipDimension} and dependent: {dependentDimension}");

            int requiredOffset = GetMipOffset(mipIndex, format, mainHeight, mainWidth);  // +128 for header

            // KFreon: Something wrong with the count here by 1 i.e. the estimate is 1 more than it should be
            if (format == ImageEngineFormat.DDS_ARGB)
                requiredOffset -= 2;

            mipOffset = requiredOffset;

            // Should only occur when an image has 0 or 1 mipmap.
            if (streamLength <= requiredOffset)
                return false;

            return true;
        }