本文整理汇总了C++中MDataHandle类的典型用法代码示例。如果您正苦于以下问题:C++ MDataHandle类的具体用法?C++ MDataHandle怎么用?C++ MDataHandle使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MDataHandle类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: CHECK_MSTATUS_AND_RETURN_IT
MStatus inverseSkinCluster::deform(MDataBlock& data,
MItGeometry& itGeo,
const MMatrix& localToWorldMatrix,
unsigned int geomIndex)
{
MStatus status;
MMatrix geomMatrix;
bool updateSkinInfo;
MDataHandle hInMesh = data.inputValue( aInMesh, &status );
CHECK_MSTATUS_AND_RETURN_IT( status );
MObject oInMesh = hInMesh.asMesh();
if( oInMesh.isNull() )
return MS::kFailure;
MFnMesh inMesh = oInMesh;
inMesh.getPoints( m_meshPoints );
if( originalMeshUpdated )
{
itGeo.allPositions( pTaskData->basePoints );
originalMeshUpdated = false;
}
MDataHandle hGeomMatrix = data.inputValue( aGeomMatrix );
geomMatrix = hGeomMatrix.asMatrix();
MDataHandle hUpdateWeightList = data.inputValue( aUpdateWeightList );
updateSkinInfo = hUpdateWeightList.asBool();
MDataHandle hEnvelop = data.inputValue( envelope );
envelopValue = hEnvelop.asFloat();
pTaskData->envelop = envelopValue;
pTaskData->invEnv = 1.0f - envelopValue;
pTaskData->beforePoints = m_meshPoints;
if( updateSkinInfo )
{
MDataHandle hUpdateSkinInfoOutput = data.outputValue( aUpdateWeightList );
hUpdateSkinInfoOutput.set( false );
weightListUpdated = false;
}
if( logicalIndexArray.length() == 0 )
updateLogicalIndexArray();
MDataHandle hUpdateMatrix = data.inputValue( aUpdateMatrix );
if( hUpdateMatrix.asBool() )
{
matrixAttrUpdated = false;
matrixInfoUpdated = false;
}
MArrayDataHandle hArrMatrix = data.inputArrayValue( aMatrix );
MArrayDataHandle hArrBindPreMatrix = data.inputArrayValue( aBindPreMatrix );
updateMatrixAttribute( hArrMatrix, hArrBindPreMatrix );
if( !matrixInfoUpdated )
{
updateMatrixInfo( hArrMatrix, hArrBindPreMatrix );
}
if( !weightListUpdated )
{
pTaskData->afterPoints.setLength( m_meshPoints.length() );
pTaskData->envPoints.setLength( m_meshPoints.length() );
updateWeightList();
}
if( !matrixInfoUpdated || !weightListUpdated )
{
if( pSkinInfo->weightsArray.size() > 0 )
getWeightedMatrices( geomMatrix );
else
return MS::kFailure;
matrixInfoUpdated = true;
weightListUpdated = true;
}
if( envelopValue )
{
setThread();
MThreadPool::newParallelRegion( parallelCompute, pThread );
endThread();
itGeo.setAllPositions( pTaskData->envPoints );
}
else
{
itGeo.setAllPositions( pTaskData->basePoints );
}
return MS::kSuccess;
}
示例2: inPlug
MStatus splatDeformer::compute(const MPlug& plug, MDataBlock& data)
{
// do this if we are using an OpenMP implementation that is not the same as Maya's.
// Even if it is the same, it does no harm to make this call.
MThreadUtils::syncNumOpenMPThreads();
MStatus status = MStatus::kUnknownParameter;
if (plug.attribute() != outputGeom) {
return status;
}
unsigned int index = plug.logicalIndex();
MObject thisNode = this->thisMObject();
// get input value
MPlug inPlug(thisNode,input);
inPlug.selectAncestorLogicalIndex(index,input);
MDataHandle hInput = data.inputValue(inPlug, &status);
MCheckStatus(status, "ERROR getting input mesh\n");
// get the input geometry
MDataHandle inputData = hInput.child(inputGeom);
if (inputData.type() != MFnData::kMesh) {
printf("Incorrect input geometry type\n");
return MStatus::kFailure;
}
// get the input groupId - ignored for now...
MDataHandle hGroup = inputData.child(groupId);
unsigned int groupId = hGroup.asLong();
// get deforming mesh
MDataHandle deformData = data.inputValue(deformingMesh, &status);
MCheckStatus(status, "ERROR getting deforming mesh\n");
if (deformData.type() != MFnData::kMesh) {
printf("Incorrect deformer geometry type %d\n", deformData.type());
return MStatus::kFailure;
}
MObject dSurf = deformData.asMeshTransformed();
MFnMesh fnDeformingMesh;
fnDeformingMesh.setObject( dSurf ) ;
MDataHandle outputData = data.outputValue(plug);
outputData.copy(inputData);
if (outputData.type() != MFnData::kMesh) {
printf("Incorrect output mesh type\n");
return MStatus::kFailure;
}
MItGeometry iter(outputData, groupId, false);
// create fast intersector structure
MMeshIntersector intersector;
intersector.create(dSurf);
// get all points at once. Faster to query, and also better for
// threading than using iterator
MPointArray verts;
iter.allPositions(verts);
int nPoints = verts.length();
// use bool variable as lightweight object for failure check in loop below
bool failed = false;
MTimer timer; timer.beginTimer();
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(int i=0; i<nPoints; i++) {
// Cannot break out of an OpenMP loop, so if one of the
// intersections failed, skip the rest
if(failed) continue;
// mesh point object must be in loop-local scope to avoid race conditions
MPointOnMesh meshPoint;
// Do intersection. Need to use per-thread status value as
// MStatus has internal state and may trigger race conditions
// if set from multiple threads. Probably benign in this case,
// but worth being careful.
MStatus localStatus = intersector.getClosestPoint(verts[i], meshPoint);
if(localStatus != MStatus::kSuccess) {
// NOTE - we cannot break out of an OpenMP region, so set
// bad status and skip remaining iterations
failed = true;
continue;
}
// default OpenMP scheduling breaks traversal into large
// chunks, so low risk of false sharing here in array write.
verts[i] = meshPoint.getPoint();
}
timer.endTimer(); printf("Runtime for threaded loop %f\n", timer.elapsedTime());
// write values back onto output using fast set method on iterator
iter.setAllPositions(verts);
//.........这里部分代码省略.........
示例3: resultColor
// Compute takes two parameters: plug and data.
// - Plug is the the data value that needs to be recomputed
// - Data provides handles to all of the nodes attributes, only these
// handles should be used when performing computations.
//
MStatus inSpecular::compute( const MPlug& plug, MDataBlock& block )
{
// The plug parameter will allow us to determine which output attribute
// needs to be calculated.
//
if( plug == aOutColor || plug == aOutTransparency || plug.parent() == aOutColor || plug.parent() == aOutTransparency )
{
MStatus status;
MFloatVector resultColor( 0.0, 0.0, 0.0 );
// Get surface shading parameters from input block
//
MFloatVector& surfaceNormal = block.inputValue( aNormalCamera, &status ).asFloatVector();
CHECK_MSTATUS( status );
MFloatVector& surfaceColor = block.inputValue( aColor, &status ).asFloatVector();
CHECK_MSTATUS( status );
MFloatVector& incandescence = block.inputValue( aIncandescence, &status ).asFloatVector();
CHECK_MSTATUS( status );
float diffuseReflectivity = block.inputValue( aDiffuseReflectivity, &status ).asFloat();
CHECK_MSTATUS( status );
// float translucenceCoeff = block.inputValue( aTranslucenceCoeff,
// &status ).asFloat();
// CHECK_MSTATUS( status );
// Get light list
//
MArrayDataHandle lightData = block.inputArrayValue( aLightData, &status );
CHECK_MSTATUS( status );
int numLights = lightData.elementCount( &status );
CHECK_MSTATUS( status );
// Calculate the effect of the lights in the scene on the color
//
// Iterate through light list and get ambient/diffuse values
//
for( int count=1; count <= numLights; count++ )
{
// Get the current light out of the array
//
MDataHandle currentLight = lightData.inputValue( &status );
CHECK_MSTATUS( status );
// Get the intensity of that light
//
MFloatVector& lightIntensity = currentLight.child( aLightIntensity ).asFloatVector();
// Find ambient component
//
if ( currentLight.child( aLightAmbient ).asBool() )
{
resultColor += lightIntensity;
}
// Find diffuse component
//
if ( currentLight.child( aLightDiffuse ).asBool() )
{
MFloatVector& lightDirection = currentLight.child( aLightDirection ).asFloatVector();
float cosln = lightDirection * surfaceNormal;
if ( cosln > 0.0f )
{
resultColor += lightIntensity * ( cosln * diffuseReflectivity );
}
}
// Advance to the next light.
//
if ( count < numLights ) {
status = lightData.next();
CHECK_MSTATUS( status );
}
}
// Factor incident light with surface color and add incandescence
//
resultColor[0] = resultColor[0] * surfaceColor[0] + incandescence[0];
resultColor[1] = resultColor[1] * surfaceColor[1] + incandescence[1];
resultColor[2] = resultColor[2] * surfaceColor[2] + incandescence[2];
// Set ouput color attribute
//.........这里部分代码省略.........
示例4: resultColor
MStatus liqSurfaceNode::compute( const MPlug& plug, MDataBlock& block )
{
//CM_TRACE_FUNC("liqSurfaceNode::compute(job="<<plug.name()<<",block)");
// outColor or individual R, G, B channel
if( (plug == aOutColor) || (plug.parent() == aOutColor)||
( plug == aOutTransparency ) || (plug.parent() == aOutTransparency) )
{
//cout <<"compute... "<<endl;
// init shader
MStatus status;
MFloatVector& cColor = block.inputValue(aColor).asFloatVector();
MFloatVector& cTrans = block.inputValue(aOpacity).asFloatVector();
MFloatVector& ctex = block.inputValue(aGLPreviewTexture).asFloatVector();
// exploit maya's free openGL preview
if ( ctex != MFloatVector( -1.0, -1.0, -1.0 ) ) cColor = ctex;
//else theColor = cColor;
MFloatVector resultColor( 0.0, 0.0, 0.0 );
MFloatVector resultTrans( cTrans );
// lambert calc -------------------
bool& ignoreLights = block.inputValue( aMayaIgnoreLights, &status ).asBool();
float& Ka = block.inputValue( aMayaKa, &status ).asFloat();
float& Kd = block.inputValue( aMayaKd, &status ).asFloat();
// get surface normal
MFloatVector& surfaceNormal = block.inputValue( aNormalCamera, &status ).asFloatVector();
CHECK_MSTATUS( status );
if ( ignoreLights ) {
MFloatVector cam( 0.0, 0.0, 1.0 );
float cosln = cam * surfaceNormal;
if ( cosln > 0.0f ) {
float diff = cosln * cosln * Kd + Ka;
resultColor = diff * cColor;
}
} else {
// Get light list
MArrayDataHandle lightData = block.inputArrayValue( aLightData, &status );
CHECK_MSTATUS( status );
int numLights = lightData.elementCount( &status );
CHECK_MSTATUS( status );
// Iterate through light list and get ambient/diffuse values
for( int count=1; count <= numLights; count++ )
{
// Get the current light out of the array
MDataHandle currentLight = lightData.inputValue( &status );
CHECK_MSTATUS( status );
// Get the intensity of that light
MFloatVector& lightIntensity = currentLight.child( aLightIntensity ).asFloatVector();
// Find ambient component
if ( currentLight.child( aLightAmbient ).asBool() ) {
resultColor += lightIntensity;
}
// Find diffuse component
if ( currentLight.child( aLightDiffuse ).asBool() ) {
MFloatVector& lightDirection = currentLight.child( aLightDirection ).asFloatVector();
float cosln = lightDirection * surfaceNormal;
if ( cosln > 0.0f ) resultColor += lightIntensity * cosln * Kd ;
}
// Advance to the next light.
if ( count < numLights ) {
status = lightData.next();
CHECK_MSTATUS( status );
}
}
resultColor[0] *= cColor[0];
resultColor[1] *= cColor[1];
resultColor[2] *= cColor[2];
}
resultTrans[0] = ( 1.0 - resultTrans[0] );
resultTrans[1] = ( 1.0 - resultTrans[1] );
resultTrans[2] = ( 1.0 - resultTrans[2] );
// set ouput color attribute
MDataHandle outColorHandle = block.outputValue( aOutColor );
MFloatVector& outColor = outColorHandle.asFloatVector();
outColor = resultColor;
outColorHandle.setClean();
MDataHandle outTransHandle = block.outputValue( aOutTransparency );
//.........这里部分代码省略.........
示例5: resultColor
MStatus OnbShader::compute(const MPlug& plug, MDataBlock& block)
{
// Sanity check
if (plug != aOutColor && plug.parent() != aOutColor &&
plug != aOutTransparency && plug.parent() != aOutTransparency)
{
return MS::kUnknownParameter;
}
// Note that this currently only implements the diffuse portion of the
// shader and ignores specular. The diffuse portion is the Oren-Nayar
// computation from:
// Engel, Wolfgang et al. Programming Vertex, Geometry, and Pixel Shaders
// http://content.gpwiki.org/index.php/D3DBook:(Lighting)_Oren-Nayar
// Further extensions could be added to this compute method to include
// the intended Blinn specular component as well as ambient and
// incandescence components.
// See the VP2 fragment-based implementation in onbShaderOverride for the
// full shader.
MStatus status;
MFloatVector resultColor(0.0f, 0.0f, 0.0f);
MFloatVector resultTransparency(0.0f, 0.0f, 0.0f);
// Get surface shading parameters from input block
const MFloatVector& surfaceColor =
block.inputValue(aColor, &status).asFloatVector();
CHECK_MSTATUS(status);
const float roughness = block.inputValue(aRoughness, &status).asFloat();
CHECK_MSTATUS(status);
const MFloatVector& transparency =
block.inputValue(aTransparency, &status).asFloatVector();
CHECK_MSTATUS(status);
const MFloatVector& surfaceNormal =
block.inputValue(aNormalCamera, &status).asFloatVector();
CHECK_MSTATUS(status);
const MFloatVector& rayDirection =
block.inputValue(aRayDirection).asFloatVector();
const MFloatVector viewDirection = -rayDirection;
// Pre-compute some values that do not vary with lights
const float NV = viewDirection*surfaceNormal;
const float acosNV = acosf(NV);
const float roughnessSq = roughness*roughness;
const float A = 1.0f - 0.5f*(roughnessSq/(roughnessSq + 0.57f));
const float B = 0.45f*(roughnessSq/(roughnessSq + 0.09f));
// Get light list
MArrayDataHandle lightData = block.inputArrayValue(aLightData, &status);
CHECK_MSTATUS(status);
const int numLights = lightData.elementCount(&status);
CHECK_MSTATUS(status);
// Iterate through light list and get ambient/diffuse values
for (int count=1; count<=numLights; count++)
{
// Get the current light
MDataHandle currentLight = lightData.inputValue(&status);
CHECK_MSTATUS(status);
// Find diffuse component
if (currentLight.child(aLightDiffuse).asBool())
{
// Get the intensity and direction of that light
const MFloatVector& lightIntensity =
currentLight.child(aLightIntensity).asFloatVector();
const MFloatVector& lightDirection =
currentLight.child(aLightDirection).asFloatVector();
// Compute the diffuse factor
const float NL = lightDirection*surfaceNormal;
const float acosNL = acosf(NL);
const float alpha = std::max(acosNV, acosNL);
const float beta = std::min(acosNV, acosNL);
const float gamma =
(viewDirection - (surfaceNormal*NV)) *
(lightDirection - (surfaceNormal*NL));
const float C = sinf(alpha)*tanf(beta);
const float factor =
std::max(0.0f, NL)*(A + B*std::max(0.0f, gamma)*C);
// Add to result color
resultColor += lightIntensity*factor;
}
// Advance to the next light.
if (count < numLights)
{
status = lightData.next();
CHECK_MSTATUS(status);
}
}
// Factor incident light with surface color
resultColor[0] = resultColor[0]*surfaceColor[0];
resultColor[1] = resultColor[1]*surfaceColor[1];
resultColor[2] = resultColor[2]*surfaceColor[2];
// Set ouput color attribute
if (plug == aOutColor || plug.parent() == aOutColor)
{
//.........这里部分代码省略.........
示例6: meshFn
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVstWeldNode::compute(
const MPlug &mPlug,
MDataBlock &mDataBlock )
{
if ( mPlug == m_oaWeldOutput || mPlug == m_oaTranslate || mPlug == m_oaRotate ||
mPlug == m_oaTranslateX || mPlug == m_oaTranslateY || mPlug == m_oaTranslateZ ||
mPlug == m_oaRotateX || mPlug == m_oaRotateY || mPlug == m_oaRotateZ )
{
const MObject geoObj = mDataBlock.inputValue( m_iaWorldGeometry ).data();
if ( geoObj.apiType() == MFn::kMeshData )
{
MStatus mStatus;
MObject meshObj = mDataBlock.inputValue( m_iaWorldGeometry ).asMeshTransformed();
MFnMesh meshFn( meshObj );
MItMeshPolygon pIt( meshObj );
MPointArray facePoints;
MArrayDataHandle wiAH = mDataBlock.inputArrayValue( m_iaWeldInput );
MArrayDataHandle woAH = mDataBlock.outputArrayValue( m_oaWeldOutput, &mStatus );
MArrayDataBuilder woADB = woAH.builder( &mStatus );
const int nWeldCount = wiAH.elementCount();
for ( int i = 0; i < nWeldCount; ++i, wiAH.next() )
{
MDataHandle wiDH = wiAH.inputValue();
const MMatrix &offsetMatrix = wiDH.child( m_iaOffsetMatrix ).asMatrix();
const MMatrix &inverseParentSpace = wiDH.child( m_iaInverseParentSpace ).asMatrix();
const MEulerRotation::RotationOrder rotationOrder = static_cast< MEulerRotation::RotationOrder >( wiDH.child( m_iaRotateOrder ).asShort() );
MMatrix geoMatrix;
switch ( wiDH.child( m_iaType ).asShort() )
{
case kMeshFace:
{
const int nMeshFaceIndex = wiDH.child( m_iaInt ).asInt();
GetMeshMatrix( pIt, nMeshFaceIndex, geoMatrix );
}
break;
default:
merr << "Unknown Weld Type " << wiDH.child( m_iaType ).asShort() << std::endl;
break;
}
const int nWeldIndex = wiAH.elementIndex();
MDataHandle woDH = woADB.addElement( nWeldIndex );
MTransformationMatrix L( inverseParentSpace * offsetMatrix * geoMatrix );
woDH.child( m_oaTranslate ).set( L.getTranslation( MSpace::kWorld ) );
MEulerRotation e = L.rotation().asEulerRotation();
e.reorder( rotationOrder );
woDH.child( m_oaRotate ).set( e.asVector() );
}
}
else
{
merr << "Invalid .inputGeometry data of type: " << geoObj.apiTypeStr() << " found while computing " << mPlug.info() << std::endl;
return MS::kFailure;
}
return MS::kSuccess;
}
return MS::kUnknownParameter;
}
示例7: curveFn
MStatus ropeGenerator::compute( const MPlug& plug, MDataBlock& data )
{
MStatus status;
if ( plug == outMesh )
{
//Get Curve
MDataHandle inCurve_Hdl = data.inputValue( inCurve, &status );
if (status != MS::kSuccess ){
MGlobal::displayError( "Node ropeGenerator needs an Input Curve" );
return MS::kSuccess;
}
MObject inCurveObj = inCurve_Hdl.asNurbsCurve();
MFnNurbsCurve curveFn( inCurveObj );
//Get Attributes
int inDiv = data.inputValue( divisions ).asInt();
bool inCreateRope = data.inputValue( createRope ).asBool();
int inRopesCount = data.inputValue( ropesCount ).asInt();
int inPointsPerRope = data.inputValue( pointsPerRope ).asInt();
int inPointsCount = data.inputValue( pointsCount ).asInt();
float inRopesStrength = data.inputValue( ropesStrength ).asFloat();
float inRadius = data.inputValue( radius ).asFloat();
MRampAttribute inRadRamp( thisMObject(), taperRamp );
float inTwist = data.inputValue( twist ).asFloat();
MRampAttribute inTwistRamp( thisMObject(), twistRamp );
float inUvWidth = data.inputValue( uvWidth ).asFloat();
float inUvHeight = data.inputValue( uvHeight ).asFloat();
float inUvCapSize = data.inputValue( uvCapSize ).asFloat();
MFnMesh fnMesh;
MFnMeshData dataCreator;
MObject outMeshData;
outMeshData = dataCreator.create();
MDataHandle outputHandle = data.outputValue(outMesh);
//createBase
MIntArray faceCounts, faceConnects, uvIds;
MFloatArray uArray, vArray;
MFloatPointArray points;
faceCounts.clear();
faceConnects.clear();
points.clear();
if (inCreateRope)
inPointsCount = ( inPointsPerRope + 2 ) * inRopesCount;
int numVertices = ( inDiv + 1 ) * inPointsCount;
int numFaces = ( inPointsCount * inDiv ) + 2;
float param;
float lengPerDiv = curveFn.length() / inDiv;
PrevNormal = MVector( curveFn.normal( 0.0, MSpace::kWorld ).normal() );
float baseLeng = lengPerDiv;
float baseParamForRamp = 0;
float paramForRamp = 1.0 / float( inDiv );
float uDivNumber = inUvWidth / float( inPointsCount );
float vDivNumber = inUvHeight / float( inDiv );
for (int d = 0; d < inDiv + 1; d++)
{
if (d == 0)
{
param = 0;
faceCounts.append( inPointsCount );
for ( int i = inPointsCount - 1; i >= 0; i-- )
{
faceConnects.append( i );
}
for ( int i = 0; i < inPointsCount; i++ )
{
uvIds.append( i );
}
MFloatArray uTmpArray, vTmpArray;
if (inCreateRope)
createRopesUvs( inRopesCount, inPointsPerRope, inRopesStrength, inUvCapSize, uTmpArray, vTmpArray, 1.0 );
else
createCircleUvs( inPointsCount, inUvCapSize, uTmpArray, vTmpArray, 1.0 );
for ( int u = uTmpArray.length() - 1; u >= 0 ; u-- )
{
uArray.append( uTmpArray[u] + 1.0 );
vArray.append( vTmpArray[u] );
}
for ( int i = 0; i < inPointsCount + 1; i++ )
{
uArray.append( uDivNumber * float( i ) );
vArray.append( vDivNumber * float( d ) );
}
}else{
param = curveFn.findParamFromLength( baseLeng );
for ( int i = 0; i < inPointsCount + 1; i++ )
{
uArray.append( uDivNumber * float( i ) );
vArray.append( vDivNumber * float( d ) );
}
for ( int f = 0; f < inPointsCount; f++ )
{
faceCounts.append( 4 );
if( f == ( inPointsCount - 1 ))
{
faceConnects.append( ( f + 1 + ( d * inPointsCount ) ) - inPointsCount - inPointsCount );
faceConnects.append( ( f + 1 + ( d * inPointsCount ) - inPointsCount ) );
faceConnects.append( f + 1 + ( d * inPointsCount ) - 1 );
faceConnects.append( f + 1 + ( d * inPointsCount ) - inPointsCount - 1 );
uvIds.append( inPointsCount + (( inPointsCount + 1 ) * float( d - 1 )) + 1 + f );
//.........这里部分代码省略.........
示例8: inMeshDat
MStatus
MayaPolySmooth::compute( const MPlug& plug, MDataBlock& data ) {
MStatus status;
// Check which output attribute we have been asked to compute. If this
// node doesn't know how to compute it, we must return
// MS::kUnknownParameter.
//
if( plug == a_output ) {
bool createdSubdMesh = false;
int subdivisionLevel = data.inputValue(a_subdivisionLevels).asInt();
short stateH = data.inputValue(state).asShort();
if ((subdivisionLevel > 0) and (stateH !=1)) {
// == Retrieve input mesh ====================================
// Get attr values
MObject inMeshObj = data.inputValue(a_inputPolymesh).asMesh();
short vertBoundaryMethod = data.inputValue(a_vertBoundaryMethod).asShort();
short fvarBoundaryMethod = data.inputValue(a_fvarBoundaryMethod).asShort();
bool fvarPropCorners = data.inputValue(a_fvarPropagateCorners).asBool();
bool smoothTriangles = data.inputValue(a_smoothTriangles).asBool();
short creaseMethodVal = data.inputValue(a_creaseMethod).asShort();
// == Get Mesh Functions and Iterators ==========================
MFnMeshData inMeshDat(inMeshObj);
MFnMesh inMeshFn(inMeshObj, &status);
MCHECKERR(status, "ERROR getting inMeshFn\n");
MItMeshPolygon inMeshItPolygon(inMeshObj, &status);
MCHECKERR(status, "ERROR getting inMeshItPolygon\n");
// Convert attr values to OSD enums
OpenSubdiv::Sdc::SchemeType type = OpenSubdiv::Sdc::SCHEME_CATMARK;
//
// Create Far topology
//
OpenSubdiv::Sdc::Options options;
options.SetVtxBoundaryInterpolation(ConvertMayaVtxBoundary(vertBoundaryMethod));
options.SetFVarLinearInterpolation(ConvertMayaFVarBoundary(fvarBoundaryMethod, fvarPropCorners));
options.SetCreasingMethod(creaseMethodVal ?
OpenSubdiv::Sdc::Options::CREASE_CHAIKIN : OpenSubdiv::Sdc::Options::CREASE_UNIFORM);
options.SetTriangleSubdivision(smoothTriangles ?
OpenSubdiv::Sdc::Options::TRI_SUB_SMOOTH : OpenSubdiv::Sdc::Options::TRI_SUB_CATMARK);
float maxCreaseSharpness=0.0f;
OpenSubdiv::Far::TopologyRefiner * refiner =
gatherTopology(inMeshFn, inMeshItPolygon, type, options, &maxCreaseSharpness);
assert(refiner);
// Refine & Interpolate
refiner->RefineUniform(OpenSubdiv::Far::TopologyRefiner::UniformOptions(subdivisionLevel));
Vertex const * controlVerts =
reinterpret_cast<Vertex const *>(inMeshFn.getRawPoints(&status));
std::vector<Vertex> refinedVerts(
refiner->GetNumVerticesTotal() - refiner->GetLevel(0).GetNumVertices());
Vertex const * srcVerts = controlVerts;
Vertex * dstVerts = &refinedVerts[0];
for (int level = 1; level <= subdivisionLevel; ++level) {
OpenSubdiv::Far::PrimvarRefiner(*refiner).Interpolate(level, srcVerts, dstVerts);
srcVerts = dstVerts;
dstVerts += refiner->GetLevel(level).GetNumVertices();
}
// == Convert subdivided OpenSubdiv mesh to MFnMesh Data outputMesh =============
// Create New Mesh Data Object
MFnMeshData newMeshData;
MObject newMeshDataObj = newMeshData.create(&status);
MCHECKERR(status, "ERROR creating outputData");
// Create out mesh
status = convertToMayaMeshData(*refiner, refinedVerts, inMeshFn, newMeshDataObj);
MCHECKERR(status, "ERROR convertOsdFarToMayaMesh");
// Propagate objectGroups from inMesh to outMesh (for per-facet shading, etc)
status = createSmoothMesh_objectGroups(inMeshFn, inMeshDat,
newMeshData, subdivisionLevel, refiner->GetLevel(subdivisionLevel).GetNumFaces());
// Write to output plug
MDataHandle outMeshH = data.outputValue(a_output, &status);
MCHECKERR(status, "ERROR getting polygon data handle\n");
outMeshH.set(newMeshDataObj);
int isolation = std::min(10,(int)ceil(maxCreaseSharpness)+1);
data.outputValue(a_recommendedIsolation).set(isolation);
// == Cleanup OSD ============================================
// REVISIT: Re-add these deletes
delete refiner;
// note that the subd mesh was created (see the section below if !createdSubdMesh)
//.........这里部分代码省略.........
示例9: inputsP
// COMPUTE ======================================
MStatus gear_rollSplineKine::compute(const MPlug& plug, MDataBlock& data)
{
MStatus returnStatus;
// Error check
if (plug != output)
return MS::kUnknownParameter;
// Get inputs matrices ------------------------------
// Inputs Parent
MArrayDataHandle adh = data.inputArrayValue( ctlParent );
int count = adh.elementCount();
if (count < 1)
return MS::kFailure;
MMatrixArray inputsP(count);
for (int i = 0 ; i < count ; i++){
adh.jumpToElement(i);
inputsP[i] = adh.inputValue().asMatrix();
}
// Inputs
adh = data.inputArrayValue( inputs );
if (count != adh.elementCount())
return MS::kFailure;
MMatrixArray inputs(count);
for (int i = 0 ; i < count ; i++){
adh.jumpToElement(i);
inputs[i] = adh.inputValue().asMatrix();
}
adh = data.inputArrayValue( inputsRoll );
if (count != adh.elementCount())
return MS::kFailure;
MDoubleArray roll(adh.elementCount());
for (int i = 0 ; i < count ; i++){
adh.jumpToElement(i);
roll[i] = degrees2radians((double)adh.inputValue().asFloat());
}
// Output Parent
MDataHandle ha = data.inputValue( outputParent );
MMatrix outputParent = ha.asMatrix();
// Get inputs sliders -------------------------------
double in_u = (double)data.inputValue( u ).asFloat();
bool in_resample = data.inputValue( resample ).asBool();
int in_subdiv = data.inputValue( subdiv ).asShort();
bool in_absolute = data.inputValue( absolute ).asBool();
// Process ------------------------------------------
// Get roll, pos, tan, rot, scl
MVectorArray pos(count);
MVectorArray tan(count);
MQuaternion *rot;
rot = new MQuaternion[count];
MVectorArray scl(count);
double threeDoubles[3];
for (int i = 0 ; i < count ; i++){
MTransformationMatrix tp(inputsP[i]);
MTransformationMatrix t(inputs[i]);
pos[i] = t.getTranslation(MSpace::kWorld);
rot[i] = tp.rotation();
t.getScale(threeDoubles, MSpace::kWorld);
scl[i] = MVector(threeDoubles[0], threeDoubles[1], threeDoubles[2]);
tan[i] = MVector(threeDoubles[0] * 2.5, 0, 0).rotateBy(t.rotation());
}
// Get step and indexes
// We define between wich controlers the object is to be able to
// calculate the bezier 4 points front this 2 objects
double step = 1.0 / max( 1, count-1.0 );
int index1 = (int)min( count-2.0, in_u/step );
int index2 = index1+1;
int index1temp = index1;
int index2temp = index2;
double v = (in_u - step * double(index1)) / step;
double vtemp = v;
// calculate the bezier
MVector bezierPos;
MVector xAxis, yAxis, zAxis;
if(!in_resample){
// straight bezier solve
MVectorArray results = bezier4point(pos[index1],tan[index1],pos[index2],tan[index2],v);
bezierPos = results[0];
xAxis = results[1];
}
else if(!in_absolute){
MVectorArray presample(in_subdiv);
MVectorArray presampletan(in_subdiv);
MDoubleArray samplelen(in_subdiv);
double samplestep = 1.0 / double(in_subdiv-1);
double sampleu = samplestep;
presample[0] = pos[index1];
presampletan[0] = tan[index1];
MVector prevsample(presample[0]);
MVector diff;
//.........这里部分代码省略.........
示例10: inPlug
MStatus finalproject::compute(const MPlug& plug, MDataBlock& data)
{
// do this if we are using an OpenMP implementation that is not the same as Maya's.
// Even if it is the same, it does no harm to make this call.
MThreadUtils::syncNumOpenMPThreads();
MStatus status = MStatus::kUnknownParameter;
if (plug.attribute() != outputGeom) {
return status;
}
unsigned int index = plug.logicalIndex();
MObject thisNode = this->thisMObject();
// get input value
MPlug inPlug(thisNode,input);
inPlug.selectAncestorLogicalIndex(index,input);
MDataHandle hInput = data.inputValue(inPlug, &status);
MCheckStatus(status, "ERROR getting input mesh\n");
// get the input geometry
MDataHandle inputData = hInput.child(inputGeom);
if (inputData.type() != MFnData::kMesh) {
printf("Incorrect input geometry type\n");
return MStatus::kFailure;
}
// get the input groupId - ignored for now...
MDataHandle hGroup = inputData.child(groupId);
unsigned int groupId = hGroup.asLong();
// get deforming mesh
MDataHandle deformData = data.inputValue(deformingMesh, &status);
MCheckStatus(status, "ERROR getting deforming mesh\n");
if (deformData.type() != MFnData::kMesh) {
printf("Incorrect deformer geometry type %d\n", deformData.type());
return MStatus::kFailure;
}
MDataHandle offloadData = data.inputValue(offload, &status);
//gathers world space positions of the object and the magnet
MObject dSurf = deformData.asMeshTransformed();
MObject iSurf = inputData.asMeshTransformed();
MFnMesh fnDeformingMesh, fnInputMesh;
fnDeformingMesh.setObject( dSurf ) ;
fnInputMesh.setObject( iSurf ) ;
MDataHandle outputData = data.outputValue(plug);
outputData.copy(inputData);
if (outputData.type() != MFnData::kMesh) {
printf("Incorrect output mesh type\n");
return MStatus::kFailure;
}
MItGeometry iter(outputData, groupId, false);
// get all points at once. Faster to query, and also better for
// threading than using iterator
MPointArray objVerts;
iter.allPositions(objVerts);
int objNumPoints = objVerts.length();
MPointArray magVerts, tempverts;
fnDeformingMesh.getPoints(magVerts);
fnInputMesh.getPoints(tempverts);
int magNumPoints = magVerts.length();
double min = DBL_MAX, max = -DBL_MAX;
//finds min and max z-coordinate values to determine middle point (choice of z-axis was ours)
for (int i = 0; i < magNumPoints; i++) {
min = magVerts[i].z < min ? magVerts[i].z : min;
max = magVerts[i].z > max ? magVerts[i].z : max;
}
double middle = (min + max) / 2;
double polarity[magNumPoints];
//assigns polarity based on middle point of mesh
for (int i = 0; i < magNumPoints; i++) {
polarity[i] = magVerts[i].z > middle ? max / magVerts[i].z : -min / magVerts[i].z;
}
double* objdVerts = (double *)malloc(sizeof(double) * objNumPoints * 3);
double* magdVerts = (double *)malloc(sizeof(double) * magNumPoints * 3);
//creates handles to use attribute data
MDataHandle vecX = data.inputValue(transX, &status);
MDataHandle vecY = data.inputValue(transY, &status);
MDataHandle vecZ = data.inputValue(transZ, &status);
//gathers previously stored coordinates of the center of the object
double moveX = vecX.asFloat();
double moveY = vecY.asFloat();
double moveZ = vecZ.asFloat();
//translates object based on the position stored in the attribute values
for (int i=0; i<objNumPoints; i++) {
objdVerts[i * 3] = tempverts[i].x + moveX;
//.........这里部分代码省略.........
示例11: pdcFile
MStatus fishVizNode::compute( const MPlug& plug, MDataBlock& data )
{
MStatus status;
MObject arbitaryMesh = data.inputValue(aInMesh).asMesh();
MDoubleArray ptc_time_offset;
MDoubleArray ptc_amplitude;
MDoubleArray ptc_bend;
MDoubleArray ptc_scale;
MDoubleArray masses;
MString cacheName = data.inputValue(acachename, &status).asString();
MTime currentTime = data.inputValue(atime, &status).asTime();
cacheName = cacheName+"."+250*int(currentTime.value())+".pdc";
pdcFile* fpdc = new pdcFile();
if(fpdc->load(cacheName.asChar())==1)
{
//MGlobal::displayInfo(MString("FishViz loaded cache file: ")+cacheName);
fpdc->readPositions(ptc_positions, ptc_velocities, ptc_ups, ptc_views, ptc_time_offset, ptc_amplitude, ptc_bend, ptc_scale, masses);
}
else MGlobal::displayWarning(MString("FishViz cannot open cache file: ")+cacheName);
if(currentTime.value()!=int(currentTime.value()))
{
float delta_t = currentTime.value()-int(currentTime.value());
for(int i=0; i<fpdc->getParticleCount(); i++)
{
ptc_positions[i] += ptc_velocities[i]*delta_t/24.0f;
}
}
delete fpdc;
double flapping = zGetDoubleAttr(data, aFlapping);
double bending= zGetDoubleAttr(data, aBending);
double oscillate= zGetDoubleAttr(data, aOscillate);
double length = zGetDoubleAttr(data, aLength);
m_fish_length = length;
double frequency = zGetDoubleAttr(data, aFrequency);
unsigned num_bones = zGetIntAttr(data, aNBone);
unsigned int nptc = ptc_positions.length();
MPointArray vertices;
MATRIX44F mat44, mat_bone;
XYZ vert, front, up, side;
MDataHandle outputHandle = data.outputValue(outMesh, &status);
zCheckStatus(status, "ERROR getting polygon data handle\n");
if(m_num_fish != nptc || m_num_bone != num_bones)
{
m_num_bone = num_bones;
m_num_fish = nptc;
unsigned int vertex_count;
unsigned int face_count;
MIntArray pcounts;
MIntArray pconnect;
unsigned inmeshnv, inmeshnp;
MPointArray pinmesh;
MIntArray count_inmesh;
MIntArray connect_inmesh;
zWorks::extractMeshParams(arbitaryMesh, inmeshnv, inmeshnp, pinmesh, count_inmesh, connect_inmesh);
vertex_count = inmeshnv * nptc;
face_count = inmeshnp * nptc;
for(unsigned int i=0; i<nptc; i++)
{
// calculate the bone transformations
poseBones(length, num_bones, ptc_time_offset[i], frequency, ptc_amplitude[i], ptc_bend[i], flapping, bending, oscillate);
front.x = ptc_views[i].x;
front.y = ptc_views[i].y;
front.z = ptc_views[i].z;
up.x = ptc_ups[i].x;
up.y = ptc_ups[i].y;
up.z = ptc_ups[i].z;
side = front.cross(up);
side.normalize();
up = side.cross(front);
up.normalize();
mat44.setIdentity();
mat44.setOrientations(side, up, front);
mat44.scale(ptc_scale[i]);
mat44.setTranslation(ptc_positions[i].x, ptc_positions[i].y, ptc_positions[i].z);
for(unsigned int j=0; j<inmeshnv; j++)
{
vert.x = pinmesh[j].x;
vert.y = pinmesh[j].y;
vert.z = pinmesh[j].z;
//.........这里部分代码省略.........
示例12: CHECK_MSTATUS
MStatus stringFormat::compute (const MPlug& plug, MDataBlock& data)
{
MStatus status;
// Check that the requested recompute is one of the output values
//
if (plug == attrOutput) {
// Read the input values
//
MDataHandle inputData = data.inputValue (attrFormat, &status);
CHECK_MSTATUS( status );
MString format = inputData.asString();
// Get input data handle, use outputArrayValue since we do not
// want to evaluate all inputs, only the ones related to the
// requested multiIndex. This is for efficiency reasons.
//
MArrayDataHandle vals = data.outputArrayValue(attrValues, &status);
CHECK_MSTATUS( status );
int indx = 0;
int param;
char letter;
while ((indx = findNextMatch(format, indx, param, letter)) > 0) {
double val = 0.;
status = vals.jumpToElement(param);
if (status == MStatus::kSuccess) {
MDataHandle thisVal = vals.inputValue( &status );
if (status == MStatus::kSuccess) {
val = thisVal.asDouble();
}
}
MString replace;
bool valid = false;
switch (letter) {
case 'd': // Integer
val = floor(val+.5);
// No break here
case 'f': // Float
replace.set(val);
valid = true;
break;
case 't': // Timecode
{
const char * sign = "";
if (val<0) {
sign = "-";
val = -val;
}
int valInt = (int)(val+.5);
int sec = valInt / 24;
int frame = valInt - sec * 24;
int min = sec / 60;
sec -= min * 60;
int hour = min / 60;
min -= hour * 60;
char buffer[90];
if (hour>0)
sprintf(buffer, "%s%d:%02d:%02d.%02d",
sign, hour, min, sec, frame);
else
sprintf(buffer, "%s%02d:%02d.%02d",
sign, min, sec, frame);
replace = buffer;
}
valid = true;
break;
}
if (valid) {
format = format.substring(0, indx-2) +
replace + format.substring(indx+2, format.length()-1);
indx += replace.length() - 3;
}
}
// Store the result
//
MDataHandle output = data.outputValue(attrOutput, &status );
CHECK_MSTATUS( status );
output.set( format );
} else {
return MS::kUnknownParameter;
}
return MS::kSuccess;
}
示例13: interval
//
// DESCRIPTION:
///////////////////////////////////////////////////////
MStatus VolumeNode::compute(const MPlug& plug, MDataBlock& block )
{
if ((plug != aOutColor) && (plug.parent() != aOutColor) &&
(plug != aOutTransparency) && (plug.parent() != aOutTransparency))
return MS::kUnknownParameter;
MFloatVector& InputColor = block.inputValue( aColor ).asFloatVector();
float Distance = block.inputValue( aInputValue ).asFloat();
MFloatVector& FarCamera = block.inputValue( aFarPointC ).asFloatVector();
MFloatVector& FarObject = block.inputValue( aFarPointO ).asFloatVector();
MFloatVector& FarWorld = block.inputValue( aFarPointW ).asFloatVector();
MFloatVector& PointCam = block.inputValue( aPointC ).asFloatVector();
MFloatVector& PointObj = block.inputValue( aPointO ).asFloatVector();
MFloatVector& PointWor = block.inputValue( aPointW ).asFloatVector();
bool Camera = block.inputValue( aToggleCamera ).asBool();
bool Object = block.inputValue( aToggleObject ).asBool();
bool World = block.inputValue( aToggleWorld ).asBool();
MFloatVector interval(0.0,0.0,0.0);
if (Camera) {
interval = FarCamera - PointCam;
}
if (Object) {
interval = FarObject - PointObj;
}
if (World) {
interval = FarWorld - PointWor;
}
double value,dist;
if ((value = ((interval[0]*interval[0]) +
(interval[1]*interval[1]) +
(interval[2]*interval[2])) ))
{
dist = sqrt ( value );
}
else dist = 0.0;
MFloatVector resultColor(0.0,0.0,0.0);
if (dist <= Distance) {
resultColor[0] = InputColor[0];
resultColor[1] = InputColor[1];
resultColor[2] = InputColor[2];
}
// set ouput color attribute
MDataHandle outColorHandle = block.outputValue( aOutColor );
MFloatVector& outColor = outColorHandle.asFloatVector();
outColor = resultColor;
outColorHandle.setClean();
// set output transparency
MFloatVector transparency(resultColor[2],resultColor[2],resultColor[2]);
MDataHandle outTransHandle = block.outputValue( aOutTransparency );
MFloatVector& outTrans = outTransHandle.asFloatVector();
outTrans = transparency;
outTransHandle.setClean( );
MDataHandle outAlphaHandle = block.outputValue( aOutAlpha );
float& outAlpha = outAlphaHandle.asFloat();
outAlpha = resultColor[2];
outAlphaHandle.setClean( );
return MS::kSuccess;
}
示例14: int
MStatus meshCacheNode::compute( const MPlug& plug, MDataBlock& data )
{
MStatus stat;
MString path = data.inputValue( input ).asString();
double time = data.inputValue( frame ).asTime().value();
int minfrm = data.inputValue( aminframe ).asInt();
//int maxfrm = data.inputValue( amaxframe ).asInt();
int frmstep = data.inputValue( aframestep ).asInt();
if( time < minfrm ) time = minfrm;
int frame_lo = minfrm + int(time-minfrm)/frmstep*frmstep;
int frame_hi = frame_lo+frmstep;
char filename[256];
sprintf( filename, "%s.%d.mcf", path.asChar(), frame_lo );
FMCFMesh mesh;
if(mesh.load(filename) != 1)
{
sprintf( filename, "%s.mcf", path.asChar());
if(mesh.load(filename) != 1)
{
MGlobal::displayError( MString("Failed to open file: ") + filename );
return MS::kFailure;
}
}
int lo_n_vertex = mesh.getNumVertex();
vertexArray.clear();
vertexFArray.clear();
uArray.clear();
vArray.clear();
polygonCounts.clear();
polygonConnects.clear();
polygonUVs.clear();
for(unsigned int i = 0; i < mesh.getNumFace(); i++ )
{
polygonCounts.append( mesh.getFaceCount(i) );
}
for(unsigned int i = 0; i < mesh.getNumFaceVertex(); i++)
{
polygonConnects.append( mesh.getVertexId(i) );
polygonUVs.append( mesh.getUVId(i) );
}
XYZ tp;
for(unsigned int i = 0; i < mesh.getNumVertex(); i++)
{
mesh.getVertex(tp, i);
vertexArray.append( MPoint( tp.x, tp.y, tp.z ) );
}
for(unsigned int i = 0; i < mesh.getNumUV(); i++)
{
uArray.append( mesh.getS(i) );
vArray.append( mesh.getT(i) );
}
if( time > frame_lo )
{
sprintf( filename, "%s.%d.mcf", path.asChar(), frame_hi );
if(mesh.load(filename) != 1)
{
MGlobal::displayError( MString("Failed to open file: ") + filename );
}
else if(mesh.getNumVertex() == lo_n_vertex)
{
XYZ tp;
for(unsigned int i = 0; i < mesh.getNumVertex(); i++)
{
mesh.getVertex(tp, i);
vertexFArray.append( MPoint( tp.x, tp.y, tp.z ) );
}
double alpha = double(time-frame_lo) / (double)frmstep;
for(unsigned int i = 0; i < mesh.getNumVertex(); i++)
{
vertexArray[i] = vertexArray[i] + alpha * ( vertexFArray[i] - vertexArray[i] );
}
}
}
if( plug == outMesh )
{
MDataHandle meshh = data.outputValue(outMesh, &stat);
MFnMeshData dataCreator;
MObject outMeshData = dataCreator.create(&stat);
//.........这里部分代码省略.........
示例15: return
MStatus sweptEmitter::compute(const MPlug& plug, MDataBlock& block)
//
// Descriptions:
// Call emit emit method to generate new particles.
//
{
MStatus status;
// Determine if we are requesting the output plug for this emitter node.
//
if( !(plug == mOutput) )
return( MS::kUnknownParameter );
// Get the logical index of the element this plug refers to,
// because the node can be emitting particles into more
// than one particle shape.
//
int multiIndex = plug.logicalIndex( &status );
McheckErr(status, "ERROR in plug.logicalIndex.\n");
// Get output data arrays (position, velocity, or parentId)
// that the particle shape is holding from the previous frame.
//
MArrayDataHandle hOutArray = block.outputArrayValue(mOutput, &status);
McheckErr(status, "ERROR in hOutArray = block.outputArrayValue.\n");
// Create a builder to aid in the array construction efficiently.
//
MArrayDataBuilder bOutArray = hOutArray.builder( &status );
McheckErr(status, "ERROR in bOutArray = hOutArray.builder.\n");
// Get the appropriate data array that is being currently evaluated.
//
MDataHandle hOut = bOutArray.addElement(multiIndex, &status);
McheckErr(status, "ERROR in hOut = bOutArray.addElement.\n");
// Get the data and apply the function set.
//
MFnArrayAttrsData fnOutput;
MObject dOutput = fnOutput.create ( &status );
McheckErr(status, "ERROR in fnOutput.create.\n");
// Check if the particle object has reached it's maximum,
// hence is full. If it is full then just return with zero particles.
//
bool beenFull = isFullValue( multiIndex, block );
if( beenFull )
{
return( MS::kSuccess );
}
// Get deltaTime, currentTime and startTime.
// If deltaTime <= 0.0, or currentTime <= startTime,
// do not emit new pariticles and return.
//
MTime cT = currentTimeValue( block );
MTime sT = startTimeValue( multiIndex, block );
MTime dT = deltaTimeValue( multiIndex, block );
if( (cT <= sT) || (dT <= 0.0) )
{
// We do not emit particles before the start time,
// and do not emit particles when moving backwards in time.
//
// This code is necessary primarily the first time to
// establish the new data arrays allocated, and since we have
// already set the data array to length zero it does
// not generate any new particles.
//
hOut.set( dOutput );
block.setClean( plug );
return( MS::kSuccess );
}
// Get speed, direction vector, and inheritFactor attributes.
//
double speed = speedValue( block );
MVector dirV = directionVector( block );
double inheritFactor = inheritFactorValue( multiIndex, block );
// Get the position and velocity arrays to append new particle data.
//
MVectorArray fnOutPos = fnOutput.vectorArray("position", &status);
MVectorArray fnOutVel = fnOutput.vectorArray("velocity", &status);
// Convert deltaTime into seconds.
//
double dt = dT.as( MTime::kSeconds );
// Apply rotation to the direction vector
MVector rotatedV = useRotation ( dirV );
// position,
MVectorArray inPosAry;
// velocity
MVectorArray inVelAry;
// emission rate
MIntArray emitCountPP;
//.........这里部分代码省略.........