Skip to content

Commit 75ba599

Browse files
committed
Store pixel data in byte array and use SetPixelData when possible.
1 parent 070d46f commit 75ba599

File tree

1 file changed

+20
-23
lines changed

1 file changed

+20
-23
lines changed

Assets/Scripts/VolumeData/VolumeDataset.cs

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -112,39 +112,36 @@ private Texture3D CreateTextureInternal()
112112
TextureFormat texformat = SystemInfo.SupportsTextureFormat(TextureFormat.RHalf) ? TextureFormat.RHalf : TextureFormat.RFloat;
113113
Texture3D texture = new Texture3D(dimX, dimY, dimZ, texformat, false);
114114
texture.wrapMode = TextureWrapMode.Clamp;
115-
115+
116116
int minValue = GetMinDataValue();
117117
int maxValue = GetMaxDataValue();
118118
int maxRange = maxValue - minValue;
119119

120-
Color[] cols;
120+
bool isHalfFloat = texformat == TextureFormat.RHalf;
121121
try
122122
{
123-
cols = new Color[data.Length];
123+
// Create a bute array for filling the texture. Store has half (16 bit) or single (32 bit) float values.
124+
int sampleSize = isHalfFloat ? 2 : 4;
125+
byte[] bytes = new byte[data.Length * sampleSize]; // This can cause OutOfMemoryException
126+
for (int iData = 0; iData < data.Length; iData++)
127+
{
128+
float pixelValue = (float)(data[iData] - minValue) / maxRange;
129+
byte[] pixelBytes = isHalfFloat ? BitConverter.GetBytes(Mathf.FloatToHalf(pixelValue)) : BitConverter.GetBytes(pixelValue);
130+
131+
Array.Copy(pixelBytes, 0, bytes, iData * sampleSize, sampleSize);
132+
}
133+
134+
texture.SetPixelData(bytes, 0);
124135
}
125136
catch (OutOfMemoryException ex)
126137
{
127-
cols = null;
138+
Debug.LogWarning("Out of memory when creating texture. Using fallback method.");
139+
for (int x = 0; x < dimX; x++)
140+
for (int y = 0; y < dimY; y++)
141+
for (int z = 0; z < dimZ; z++)
142+
texture.SetPixel(x, y, z, new Color((float)(data[x + y * dimX + z * (dimX * dimY)] - minValue) / maxRange, 0.0f, 0.0f, 0.0f));
128143
}
129-
for (int x = 0; x < dimX; x++)
130-
{
131-
for (int y = 0; y < dimY; y++)
132-
{
133-
for (int z = 0; z < dimZ; z++)
134-
{
135-
int iData = x + y * dimX + z * (dimX * dimY);
136-
if (cols == null)
137-
{
138-
texture.SetPixel(x, y, z, new Color((float)(data[iData] - minValue) / maxRange, 0.0f, 0.0f, 0.0f));
139-
}
140-
else
141-
{
142-
cols[iData] = new Color((float)(data[iData] - minValue) / maxRange, 0.0f, 0.0f, 0.0f);
143-
}
144-
}
145-
}
146-
}
147-
if(cols != null) texture.SetPixels(cols);
144+
148145
texture.Apply();
149146
return texture;
150147
}

0 commit comments

Comments
 (0)