/* ******************************************************************************
*  Function Name : initialize
*
*  Description :  Initialize the VRAY_clusterThis object
*
*  Input Arguments : const UT_BoundingBox *
*
*  Return Value : int
*
***************************************************************************** */
int VRAY_clusterThis::initialize(const UT_BoundingBox * box)
{
   if(myVerbose > CLUSTER_MSG_INFO)
      std::cout << "VRAY_clusterThis::initialize()" << std::endl;

   void   *   handle;
   const char  *  name;
   UT_BoundingBox tbox, tvbox;
   UT_Matrix4     xform;
   UT_String      str;

   myInitTime = std::clock();
   std::time(&myInitStartTime);

   // Get the OTL parameters
   VRAY_clusterThis::getOTLParameters();

   if(myVerbose > CLUSTER_MSG_QUIET) {
         std::cout << std::endl << "VRAY_clusterThis::initialize() - Version: "
                   << MAJOR_VER << "." << MINOR_VER << "." << BUILD_VER << std::endl;
         std::cout << "VRAY_clusterThis::initialize() - Built for Houdini Version: "
                   << UT_MAJOR_VERSION << "." << UT_MINOR_VERSION << "." << UT_BUILD_VERSION_INT << std::endl;
         std::cout << "VRAY_clusterThis::initialize() - Initializing ..." <<  std::endl;
      }

//          cout << "VM_GEO_clusterThis OTL version: " <<  myOTLVersion << std::endl;
//       if(myOTLVersion != DCA_VERSION) {
//          cout << "VM_GEO_clusterThis OTL is wrong version: " <<  myOTLVersion << ", should be version: " << DCA_VERSION << ", please install correct version." << std::endl;
//          throw VRAY_clusterThis_Exception ( "VRAY_clusterThis::initialize() VM_GEO_clusterThis OTL is wrong version!", 1 );
//       }


   // Dump the user parameters to the console
   if(myVerbose == CLUSTER_MSG_DEBUG)
      VRAY_clusterThis::dumpParameters();


   // Find the geometry object to render
//   name = 0;
//   if(VRAY_Procedural::import("object", str))
//      name = str.isstring() ? (const char *)str : 0;
////   handle = VRAY_Procedural::queryObject(name);
//   handle = VRAY_Procedural::queryObject(0);
//   if(!handle) {
//         VRAYerror("%s couldn't find object '%s'", VRAY_Procedural::getClassName(), name);
//         return 0;
//      }
//   name = VRAY_Procedural::queryObjectName(handle);
//
////   std::cout << "VRAY_clusterThis::initialize() name: " << name << std::endl;
//
//   myGdp = (GU_Detail *)VRAY_Procedural::queryGeometry(handle, 0);
//   if(!myGdp) {
//         VRAYerror("%s object '%s' has no geometry", VRAY_Procedural::getClassName(), name);
//         return 0;
//      }



   handle = VRAY_Procedural::queryObject(0);
   myGdp = VRAY_Procedural::allocateGeometry();

   if(myUseGeoFile) {
         // If the file failed to load, throw an exception
         if(!(myGdp->load((const char *)mySrcGeoFname).success()))
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::initialize() - Failed to read source geometry file ", 1);

         if(myVerbose > CLUSTER_MSG_INFO)
            cout << "VRAY_clusterThis::initialize() - Successfully loaded source geo file: " << mySrcGeoFname << endl;
      }
   else {
         myGdp->copy(*VRAY_Procedural::queryGeometry(handle, 0));
         if(myVerbose > CLUSTER_MSG_INFO)
            cout << "VRAY_clusterThis::initialize() - Copied incoming geometry" << endl;
      }


   // Get the point's attribute references
   VRAY_clusterThis::getAttributeRefs(myGdp);

   // Check for required attributes
   VRAY_clusterThis::checkRequiredAttributes();

   myNumSourcePoints = (long int) myGdp->points().entries();

   VRAY_Procedural::querySurfaceShader(handle, myMaterial);
   myMaterial.harden();
//         myPointAttributes.material = myMaterial;

#ifdef DEBUG
   cout << "VRAY_clusterThis::initialize() myMaterial: " << myMaterial << std::endl;
#endif

   myObjectName = VRAY_Procedural::queryObjectName(handle);

//      cout << "VRAY_clusterThis::initialize() Object Name: " << myObjectName << std::endl;
//      cout << "VRAY_clusterThis::initialize() Root Name: " << queryRootName() << std::endl;

#ifdef DEBUG
   cout << "Geometry Samples: " << queryGeometrySamples(handle) << std::endl;
#endif


//   if(import("object:name", str)) {
//         cout << "object:name: " << str << std::endl;
//      }
//
//   if(import("object:surface", str)) {
//         cout << "object:surface: " << str << std::endl;
//      }
//
//   if(import("plane:variable", str)) {
//         cout << "plane:variable: " << str << std::endl;
//      }
//
//   if(import("image:resolution", str)) {
//         cout << "image:resolution: " << str << std::endl;
//      }
//
//   if(import("object:categories", str)) {
//         cout << "object:categories: " << str << std::endl;
//      }
//
//   if(import("object:renderpoints", str)) {
//         cout << "object:renderpoints: " << str << std::endl;
//      }



//   changeSetting("object:geo_velocityblur", "on");

//   int     vblur = 0;
//   import("object:velocityblur", &vblur, 0);
//
//   if(vblur) {
//         str = 0;
//         import("velocity", str);
//         if(str.isstring()) {
////               const char  *  name;
////               name = queryObjectName(handle);
//               VRAYwarning("%s[%s] cannot get %s",
//                           VRAY_Procedural::getClassName(), (const char *)myObjectName, " motion blur attr");
//
//            }
//      }



   myXformInverse = queryTransform(handle, 0);
   myXformInverse.invert();


   if(myPostProcess && myVDBPostProcess)
      VRAY_clusterThis::buildVDBGrids(myGdp);

   // find how much noise is being generated to help with BBox calculations
   fpreal noise_bias;

   if(myNoiseType < 4) {
         myNoise.setSeed(myPointAttributes.id);
         noise_bias = (myNoise.turbulence(myPointAttributes.myPos, myFractalDepth, myRough, myNoiseAtten) * myNoiseAmp) + 1.0;
      }
   else {
         myMersenneTwister.setSeed(myPointAttributes.id);
         noise_bias = (myMersenneTwister.frandom() * myNoiseAmp) + 1.0;
      }

#ifdef DEBUG
   cout << "VRAY_clusterThis::initialize() " << "noise_bias: " << noise_bias << endl;
#endif


   // Calculate our BBox for the incoming point cloud and add noise, radius, etc. to enlarge the BBox to
   // accomodate the instanced geometry
   // Build the geo point tree to be used for nearest neighbor caculations
   fpreal scale;
   fpreal radius;
   fpreal pscale;
   int first = 1;
   xform = myXformInverse;

   for(uint32 i = myGdp->points().entries(); i-- > 0;) {
         GEO_Point * ppt = myGdp->points()(i);

//         // Append to our list of points to be used for various tasks,
//         // like breaking up the point cloud into regular grids, etc.
//         mySRCPointList.append(i);

         if(myUsePointRadius)
            radius = static_cast<fpreal>(ppt->getValue<fpreal>(myPointAttrRefs.radius, 0));
         else
            radius = myRadius;

         pscale = static_cast<fpreal>(ppt->getValue<fpreal>(myPointAttrRefs.pscale, 0));

         if(myUsePointRadius)
            scale = (radius + noise_bias) * pscale;
         else
            scale = (myRadius + noise_bias) * pscale;

         mySRCPointTree.appendPtRadius(myGdp, ppt, radius);

         getRoughBBox(tbox, tvbox, ppt, scale, myPointAttrRefs.v, myTimeScale, xform);
         if(first) {
               myBox = tbox;
               myVelBox = tvbox;
               first = 0;
            }
         else {
               myBox.enlargeBounds(tbox);
               myVelBox.enlargeBounds(tvbox);
            }

      }

   if(first) {
         std::cout << "VRAY_clusterThis::initialize() " << getClassName() << " found no points in: " << name << std::endl;
         VRAYwarning("VRAY_clusterThis::initialize() %s found no points in %s", getClassName(), name);
         return 0;
      }


//   std::cout << "VRAY_clusterThis::initialize() *** \nmyBox: " << myBox << "myVelBox: " << myVelBox << std::endl;

   // NOTE: Enlarge the bbox another x% because we won't be able to give mantra the actual bbox size via render() method.
   // (mantra calls getBoundingBox() only once, and it's before the render() method is called by mantra).
   myBox.enlargeBounds(myBBoxFudgeFactor);
   myVelBox.enlargeBounds(myBBoxFudgeFactor);

//   myBox.enlargeFloats();
//   myVelBox.enlargeFloats();

   for(int i = 0; i < 3; i++)
      for(int j = 0; j < 2; j++) {
            if(myBox.vals[i][j] <= CLUSTER_BBOX_MIN) {
//            if(SYSisNan(myBox.vals[i][j])) {
//            if(myBox.vals[i][j] <= std::numeric_limits<float>::min()) {
                  myBox.vals[i][j] = CLUSTER_BBOX_MIN;
                  if(myVerbose == CLUSTER_MSG_DEBUG)
                     std::cout << "VRAY_clusterThis::initialize() found NAN: " << myBox.vals[i][j] << std::endl;
               }
         }


   if(myVerbose == CLUSTER_MSG_DEBUG)
      std::cout << "VRAY_clusterThis::initialize()\nmyBox: " << myBox << "myVelBox: " << myVelBox << std::endl;


   if(box) {
         if(myPointAttrRefs.v.isValid()) {
               if(testClampBox(myBox, *box) || testClampBox(myVelBox, *box))
                  VRAYwarning("%s[%s] cannot render a partial box %s", getClassName(), name, "with motion blur");
               std::cout << "VRAY_clusterThis::initialize() " << getClassName() << " WARNING: cannot render a partial box " << name << std::endl;
            }
         else {
               clampBox(myBox, *box);
               clampBox(myVelBox, *box);
            }
      }

//   std::cout << "VRAY_clusterThis::initialize() 3 \nmyBox: " << myBox << "myVelBox: " << myVelBox << std::endl;
//   if(box) {
//         std::cout << "VRAY_clusterThis::initialize() box min: " << box->xmin() << " " << box->ymin() << " " << box->zmin() << std::endl;
//         std::cout << "VRAY_clusterThis::initialize() box max: " << box->xmax() << " " << box->ymax() << " " << box->zmax() << std::endl;
//      }


   myPointTreeMemUsage = mySRCPointTree.getMemoryUsage();

   if(myVerbose == CLUSTER_MSG_DEBUG)
      std::cout << "VRAY_clusterThis::initialize() myPointTreeMemUsage: " << myPointTreeMemUsage << std::endl;


   std::time(&myInitEndTime);
   myInitExecTime = std::clock() - myInitTime;
   cout << "VRAY_clusterThis::initialize() " << "myInitExecTime: " << myInitExecTime << endl;


   return 1;
}
/* ******************************************************************************
*  Function Name : render()
*
*  Description :   Render VRAY_clusterThis object
*
*  Input Arguments : None
*
*  Return Value : None
*
***************************************************************************** */
void VRAY_clusterThis::render()
{
   GU_Detail * gdp, *inst_gdp, *mb_gdp, *file_gdp;
   GEO_Point * ppt;

//   GEO_AttributeHandle attrHandleVelocity, attrHandleForce, attrHandleVorticity, attrHandleNormal, attrHandleNumNeighbors,
//   attrHandleTextureUV, attrHandleMass, attrHandleAge, attrHandleTemperature, attrHandleID,
//   attrHandleDensity, attrHandleViscosity, attrHandlePressure, attrHandlePscale;

   long int point_num = 0;
   static bool rendered = false;

   if(myVerbose > CLUSTER_MSG_QUIET) {
         std::cout << "VRAY_clusterThis::render() - Version: " << DCA_VERSION << std::endl;
         std::cout << "VRAY_clusterThis::render() - Built for Houdini Version: " << UT_MAJOR_VERSION
                   << "." << UT_MINOR_VERSION << "." << UT_BUILD_VERSION_INT << std::endl;
         std::cout << "VRAY_clusterThis::render() - Instancing ..." <<  endl;
      }


   try {

//          cout << "VM_GEO_clusterThis OTL version: " <<  myOTLVersion << endl;

//       if(myOTLVersion != DCA_VERSION) {
//          cout << "VM_GEO_clusterThis OTL is wrong version: " <<  myOTLVersion << ", should be version: " << DCA_VERSION << ", please install correct version." << endl;
//          throw VRAY_clusterThis_Exception ( "VRAY_clusterThis::render() VM_GEO_clusterThis OTL is wrong version!", 1 );
//       }


         if(!rendered || !myUseTempFile) {

               void * handle = VRAY_Procedural::queryObject(0);
               gdp = VRAY_Procedural::allocateGeometry();

               if(myUseGeoFile) {
                     // If the file failed to load, throw an exception
                     if(!(gdp->load((const char *)mySrcGeoFname).success()))
                        throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() - Failed to read source geometry file ", 1);

                     if(myVerbose > CLUSTER_MSG_INFO)
                        cout << "VRAY_clusterThis::render() - Successfully loaded source geo file: " << mySrcGeoFname << endl;
                  }
               else {
                     gdp->copy(*VRAY_Procedural::queryGeometry(handle, 0));
                     if(myVerbose > CLUSTER_MSG_INFO)
                        cout << "VRAY_clusterThis::render() - Copied incoming geometry" << endl;
                  }


               gdp->getBBox(&myBox);

//               std::cout << "VRAY_clusterThis::render() - gdp->getBBox(&myBox): " << myBox << std::endl;

               VRAY_Procedural::querySurfaceShader(handle, myMaterial);
               myMaterial.harden();
//         myPointAttributes.material = myMaterial;

//         const char **        getSParm (int token) const
//         cout << "VRAY_clusterThis::render() getSParm: " << *getSParm (0) << endl;


#ifdef DEBUG
               cout << "VRAY_clusterThis::render() myMaterial: " << myMaterial << endl;
#endif

               myLOD = getLevelOfDetail(myBox);
               if(myVerbose > CLUSTER_MSG_INFO)
                  cout << "VRAY_clusterThis::render() myLOD: " << myLOD << endl;


               // Get the number if points of the incoming geometery, calculate an interval for reporting the status of the instancing to the user
               long int num_points = (long int) gdp->points().entries();
               long int stat_interval = (long int)(num_points * 0.10) + 1;

               if(myVerbose > CLUSTER_MSG_QUIET)
                  cout << "VRAY_clusterThis::render() Number of points of incoming geometry: " << num_points << endl;

               myObjectName = VRAY_Procedural::queryObjectName(handle);

//      cout << "VRAY_clusterThis::render() Object Name: " << myObjectName << endl;
//      cout << "VRAY_clusterThis::render() Root Name: " << queryRootName() << endl;

// DEBUG stuff ...

//   changeSetting("object:geo_velocityblur", "on");

               UT_String      str;
               int     vblur = 0;
               import("object:velocityblur", &vblur, 0);

               if(vblur) {
                     str = 0;
                     import("velocity", str);
                     if(str.isstring()) {
//               const char  *  name;
//               name = queryObjectName(handle);
                           VRAYwarning("%s[%s] cannot get %s",
                                       VRAY_Procedural::getClassName(), (const char *)myObjectName, " motion blur attr");

                        }
                  }


               myXformInverse = queryTransform(handle, 0);
               myXformInverse.invert();




#ifdef DEBUG
               cout << "Geometry Samples: " << queryGeometrySamples(handle) << endl;
// cout << "scale: " << getFParm ( "scale" ) << endl;
#endif

               // Dump the user parameters to the console
               if(myVerbose == CLUSTER_MSG_DEBUG)
                  VRAY_clusterThis::dumpParameters();

               switch(myMethod) {
                     case CLUSTER_INSTANCE_NOW:
                        inst_gdp = VRAY_Procedural::allocateGeometry();
                        if(myDoMotionBlur == CLUSTER_MB_DEFORMATION)
                           mb_gdp = VRAY_Procedural::allocateGeometry();
                        if(myVerbose > CLUSTER_MSG_QUIET)
                           cout << "VRAY_clusterThis::render() - Using \"instance all the geometry at once\" method" << endl;
                        break;
                     case CLUSTER_INSTANCE_DEFERRED:
                        if(myVerbose > CLUSTER_MSG_QUIET)
                           cout << "VRAY_clusterThis::render() - Using \"addProcedural()\" method" << endl;
                        break;
                  }

               rendered = true;

               // Get the point's attribute offsets
               VRAY_clusterThis::getAttributeOffsets(gdp);

               // Check for required attributes
               VRAY_clusterThis::checkRequiredAttributes();

               // Check for weight attribute if the user wants metaballs
               if((myPrimType == CLUSTER_PRIM_METABALL) && (myPointAttrOffsets.weight.isInvalid())) {

                     cout << "Incoming points must have weight attribute if instancing metaballs! Throwing exception ..." << endl;
                     throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() Incoming points must have weight attribute if instancing metaballs!", 1);
                  }


               if(myPrimType == CLUSTER_FILE) {
                     file_gdp = VRAY_Procedural::allocateGeometry();
                     int file_load_stat = VRAY_clusterThis::preLoadGeoFile(file_gdp);

                     if(!file_load_stat) {
//                           myFileGDP = file_gdp;
                           if(myVerbose > CLUSTER_MSG_INFO)
                              cout << "VRAY_clusterThis::render() Successfully loaded geometry file: " << myGeoFile << endl;
                        }
                     else {
                           throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() Failed to load geometry file ", 1);
                        }
                  }

               // init some vars ...
               myPointAttributes.Cd = (UT_Vector3(1, 1, 1));
               myPointAttributes.v = (UT_Vector3(0, 0, 0));
               myPointAttributes.N = (UT_Vector3(0, 1, 0));
               myPointAttributes.Alpha = 1.0;
               myPointAttributes.pscale = 1.0;
               myPointAttributes.id = 0;

               myNoise.initialize(myNoiseSeed, myNoiseType);

               // Create the attribute "offsets" for the geometry to be instanced
               VRAY_clusterThis::createAttributeOffsets(inst_gdp, mb_gdp);

//changeSetting("surface", "constant Cd ( 1 0 0 )", "object");


               fpreal theta = (2.0 * M_PI) / myNumCopies;
               myInstanceNum = 0;

               if(myCVEX_Exec_pre) {
                     if(myVerbose > CLUSTER_MSG_INFO)
                        cout << "VRAY_clusterThis::render() Executing Pre Process CVEX code" << endl;
                     VRAY_clusterThis::runCVEX(gdp, gdp, myCVEXFname_pre, CLUSTER_CVEX_POINT);
                  }

               /// For each point of the incoming geometry
               GA_FOR_ALL_GPOINTS(gdp, ppt) {
                  myPointAttributes.myPos = ppt->getPos();

                  // get the point's attributes
                  VRAY_clusterThis::getAttributes(ppt, gdp);

#ifdef DEBUG
                  cout << "VRAY_clusterThis::render() " << "theta: " << theta << endl;
#endif

                  uint seed = 37;
                  fpreal dice;
                  bool skip = false;

                  if((myPrimType != CLUSTER_PRIM_CURVE) ||
                        ((myMethod == CLUSTER_INSTANCE_DEFERRED && (myPrimType == CLUSTER_PRIM_CURVE)))) {


                        // For each point, make a number of copies of and recurse a number of times for each copy ...
                        for(int copyNum = 0; copyNum < myNumCopies; copyNum++) {
                              for(int recursionNum = 0; recursionNum < myRecursion; recursionNum++) {

                                    // generate random number to determine to instance or not

                                    dice = SYSfastRandom(seed);
                                    (dice > myBirthProb)?skip = true:skip = false;
//                  cout << dice << " " << skip << endl;
                                    seed = uint(dice * 100);

                                    // Calculate the position for the next instanced object ...
                                    VRAY_clusterThis::calculateNewPosition(theta, copyNum, recursionNum);

                                    if(!skip) {

                                          // Instance an object ...
                                          switch(myMethod) {
                                                   // For the "create all geometry at once" method, instance the object now ...
                                                case CLUSTER_INSTANCE_NOW:
                                                   // Create a primitive based upon user's selection
                                                   // TODO: can later be driven by a point attribute
                                                   switch(myPrimType) {
                                                         case CLUSTER_POINT:
                                                            VRAY_clusterThis::instancePoint(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_SPHERE:
                                                            VRAY_clusterThis::instanceSphere(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_CUBE:
                                                            VRAY_clusterThis::instanceCube(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_GRID:
                                                            VRAY_clusterThis::instanceGrid(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_TUBE:
                                                            VRAY_clusterThis::instanceTube(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_CIRCLE:
                                                            VRAY_clusterThis::instanceCircle(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_METABALL:
                                                            VRAY_clusterThis::instanceMetaball(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_FILE:
                                                            VRAY_clusterThis::instanceFile(file_gdp, inst_gdp, mb_gdp);
                                                            break;
                                                            // In case a instance type comes through that's not "legal", throw exception
                                                         default:
                                                            throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() Illegal instance type, exiting ...", 1);
                                                            break;
                                                      }
                                                   break;

                                                   // For the "deferred instance" method, add the procedural now ...
                                                case CLUSTER_INSTANCE_DEFERRED:
                                                   VRAY_Procedural::openProceduralObject();
                                                   VRAY_clusterThisChild * child = new VRAY_clusterThisChild::VRAY_clusterThisChild(this);
                                                   VRAY_Procedural::addProcedural(child);
                                                   VRAY_Procedural::changeSetting("object:geo_velocityblur", "on");
                                                   VRAY_Procedural::closeObject();
//changeSetting("surface", "constant Cd ( 1 0 0 )", "object");
//   changeSetting("object:geo_velocityblur", "on");

                                                   break;
                                             }

                                          myInstanceNum++;

#ifdef DEBUG
                                          cout << "VRAY_clusterThis::render() - myInstanceNum: " << myInstanceNum << std::endl;
#endif
                                       }

                                 } // for number of recursions ...
                           } // for number of copies ...

                     }

                  // User wants a curve instanced on this point
                  if((myPrimType == CLUSTER_PRIM_CURVE) && (myMethod == CLUSTER_INSTANCE_NOW) && (!skip))
                     VRAY_clusterThis::instanceCurve(inst_gdp, mb_gdp, theta, point_num);

                  // Increment our point counter
                  point_num++;

                  // Print out stats to the console
                  if(myVerbose > CLUSTER_MSG_INFO && (myPrimType != CLUSTER_PRIM_CURVE))
                     if((long int)(point_num % stat_interval) == 0)
                        cout << "VRAY_clusterThis::render() Number of points processed: " << point_num << " Number of instances: " << myInstanceNum << endl;

               } // for all points ...


               if(myVerbose > CLUSTER_MSG_QUIET)
                  if(myMethod == CLUSTER_INSTANCE_NOW)
                     if(myDoMotionBlur == CLUSTER_MB_DEFORMATION)
                        cout << "VRAY_clusterThis::render() - Memory usage(MB): " <<
                             (fpreal)(inst_gdp->getMemoryUsage() + mb_gdp->getMemoryUsage() / (1024.0 * 1024.0)) << endl;
                     else
                        cout << "VRAY_clusterThis::render() - Memory usage(MB): " <<
                             (fpreal)(inst_gdp->getMemoryUsage() / (1024.0 * 1024.0)) << endl;

               // If the "instance all the geo at once method" is used, add the the instanced geo for mantra to render ...
               switch(myMethod) {
                     case CLUSTER_INSTANCE_NOW:

                        if(myCVEX_Exec_post) {
                              if(myVerbose > CLUSTER_MSG_INFO)
                                 cout << "VRAY_clusterThis::render() Executing Post Process CVEX code" << endl;
                              VRAY_clusterThis::runCVEX(inst_gdp, mb_gdp, myCVEXFname_post, CLUSTER_CVEX_POINT);
                           }
                        VRAY_Procedural::openGeometryObject();
                        VRAY_Procedural::addGeometry(inst_gdp, 0.0);

                        if(myDoMotionBlur == CLUSTER_MB_VELOCITY)
                           VRAY_Procedural::addVelocityBlurGeometry(inst_gdp, myShutter, myShutter2);

// float    addVelocityBlurGeometry (GU_Detail *gdp, fpreal pre_blur, fpreal post_blur, const char *velocity_attribute="v")

                        if(myDoMotionBlur == CLUSTER_MB_DEFORMATION)
                           VRAY_Procedural::addGeometry(mb_gdp, myShutter);

                        VRAY_Procedural::setComputeN(1);
//                        setSurface(myMaterial);
                        VRAY_Procedural::closeObject();

                        break;
                     case CLUSTER_INSTANCE_DEFERRED:
                        break;
                  }

               if(myVerbose > CLUSTER_MSG_QUIET && (myPrimType != CLUSTER_PRIM_CURVE))
                  cout << "VRAY_clusterThis::render() Total number of instances: " << myInstanceNum << endl;

               // Save the geo to temp location so it doesn't have to be regenerated for a deep shadow pass, etc.
               if(myMethod == CLUSTER_INSTANCE_NOW && myUseTempFile) {
                     ofstream myGeoStream;
                     // myGeoStream.open("/tmp/thisGeo.bgeo");
                     myGeoStream.open((const char *)myTempFname, ios_base::binary);
                     UT_Options myOptions;
                     inst_gdp->save(myGeoStream, 1, &myOptions);
                     myGeoStream.flush();
                     myGeoStream.close();
                     if(myVerbose > CLUSTER_MSG_QUIET)
                        cout << "VRAY_clusterThis::render() - Saved geometry to temp file: " << myTempFname << endl;
                  }

               if(myPrimType == CLUSTER_FILE)
                  VRAY_Procedural::freeGeometry(file_gdp);

               // We're done, free the original geometry
               VRAY_Procedural::freeGeometry(gdp);

            } /// if (rendered) ...