@@ -112,39 +112,36 @@ private Texture3D CreateTextureInternal()
112
112
TextureFormat texformat = SystemInfo . SupportsTextureFormat ( TextureFormat . RHalf ) ? TextureFormat . RHalf : TextureFormat . RFloat ;
113
113
Texture3D texture = new Texture3D ( dimX , dimY , dimZ , texformat , false ) ;
114
114
texture . wrapMode = TextureWrapMode . Clamp ;
115
-
115
+
116
116
int minValue = GetMinDataValue ( ) ;
117
117
int maxValue = GetMaxDataValue ( ) ;
118
118
int maxRange = maxValue - minValue ;
119
119
120
- Color [ ] cols ;
120
+ bool isHalfFloat = texformat == TextureFormat . RHalf ;
121
121
try
122
122
{
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 ) ;
124
135
}
125
136
catch ( OutOfMemoryException ex )
126
137
{
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 ) ) ;
128
143
}
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
+
148
145
texture . Apply ( ) ;
149
146
return texture ;
150
147
}
0 commit comments