Skip to content

Commit

Permalink
[ME] Fix mipmap calculation in WebP (#268)
Browse files Browse the repository at this point in the history
  • Loading branch information
RikkiBalboa authored Jun 19, 2024
1 parent ca4757e commit b67836c
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/Shared.TextureContainer/WebP/Texture2DExt.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
//https://github.com/octo-code/webp-unity3d
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using UnityEngine;

using WebP.Extern;

namespace WebP
Expand Down Expand Up @@ -112,13 +108,8 @@ public static unsafe byte[] LoadRGBAFromWebP(byte[] lData, ref int lWidth, ref i
{
scalingFunction(ref lWidth, ref lHeight);
}

// If mipmaps are requested we need to create 1/3 more memory for the mipmaps to be generated in.
int numBytesRequired = lWidth * lHeight * 4;
if (lMipmaps)
{
numBytesRequired = Mathf.CeilToInt((numBytesRequired * 4.0f) / 3.0f);
}

int numBytesRequired = CalculateTextureBytes(lWidth, lHeight, lMipmaps);

lRawData = new byte[numBytesRequired];
fixed (byte* lRawDataPtr = lRawData)
Expand Down Expand Up @@ -276,5 +267,22 @@ public static unsafe byte[] EncodeToWebP(this Texture2D lTexture2D, float lQuali

return lOutputBuffer;
}

internal static int CalculateTextureBytes(int width, int height, bool mipmap)
{
int bytes = width * height * 4;

if (!mipmap)
return bytes;

while (width > 1 || height > 1)
{
width = (width + 1) >> 1;
height = (height + 1) >> 1;
bytes += width * height * 4;
}

return bytes;
}
}
}

0 comments on commit b67836c

Please sign in to comment.