/*
Save this file as "aveOpacity.cpp". Compile using Cutter.
To use this rslplugin in a shader source code file,
-----------------------------------------------------------
plugin "aveOpacity"; // or specify the full path to the .so
surface plugtest(string dataName = "")
{
Oi = Os;      // fancy opacity stuff goes here!
Ci = Oi * Cs; // fancy coloration goes here!
if(dataName != "")
    aveOpacity(Oi, area(P, "dicing"), dataName);
}
-----------------------------------------------------------
For RenderMan Studio
Put the compiled plugin into your maya/projects/RMS_rslplugin directory.
In your maya/projects/RMS_ini/slim.ini file set the ShaderCompiler pref
as follows,
SetPref ShaderCompiler "shader -I[GetEnv HOME]/maya/projects/RMS_rslplugins -I%I -%D -C %f"
or use this,
SetPref ShaderCompiler [list $RMANTREE/bin/shader \
-I[GetEnv HOME]/maya/projects/RMS_rslplugins \
-I$RMSTREE/lib/shaders \
-I$RMSTREE/lib/slim/include \
-I$RMSTREE/lib/rfm/rsl \
-C %f]
Also, add the same directory (ie. "maya/projects/RMS_rslplugins") to the 
workspace's "shader" search path.
  
Malcolm Kesson
March 2010
*/
  
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "RslPlugin.h"
  
extern "C" {
  
static FILE *file = NULL;
 
static int     count = 0;
static float totalR = 0,
             totalG = 0,
             totalB = 0;
static float totalArea = 0;
  
RixMutex *dataLock = NULL;
  
//-------------------------------------
// init
//-------------------------------------
// Called at startup
void init(RixContext *ctx) 
{ 
RixThreadUtils *lockFactory = (RixThreadUtils *)ctx->GetRixInterface(k_RixThreadUtils);
dataLock = lockFactory->NewMutex();
}
  
//-------------------------------------
// cleanup
//-------------------------------------
// Called at shutdown
void cleanup(RixContext *ctx) 
{ 
if(dataLock) 
    delete dataLock;
if(count > 0) {
    fprintf(file, "%1.3f %1.3f %1.3f\n", totalR/count,totalG/count,totalB/count);
    fprintf(file, "%1.3f\n", totalArea);
    fprintf(file, "%d\n", count);
    }
fflush(file);
fclose(file);
}
  
//-------------------------------------
// aveOpacity
//-------------------------------------
// Main function
RSLEXPORT int aveOpacity (RslContext* rslContext, int argc, const RslArg* argv[])
{
RslPointIter     colorArg(argv[1]);
RslFloatIter     floatArg(argv[2]);
RslStringIter     fileName(argv[3]);
  
dataLock->Lock();
  
if(file == NULL) {
    file = fopen(*fileName, "w");
    }
int numVals = argv[0]->NumValues();
for (int i = 0; i < numVals; ++i) {
    totalR += (*colorArg)[0];
    totalG += (*colorArg)[1];
    totalB += (*colorArg)[2];
    totalArea += *floatArg;
    ++count;
    
    ++colorArg;
    ++floatArg;
    }
dataLock->Unlock();
  
return 0;
}
  
static RslFunction myFunctions[] = {
    { "void aveOpacity(color,float,string)", aveOpacity,init,cleanup },
    NULL
    };
RSLEXPORT RslFunctionTable RslPublicFunctions = myFunctions;
};  // extern "C"