//
// Pre Shape Mel Script
//
global proc useArchivesRI() {
// Get the name of the shape node
string $shapeNode = `rman ctxGetObject`;
string $parents[] = `listRelatives -parent $shapeNode`;
string $tformNode = $parents[0];
  
// The node may hava a number in its name that we can use 
// to set the random number generator
int    $nodeNumber = `match "[0-9]+" $shapeNode`;    
if($nodeNumber != "") {
    seed(int($nodeNumber));
    }
// Bounding box...
float $bb_width =  `getAttr ($shapeNode + ".boundingBoxSizeX")`;
float $bb_height = `getAttr ($shapeNode + ".boundingBoxSizeY")`;
float $bb_depth =  `getAttr ($shapeNode + ".boundingBoxSizeZ")`;
  
string $attr;
$attr = `rmanGetAttrName "ua_path"`;
$attr = `rmanGetFullSharedGeometricAttrName $shapeNode $attr`;
string $ua_path = `getAttr $attr`;
  
$attr = `rmanGetAttrName "ua_mode"`;
$attr = `rmanGetFullSharedGeometricAttrName $shapeNode $attr`;
int $ua_mode = `getAttr $attr`;
  
$attr = `rmanGetAttrName "ua_offset"`;
$attr = `rmanGetFullSharedGeometricAttrName $shapeNode $attr`;
int $ua_offset = `getAttr $attr`;
  
if(size($ua_path) == 0)
    return;
//_____________________________________________________
if($ua_mode == 0) {    // Use normally
    RiReadArchive($ua_path);
    }
else 
    {
    string $dirpath = dirname($ua_path);
    string $ribs[] = `getFileList -folder $dirpath -filespec "*.rib"`;
    int    $numRibs = size($ribs);
    if($ua_mode == 1) {    // Animation
        int $f = `currentTime -q`;
        int $index = sequencer($f + $ua_offset, $numRibs) - 1;
        string $rib = $ribs[$index];
        string $fullpath = $dirpath + "/" + $rib;
        print("Aniamtion Info: using \"" + $fullpath + "\"\n");
        RiReadArchive($fullpath);
        }
    else // Random choice
        {
        int $index = rand(0, $numRibs);
        string $rib = $ribs[$index];
        string $fullpath = $dirpath + "/" + $rib;
        print("Random Choice Info: using \"" + $fullpath + "\"\n");
        RiReadArchive($fullpath);
        }
    }
// Make the proxy object "inactive"
RiAttribute "visibility" "int camera" 0;
RiAttribute "visibility" "int indirect" 0;
RiAttribute "visibility" "int transmission" 0;
}
  
//__________________________________________________________
// A utility proc that returns the archive rib number based
// on the current frame and the number of archives.
global proc int sequencer(int $frame, int $numRibs) {
    if($frame <= $numRibs)
        return $frame;
    if($frame % $numRibs == 0)
        return $numRibs;
    else
        return $frame % $numRibs;
    }