Unity用CPU上下翻转Texture2D的最优解

发布时间 2023-08-07 12:01:14作者: Jason_c

将Texture2D上下翻转效率的进化史

以下数据都是基于8000x4000全景图进行对比的

1、最简单也是最先想到的,直接根据索引塞到另一个数组里,耗时:0.3061805秒

        static Color32[] FlipColors(Color32[] originalColors, int width, int height)
        {
            Color32[] flippedColors = new Color32[originalColors.Length];
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int originalIndex = y * width + x;
                    int flippedIndex = (height - y - 1) * width + x;

                    flippedColors[flippedIndex] = originalColors[originalIndex];
                }
            }
            return flippedColors;

        }

 

2、使用Array.Copy速度更快,耗时:0.1576061秒

        static Color32[] FlipColors(Color32[] originalColors, int width, int height)
        {

            for (int y = 0; y < height / 2; y++)
            {
                int topRowIndex = y * width;
                int bottomRowIndex = (height - y - 1) * width;

                // 交换顶部和底部的像素行
                Color32[] tempRow = new Color32[width];
                Array.Copy(originalColors, topRowIndex, tempRow, 0, width);
                Array.Copy(originalColors, bottomRowIndex, originalColors, topRowIndex, width);
                Array.Copy(tempRow, 0, originalColors, bottomRowIndex, width);
            }
            return originalColors;

        }

 

3、在for循环里创建数据会产生大量垃圾,可以将new循环外面,耗时:0.0847777秒

        static Color32[] FlipColors(Color32[] originalColors, int width, int height)
        {
            Color32[] tempRow = new Color32[width];
            for (int y = 0; y < height / 2; y++)
            {
                int topRowIndex = y * width;
                int bottomRowIndex = (height - y - 1) * width;

                // 交换顶部和底部的像素行
                Array.Copy(originalColors, topRowIndex, tempRow, 0, width);
                Array.Copy(originalColors, bottomRowIndex, originalColors, topRowIndex, width);
                Array.Copy(tempRow, 0, originalColors, bottomRowIndex, width);
            }
            return originalColors;
        }

 

第3种方式理论上是通过CPU翻转Texture2D的性能极限了,没有其他逻辑比他速度更快了!!!

但是,此处转折一下,打败自己的从来不是对手,而是另一个赛道的人,在GPU面前,都是渣渣,写个Shader在GPU上处理将比上述方式更快,而且也比较简单,后面有时间再一篇文章介绍

下面我们还是根据第3种方式,把其他情况的翻转完善下:

1、上下翻转,参考上述代码

2、水平翻转,