Game Development Community

Divide by zero in Terraformer::getScaledGreyscale()

by Tom Spilman · in Torque Game Engine · 09/05/2006 (6:17 pm) · 1 replies

Another Div-by-zero bug i found. This time in Terraformer::getScaledGreyscale() in engine\editor\terraformer.cpp...

S32 y, x;
   U8 *rgb = bitmap->getAddress(0,0);
   for (y=blockSize-1; y >= 0; y--)
   {
      for (x=0; x < blockSize; x++)
      {
         ColorI c; // NOT INITIALIZED!
         F32 index = (src->val(wrap(x), wrap(y))-fmin) * scale;
         if (index > worldWater)
         {  // above "water"
            S32 indexLo = (S32)mFloor(index);
            S32 indexHi = (S32)mCeil(index);
            index -= indexLo;
            c.interpolate(land[indexLo], land[indexHi], index);
         }
         else if(water != 0)
         {  // below "water"
            index /= worldWater; // DIV BY ZERO!
            S32 indexLo = (S32)mFloor(index);
            S32 indexHi = (S32)mCeil(index);

The fix...

S32 y, x;
   U8 *rgb = bitmap->getAddress(0,0);
   for (y=blockSize-1; y >= 0; y--)
   {
      for (x=0; x < blockSize; x++)
      {
         ColorI c( 255, 255, 255, 255 ); // FIX!
         F32 index = (src->val(wrap(x), wrap(y))-fmin) * scale;
         if (index > worldWater)
         {  // above "water"
            S32 indexLo = (S32)mFloor(index);
            S32 indexHi = (S32)mCeil(index);
            index -= indexLo;
            c.interpolate(land[indexLo], land[indexHi], index);
         }
         else if(water != 0 && worldWater > 0) // FIX!
         {  // below "water"
            index /= worldWater;
            S32 indexLo = (S32)mFloor(index);
            S32 indexHi = (S32)mCeil(index);

Not sure if this is exactly the right behavior in this case, but it keeps NANs from being generated.

About the author

Tom is a programmer and co-owner of Sickhead Games, LLC.