//
// Post Transform Mel Script
//
global proc meshArchivesRI() {
// Get the name of the transform node
string $tformNode = `rman ctxGetObject`;
  
// The node may hava a number in its name that we can use to set the
// random number generator
int    $nodeNumber = `match "[0-9]+" $tformNode`;
if($nodeNumber != "") {
    seed(int($nodeNumber));
    }
else
    seed(1);
  
// Bounding box is only relevant if the transform node is not a group.
string $children[] = `listRelatives -children $tformNode`;
string $shapeNode = $children[0];
float $bb_width = -1, $bb_height = -1, $bb_depth = -1;
if(size($children) == 1) {
    $bb_width =  `getAttr ($shapeNode + ".boundingBoxSizeX")`;
    $bb_height = `getAttr ($shapeNode + ".boundingBoxSizeY")`;
    $bb_depth =  `getAttr ($shapeNode + ".boundingBoxSizeZ")`;
    }
  
string $attr;
$attr = `rmanGetAttrName "ma_path"`;
string $ma_path = `getAttr($tformNode + "." + $attr)`;
  
$attr = `rmanGetAttrName "ma_radial_offset"`;
float $ma_radial_offset = `getAttr($tformNode + "." + $attr)`;
  
$attr = `rmanGetAttrName "ma_use_normals"`;
int $ma_use_normals = `getAttr($tformNode + "." + $attr)`;
  
$attr = `rmanGetAttrName "ma_jitter"`;
float $ma_jitter = `getAttr($tformNode + "." + $attr)`;
  
$attr = `rmanGetAttrName "ma_yrot"`;
float $ma_yrot = `getAttr($tformNode + "." + $attr)`;
  
$attr = `rmanGetAttrName "ma_scale"`;
float $ma_scale = `getAttr($tformNode + "." + $attr)`;
  
// To use the shader of a "Custom Shading Group that can be
// assigned to the transform node of your geometry.
RiArchiveRecord("structure", "RLF Inject SurfaceShading");
  
vector $verts[], $norms[];
getVertices($tformNode, $verts);
getNormals($tformNode, $norms);
  
if(size($verts) == 0 || size($norms) == 0)
    return;
int $n;
vector $vert, $norm;
float  $rot[], $x, $y, $z, $yangle, $xscale, $yscale, $zscale;
  
for($n = 0; $n < size($verts); $n++) {
    $vert = $verts[$n];
    $x = $vert.x * $ma_radial_offset;
    $y = $vert.y * $ma_radial_offset;
    $z = $vert.z * $ma_radial_offset;
    // Apply position jitter
    $x += rand(-$ma_jitter, $ma_jitter);
    $y += rand(-$ma_jitter, $ma_jitter);
    $z += rand(-$ma_jitter, $ma_jitter);
  
    RiAttributeBegin();
        RiTranslate($x, $y, $z);
        // Alignment to the mesh formal
        if($ma_use_normals) {
            $norm = $norms[$n];
            $rot = aimY($norm);
            RiRotate($rot[1], 0,0,1);
            RiRotate($rot[0], 1,0,0);        
            }
        // Apply Y axis rotational jitter
        if($ma_yrot > 0) {
            $yangle = rand(-$ma_yrot, $ma_yrot);
            RiRotate($yangle, 0, 1, 0);
            }
        // Ditto the randomized scaling
        $xscale = rand(1, 1 + $ma_scale);
        $yscale = rand(1, 1 + $ma_scale);
        $zscale = rand(1, 1 + $ma_scale);
        RiScale($xscale, $yscale, $zscale);
        RiReadArchive($ma_path);
    RiAttributeEnd();
    }
}