MStatus sgCurveEditBrush_context::getShapeNode( MDagPath& path )
{
    MStatus status;

    if ( path.apiType() == MFn::kNurbsCurve )
    {
        return MS::kSuccess;
    }

    unsigned int numShapes;
    status = path.numberOfShapesDirectlyBelow( numShapes );
    CHECK_MSTATUS_AND_RETURN_IT( status );

    for ( unsigned int i = 0; i < numShapes; ++i )
    {
        status = path.extendToShapeDirectlyBelow( i );
        CHECK_MSTATUS_AND_RETURN_IT( status );

        if ( !path.hasFn( MFn::kNurbsCurve ) )
        {
            path.pop();
            continue;
        }

        MFnDagNode fnNode( path, &status );
        CHECK_MSTATUS_AND_RETURN_IT( status );
        if ( !fnNode.isIntermediateObject() )
        {
            return MS::kSuccess;
        }
        path.pop();
    }

    return MS::kFailure;
}
Exemplo n.º 2
0
IECore::SceneInterfacePtr MayaScene::retrieveChild( const Name &name, MissingBehaviour missingBehaviour ) const
{
	tbb::mutex::scoped_lock l( s_mutex );
	
	if( m_dagPath.length() == 0 && !m_isRoot )
	{
		throw Exception( "MayaScene::retrieveChild: Dag path no longer exists!" );
	}
	
	MSelectionList sel;
	sel.add( m_dagPath.fullPathName() + "|" + std::string( name ).c_str() );
	
	MDagPath path;
	MStatus st = sel.getDagPath( 0, path );
	
	if( !path.hasFn( MFn::kTransform ) )
	{
		if( missingBehaviour == SceneInterface::ThrowIfMissing )
		{
			throw Exception( "MayaScene::retrieveChild: Couldn't find transform at specified path " + std::string( path.fullPathName().asChar() ) );
		}
		return 0;
	}
	
	return duplicate( path );
}
Exemplo n.º 3
0
MStatus recoverVisibleCmd::doIt(const MArgList&)
{
	MStatus status;
	MItDag dagItr(MItDag::kDepthFirst, MFn::kInvalid,&status);
	if(status!=MS::kSuccess){MGlobal::displayError(" Failure in DAG iterator");return status;}
	for(;!dagItr.isDone();dagItr.next())
	{
		MDagPath dagPath;
		status = dagItr.getPath(dagPath);
		if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting path");return status;}
		MFnDagNode dagNode(dagPath,&status);
		if(dagNode.isIntermediateObject())continue;
		if(!dagPath.hasFn(MFn::kDependencyNode))continue;

		MObject mObj=dagNode.object(&status);
		if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting object");return status;}

		//getParticle
		MFnDependencyNode fnNode(mObj, &status);
		if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting dependency node");return status;}
		if(fnNode.typeId() == OParticleNode::typeId) MPlug(mObj, OParticleNode::isVisible).setValue(true);
		if(fnNode.typeId() == edgeNode::typeId) MPlug(mObj, edgeNode::isVisible).setValue(true);
			
		
	}


	return status;
}
Exemplo n.º 4
0
MStatus GetShapeNode(MDagPath& path, bool intermediate) {
  MStatus status;

  if (IsShapeNode(path)) {
    // Start at the transform so we can honor the intermediate flag.
    path.pop();
  }

  if (path.hasFn(MFn::kTransform)) {
    unsigned int shapeCount = path.childCount();

    for (unsigned int i = 0; i < shapeCount; ++i) {
      status = path.push(path.child(i));
      CHECK_MSTATUS_AND_RETURN_IT(status);
      if (!IsShapeNode(path)) {
        path.pop();
        continue;
      }

      MFnDagNode fnNode(path, &status);
      CHECK_MSTATUS_AND_RETURN_IT(status);
      if ((!fnNode.isIntermediateObject() && !intermediate) ||
          (fnNode.isIntermediateObject() && intermediate)) {
        return MS::kSuccess;
      }
      // Go to the next shape
      path.pop();
    }
  }

  // No valid shape node found.
  return MS::kFailure;
}
Exemplo n.º 5
0
SceneInterfacePtr MayaScene::retrieveScene( const Path &path, MissingBehaviour missingBehaviour ) const
{
	tbb::mutex::scoped_lock l( s_mutex );
	
	if( path.size() == 0 )
	{
		MItDag it;
		MDagPath rootPath;
		it.getPath( rootPath );
		return duplicate( rootPath, true );
	}
	
	MString pathName;
	
	for( Path::const_iterator it=path.begin(); it != path.end(); ++it )
	{
		pathName += "|";
		pathName += std::string( *it ).c_str();
	}
	
	MSelectionList sel;
	MStatus st = sel.add( pathName );
	if( !st )
	{
		if( missingBehaviour == SceneInterface::ThrowIfMissing )
		{
			std::string pathName;
			for( size_t i = 0; i < path.size(); ++i )
			{
				pathName += std::string( path[i] ) + "/";
			}
			
			throw Exception( "MayaScene::retrieveScene: Couldn't find transform at specified path " + pathName );
		}
		return 0;
	}
	
	MDagPath dagPath;
	sel.getDagPath( 0, dagPath );
	
	if( dagPath.hasFn( MFn::kTransform ) )
	{
		return duplicate( dagPath );
	}
	else
	{
		if( missingBehaviour == SceneInterface::ThrowIfMissing )
		{
			std::string pathName;
			for( size_t i = 0; i < path.size(); ++i )
			{
				pathName += std::string( path[i] ) + "/";
			}
			
			throw Exception( "MayaScene::retrieveScene: Couldn't find transform at specified path " + pathName );
		}
		return 0;
	}
	
}
Exemplo n.º 6
0
MStatus radiusCmd::doIt(const MArgList&args)
{
	MStatus status=MStatus::kSuccess;

	MArgDatabase argData(syntax(),args,&status);
	if(argData.isFlagSet(rFlag))argData.getFlagArgument(rFlag,0,radius);

	MItDag dagItr(MItDag::kDepthFirst, MFn::kInvalid,&status);
	if(status!=MS::kSuccess){MGlobal::displayError(" Failure in DAG iterator");return status;}
	for(;!dagItr.isDone();dagItr.next())
	{
		MDagPath dagPath;
		status = dagItr.getPath(dagPath);
		if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting path");return status;}
		MFnDagNode dagNode(dagPath,&status);
		if(dagNode.isIntermediateObject())continue;
		if(!dagPath.hasFn(MFn::kDependencyNode))continue;

		MObject mObj=dagNode.object(&status);
		if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting object");return status;}

		//getParticle
		MFnDependencyNode fnNode(mObj, &status);
		if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting dependency node");return status;}
		if(fnNode.typeId() == OParticleNode::typeId) MPlug(mObj, OParticleNode::radius).setValue(radius);
		
	}


	return status;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVsSkinnerCmd::IsSkinnerNode(
	const MDagPath &iDagPath )
{
	if ( iDagPath.hasFn( MFn::kPluginShape ) && MFnDagNode( iDagPath ).typeName() == "vsSkinner" )
		return MS::kSuccess;

	return MS::kFailure;
}
Exemplo n.º 8
0
MStatus twistSurf()
{
	MStatus status;

	cout << ">>>> Start twist routine <<<<" << endl;

	MString	surface1("surface1");
	MGlobal::selectByName(surface1, MGlobal::kReplaceList);

	// Create an iterator for the active selection list
	//
	MSelectionList slist;
	MGlobal::getActiveSelectionList( slist );
	MItSelectionList iter( slist );

	if (iter.isDone()) {
		cerr << "Nothing selected\n";
		return MS::kFailure;
	}

	MDagPath objectPath;
	MObject component;

	for ( ; !iter.isDone(); iter.next() ) {
		status = iter.getDagPath( objectPath, component );

		if (objectPath.hasFn(MFn::kNurbsSurface))
			status = twistNurbsSurface(objectPath, component);
		else if (objectPath.hasFn(MFn::kMesh))
			status = twistPolygon(objectPath, component);
		else {
			cerr << "Selected object is not a NURBS surface or a polygon\n";
			return MS::kFailure;
		}
	}

	if ( status ) {
		cout << ">>>> Twist Successfull <<<<\n";
	} else {
		cout << ">>>> Twist Failed <<<<\n";
	}

	return status;
}
Exemplo n.º 9
0
//-----------------------------------------------------------------------------
// Adds a color set to the input history of the passed mesh
//-----------------------------------------------------------------------------
MObject ValveMaya::AddColorSetToMesh(
	const MString &colorSetName,
	const MDagPath &mDagPath,
	MDagModifier &mDagModifier )
{
	if ( !mDagPath.hasFn( MFn::kMesh ) )
		return MObject::kNullObj;

	MFnMesh meshFn( mDagPath );
	MString uniqueColorSetName;

	{
		MStringArray colorSetNames;
		meshFn.getColorSetNames( colorSetNames );
		const uint nColorSets( colorSetNames.length() );
		for ( int i( 0 ); uniqueColorSetName.length() == 0; ++i )
		{
			uniqueColorSetName = colorSetName;
			if ( i > 0 )
			{
				uniqueColorSetName += i;
			}
			for ( uint j( 0U ); j != nColorSets; ++j )
			{
				if ( uniqueColorSetName == colorSetNames[ j ] )
				{
					uniqueColorSetName.clear();
					break;
				}
			}
		}
	}

	// Create a 'createColorSet' node
	MObject ccsObj( mDagModifier.MDGModifier::createNode( "createColorSet" ) );
	mDagModifier.doIt();
	const MFnDependencyNode ccsFn( ccsObj );
	MPlug csnP( ccsFn.findPlug( "colorSetName" ) );
	csnP.setValue( uniqueColorSetName );

	// Insert it in the history of the mesh
	MPlug inMeshP( meshFn.findPlug( "inMesh" ) );
	MPlugArray mPlugArray;
	if ( inMeshP.connectedTo( mPlugArray, true, false ) && mPlugArray.length() )
	{
		mDagModifier.disconnect( mPlugArray[ 0 ], inMeshP );
		mDagModifier.connect( mPlugArray[ 0 ], ccsFn.findPlug( "inputGeometry" ) );
	}

	mDagModifier.connect( ccsFn.findPlug( "outputGeometry" ), inMeshP );
	mDagModifier.doIt();

	return ccsObj;
}
Exemplo n.º 10
0
MStatus PluginTestUserOperation::execute(const MHWRender::MDrawContext & drawContext)
{
	//return MStatus::kSuccess;
	M3dView view;
	if(M3dView::getM3dViewFromModelPanel(panelName, view) == MStatus::kSuccess)
	{
		// Get the current viewport and scale it relative to that
		//
		int targetW, targetH;
		drawContext.getRenderTargetSize(targetW, targetH);

		// Some user drawing of scene bounding boxes
		//
		MDagPath cameraPath;
		MFnCamera fnCamera;
		view.getCamera(cameraPath);
		MMatrix m3dViewProjection, m3dViewModelView;
		view.projectionMatrix(m3dViewProjection);
		view.modelViewMatrix(m3dViewModelView);
		MFloatMatrix m3dFloatViewProjection(m3dViewProjection.matrix);
		MFloatMatrix m3dFloatViewModelView(m3dViewModelView.matrix);
		MFloatMatrix viewProjection = m3dFloatViewModelView * m3dFloatViewProjection;
		SurfaceDrawTraversal traversal;
		traversal.enableFiltering(true);
		traversal.setFrustum(cameraPath, targetW, targetH);
		traversal.traverse();
		unsigned int numItems = traversal.numberOfItems();
		MFnMesh fnMesh;
		for (int i = 0; i < numItems; i++)
		{
			MDagPath path;
			traversal.itemPath(i, path);
			if (path.hasFn(MFn::kMesh))
			{
				fnMesh.setObject(path);
				MFloatMatrix modelWorld(path.inclusiveMatrix().matrix);
				MTransformationMatrix transformMatrix;
				MFloatMatrix modelViewProjection = modelWorld * viewProjection;
				modelViewProjection = modelViewProjection.transpose();
				MIntArray triangleCounts;
				MIntArray triangleVertices; // This is the index list for all the triangles in the mesh in one big list. Ie. first 3 are for tri 1 etc. Index into getPoints()
				fnMesh.getTriangles(triangleCounts, triangleVertices);
				//int indices[100];
				//triangleVertices.get(indices);
				MFloatPointArray vertexArray;
				//float points[1000][4];
				fnMesh.getPoints(vertexArray);
				//vertexArray.get(points);
				UserSceneRenderer::get()->render(triangleVertices, vertexArray, modelViewProjection);
			}
		}
	}
	return MStatus::kSuccess;
}
Exemplo n.º 11
0
bool getObjectShadingGroups(const MDagPath& shapeObjectDP, MObject& shadingGroup)
{
    // if obj is a light, simply return the mobject
    if (shapeObjectDP.hasFn(MFn::kLight))
        shadingGroup = shapeObjectDP.node();

    if (shapeObjectDP.hasFn(MFn::kMesh))
    {
        // Find the Shading Engines Connected to the SourceNode
        MFnMesh fnMesh(shapeObjectDP.node());

        // A ShadingGroup will have a MFnSet
        MObjectArray sets, comps;
        fnMesh.getConnectedSetsAndMembers(shapeObjectDP.instanceNumber(), sets, comps, true);

        // Each set is a Shading Group. Loop through them
        for (unsigned int i = 0; i < sets.length(); ++i)
        {
            shadingGroup = sets[i];
            return true;
        }
    }

    if (shapeObjectDP.hasFn(MFn::kNurbsSurface)||shapeObjectDP.hasFn(MFn::kParticle)||shapeObjectDP.hasFn(MFn::kNParticle))
    {

        MObject instObjGroupsAttr;
        if (shapeObjectDP.hasFn(MFn::kNurbsSurface))
        {
            MFnNurbsSurface fnNurbs(shapeObjectDP.node());
            instObjGroupsAttr = fnNurbs.attribute("instObjGroups");
        }
        if (shapeObjectDP.hasFn(MFn::kParticle)||shapeObjectDP.hasFn(MFn::kNParticle))
        {
            MFnParticleSystem fnPart(shapeObjectDP.node());
            instObjGroupsAttr = fnPart.attribute("instObjGroups");
        }
        MPlug instPlug(shapeObjectDP.node(), instObjGroupsAttr);

        // Get the instance that our node is referring to;
        // In other words get the Plug for instObjGroups[intanceNumber];
        MPlug instPlugElem = instPlug.elementByLogicalIndex(shapeObjectDP.instanceNumber());

        // Find the ShadingGroup plugs that we are connected to as Source
        MPlugArray SGPlugArray;
        instPlugElem.connectedTo(SGPlugArray, false, true);

        // Loop through each ShadingGroup Plug
        for (unsigned int i=0; i < SGPlugArray.length(); ++i)
        {
            shadingGroup = SGPlugArray[i].node();
            return true;
        }
    }
    return false;
}
MayaTransformWriter::MayaTransformWriter(double iFrame,
    MayaTransformWriter & iParent, MDagPath & iDag,
    uint32_t iTimeIndex,
    bool iWriteVisibility)
{
    if (iDag.hasFn(MFn::kJoint))
    {
        MFnIkJoint joint(iDag);

        Alembic::AbcGeom::OXform obj(iParent.getObject(), joint.name().asChar(),
            iTimeIndex);
        mSchema = obj.getSchema();

        Alembic::Abc::OCompoundProperty cp = obj.getProperties();
        mAttrs = AttributesWriterPtr(new AttributesWriter(iFrame, cp, joint,
            iTimeIndex, iWriteVisibility));

        pushTransformStack(iFrame, joint);
    }
    else
    {
        MFnTransform trans(iDag);
        Alembic::AbcGeom::OXform obj(iParent.getObject(), trans.name().asChar(),
            iTimeIndex);
        mSchema = obj.getSchema();

        Alembic::Abc::OCompoundProperty cp = obj.getProperties();
        mAttrs = AttributesWriterPtr(new AttributesWriter(iFrame, cp, trans,
            iTimeIndex, iWriteVisibility));

        pushTransformStack(iFrame, trans);
    }


    // need to look at inheritsTransform
    MFnDagNode dagNode(iDag);
    MPlug inheritPlug = dagNode.findPlug("inheritsTransform");
    if (!inheritPlug.isNull())
    {
        if (util::getSampledType(inheritPlug) != 0)
            mInheritsPlug = inheritPlug;

        mSample.setInheritsXforms(inheritPlug.asBool());
    }

    // everything is default, don't write anything
    if (mSample.getNumOps() == 0 && mSample.getInheritsXforms())
        return;

    mSchema.set(mSample);
}
Exemplo n.º 13
0
MStatus surfaceTwist::doIt( const MArgList& )
//
//	Description:
//		Plugin command to test Selection List Iterator.
//
//
{
	MStatus status;

	// Create an iterator for the active selection list
	//
	MSelectionList slist;
	MGlobal::getActiveSelectionList( slist );
	MItSelectionList iter( slist );

	if (iter.isDone()) {
		cerr << "Nothing selected\n";
		return MS::kFailure;
	}

	MDagPath objectPath;
	MObject component;

	for ( ; !iter.isDone(); iter.next() ) {
		status = iter.getDagPath( objectPath, component );

		if (objectPath.hasFn(MFn::kNurbsSurface))
			status = twistNurbsSurface(objectPath, component);
		else if (objectPath.hasFn(MFn::kMesh))
			status = twistPolygon(objectPath, component);
		else {
			cerr << "Selected object is not a NURBS surface or a polygon\n";
			return MS::kFailure;
		}
	}
	return status;
}
Exemplo n.º 14
0
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVsSkinnerCmd::FindMeshesInHierarchy(
	const MDagPath &iDagPath,
	MSelectionList &oList )
{
	MStatus retVal( MS::kFailure );

	MDagPath rDagPath( iDagPath );	// Root dag path
	while ( rDagPath.length() > 1U )
	{
		rDagPath.pop();
	}

	MDagPath mDagPath;
	MDagPath sDagPath;

	uint nShapes;

	MItDag dIt;
	if ( rDagPath.length() )
	{
		dIt.reset( rDagPath );
	}

	for ( ; !dIt.isDone(); dIt.next() )
	{
		if ( !dIt.getPath( mDagPath ) )
			continue;

		mDagPath.numberOfShapesDirectlyBelow( nShapes );
		for ( uint i( 0U ); i != nShapes; ++i )
		{
			sDagPath = mDagPath;
			sDagPath.extendToShapeDirectlyBelow( i );
			if ( sDagPath.hasFn( MFn::kMesh ) )
				continue;

			oList.add( sDagPath, MObject::kNullObj, true );
			retVal = MS::kSuccess;
		}

		if ( !ConnectedToMesh( mDagPath, sDagPath ) )
			continue;

		oList.add( sDagPath, MObject::kNullObj, true );
		retVal = MS::kSuccess;
	}

	return retVal;
}
Exemplo n.º 15
0
MStatus unShowAvailableSystems::findAvailableSystems(std::string& str,MDagPath& dagPath)
{
	MStatus stat = MS::kSuccess;

	if(dagPath.hasFn(MFn::kJoint))
	{
		MFnIkJoint jointFn(dagPath);
		std::string name = dagPath.partialPathName().asChar();
		MPlug plug = jointFn.findPlug("unRibbonEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			char s[256];
			sprintf(s,"%s RibbonSystem %s\n",name.c_str(),enabled ? "True" : "False");
			str += s;
		}
		plug = jointFn.findPlug("unParticleEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			char s[256];
			sprintf(s,"%s ParticleSystem %s\n",name.c_str(),enabled ? "True" : "False");
			str += s;
		}
	}

	for (unsigned int i = 0; i < dagPath.childCount(); i++)
	{
		MObject child = dagPath.child(i);
		MDagPath childPath;
		stat = MDagPath::getAPathTo(child,childPath);
		if (MS::kSuccess != stat)
		{
			return MS::kFailure;
		}
		stat = findAvailableSystems(str,childPath);
		if (MS::kSuccess != stat)
			return MS::kFailure;
	}
	return MS::kSuccess;
}
Exemplo n.º 16
0
static MObject EntityNodeParent( MDagPath& path )
{
    if( path.hasFn( MFn::kDagNode ) )
    {
        MDagPath parentPath;
        MFnDependencyNode nodeFn;

        while( path.pop( 1 ) != MS::kInvalidParameter )
        {        
            nodeFn.setObject( path.node() );
            if( nodeFn.typeId() == EntityInstanceNode::s_TypeID )    
            {
                return nodeFn.object();
            }
        }
    }

    return MObject::kNullObj;
}
//
// Method to add in a light "prune" list. Only selected
// lights will be have their shadows requested, and
// be used for the scene render shader override.
//
MStatus viewRenderOverrideShadows::updateLightList()
{
	mLightList.clear();

	shadowPrepass* shadowOp = (shadowPrepass*)mRenderOperations[kShadowPrePass];
	sceneRender* sceneOp = (sceneRender*)mRenderOperations[kMaya3dSceneRender];
	if (!shadowOp || !sceneOp)
		return MStatus::kFailure;

	// Scan selection list for active lights
	//
	MSelectionList selectList;
	MDagPath dagPath;
	MObject component;
	MGlobal::getActiveSelectionList( selectList );
	for (unsigned int i=0; i<selectList.length(); i++)
	{
		selectList.getDagPath( i, dagPath, component );
		dagPath.extendToShape();
		if ( dagPath.hasFn( MFn::kLight ) )
		{
			mLightList.add( dagPath );
		}
	}
	
	// Set light list to prune which lights to request shadows for
	//
	if (mLightList.length())
		shadowOp->setLightList( &mLightList );
	else
		shadowOp->setLightList( NULL );

	// Set light list to prune which lights to bind for scene shader
	//
	if (mLightList.length())
		sceneOp->setLightList( &mLightList );
	else
		sceneOp->setLightList( NULL );

	return MStatus::kSuccess;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CVstSelectCoincidentFacesCmd::GetSpecifiedMeshes(
	MSelectionList &meshList )
{
	meshList.clear();

	MSelectionList optSelectionList;
	m_undo.ArgDatabase().getObjects( optSelectionList );

	MDagPath mDagPath;
	MObject cObj;
	for ( MItSelectionList sIt( optSelectionList ); !sIt.isDone(); sIt.next() )
	{
		if ( sIt.itemType() == MItSelectionList::kDagSelectionItem && sIt.getDagPath( mDagPath, cObj ) )
		{
			if ( mDagPath.hasFn( MFn::kMesh ) )
			{
				if ( sIt.hasComponents() || !cObj.isNull() )
				{
					meshList.add( mDagPath, cObj );
				}
				else
				{
					mDagPath.extendToShapeDirectlyBelow( 0U );
					meshList.add( mDagPath, MObject::kNullObj, true );
				}
			}
		}
	}

	if ( meshList.isEmpty() )
	{
		for ( MItDag dIt( MItDag::kDepthFirst, MFn::kMesh ); !dIt.isDone(); dIt.next() )
		{
			if ( dIt.getPath( mDagPath ) )
			{
				meshList.add( mDagPath, MObject::kNullObj, true );
			}
		}
	}
}
Exemplo n.º 19
0
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVsSkinnerCmd::GetSpecifiedMeshes(
	const MSelectionList &iList,
	MSelectionList &oList )
{
	MStatus retVal( MS::kFailure );

	oList.clear();

	MDagPath mDagPath;

	for ( MItSelectionList sIt( iList ); !sIt.isDone(); sIt.next() )
	{
		if ( sIt.itemType() == MItSelectionList::kDagSelectionItem && sIt.getDagPath( mDagPath ) )
		{
			if ( mDagPath.hasFn( MFn::kMesh ) )
			{
				mDagPath.extendToShapeDirectlyBelow( 0 );
				oList.add( mDagPath, MObject::kNullObj, true );
				retVal = MS::kSuccess;
			}
		}
	}

	MSelectionList tmpList;

	for ( MItSelectionList sIt( iList ); !sIt.isDone(); sIt.next() )
	{
		if ( sIt.itemType() == MItSelectionList::kDagSelectionItem && sIt.getDagPath( mDagPath ) )
		{
			if ( FindMeshesInHierarchy( mDagPath, tmpList ) )
			{
				oList.merge( tmpList );
				retVal = MS::kSuccess;
			}
		}
	}

	return retVal;
}
Exemplo n.º 20
0
	MStatus CVCurveFromObject(const Model::Object & object, MPointArray & array) {
		MStatus status;
		MDagPath dagPath = object.getDagPath(status);

		if (!status) {
			status.perror("Object::getDagPath");
			return status;
		}
		
		MDagPath shape = dagPath;
		unsigned int numShapes;
		
		if (!(status = dagPath.numberOfShapesDirectlyBelow(numShapes))) {
			status.perror("MDagPath::numberOfShapesDirectlyBelow");
			return status;
		}

		for(unsigned int i = 0; i < numShapes; ++i) {
			if (!(status = shape.extendToShapeDirectlyBelow(i))) {
				status.perror("MDagPath::extendToShapeDirectlyBelow");
				return status;
			}

			if (shape.hasFn(MFn::kNurbsCurve)) {
				MFnNurbsCurve nurbsCurve(shape);

				if (!(status = nurbsCurve.getCVs(array, MSpace::kWorld))) {
					status.perror("MFnNurbsCurve::getCVs");
					return status;
				}

				return MStatus::kSuccess;
			}
			else
				std::cerr << "No MFnNurbsCurve!" << std::endl;
		}

		return MStatus::kNotFound;
	}
Exemplo n.º 21
0
MStatus cvExpand::doIt( const MArgList& args )
{

	MSelectionList list;
	MSelectionList newList;

	// Get the geometry list from what is currently selected in the 
	// model
	//
	MGlobal::getActiveSelectionList( list );

	MDagPath path;
	MObject  component;
 
	// Make expanded Selection List
	//
	for ( MItSelectionList iter( list ); !iter.isDone(); iter.next() ) {
		iter.getDagPath( path, component );
		
		if ( path.hasFn( MFn::kNurbsSurfaceGeom ) && 
			 !component.isNull() ) {
			for ( MItSurfaceCV cvIter( path, component ); 
				  !cvIter.isDone(); cvIter.next() ) {
				newList.add( path, cvIter.cv() );
			}
		} else {
			newList.add( path, component );
		}
	}

	// Return expanded selection list as an array of strings
	//
	MStringArray returnArray;
	newList.getSelectionStrings( returnArray );

	MPxCommand::setResult( returnArray );

	return MS::kSuccess;
}
Exemplo n.º 22
0
MS DCTranslator::exportSelected()
{
	MS status;
	MSelectionList selection;
	MGlobal::getActiveSelectionList(selection);
	MItSelectionList selIt(selection);
	if (selIt.isDone()) {
		status.perror("MayaToolKit: Nothing Selected!");
		MGlobal::displayWarning("kaleido maya toolkit: Nothing selected!");
		return MS::kFailure;
	}

	MDagPathArray pathArray;
	for (; !selIt.isDone(); selIt.next()) {
		MItDag dagIt(MItDag::kDepthFirst, MFn::kInvalid, &status);
		MDagPath objPath;
		status = selIt.getDagPath(objPath);
		status = dagIt.reset(objPath.node(), MItDag::kDepthFirst, MFn::kInvalid);
		do {
			MDagPath dagPath;
			MObject component = MObject::kNullObj;
			status = dagIt.getPath(dagPath);
			MFnDagNode dagNode(dagPath, &status);
			if (dagNode.isIntermediateObject())
			{

			}
			else if (dagPath.hasFn(MFn::kMesh))
			{
				if (!dagPath.hasFn(MFn::kTransform))
				{
					SpMesh curMesh{ new Mesh };
					status = GetMeshFromNode(dagPath, status, *curMesh);
					//WriteTheMesh Here
					if (status == MS::kSuccess) {
						(*m_MeshArch) << curMesh;
						MGlobal::displayInfo("Write Mesh finished.");
						m_Meshes.push_back(curMesh);
					}
					else {
						MGlobal::displayError("Error GetMesh From Node.");
					}
				}
			}
			else if (dagPath.hasFn(MFn::kCamera))
			{
				if (!dagPath.hasFn(MFn::kTransform))
				{
					pathArray.append(dagPath);
				}
			}
			else if (dagPath.hasFn(MFn::kSpotLight))
			{
				if (!dagPath.hasFn(MFn::kTransform))
				{
					pathArray.append(dagPath);
				}
			}
			dagIt.next();
		} while (!dagIt.isDone());
	}

	return status;
}
Exemplo n.º 23
0
MS DCTranslator::exportAll()
{
	MStatus status = MS::kSuccess;
	MItDag dagIterator(MItDag::kBreadthFirst, MFn::kInvalid, &status);

	if (MS::kSuccess != status) {
		fprintf(stderr, "Failure in DAG iterator setup.\n");
		return MS::kFailure;
	}

	for (; !dagIterator.isDone(); dagIterator.next())
	{
		MDagPath dagPath;
		status = dagIterator.getPath(dagPath);

		if (!status) {
			fprintf(stderr, "Failure getting DAG path.\n");
			return MS::kFailure;
		}

		MFnDagNode dagNode(dagPath, &status);
		if (dagNode.isIntermediateObject())
		{
			continue;
		}

		if ((dagPath.hasFn(MFn::kNurbsSurface)) &&
			(dagPath.hasFn(MFn::kTransform)))
		{
			status = MS::kSuccess;
			fprintf(stderr, "Warning: skipping Nurbs Surface.\n");
		}
		else if ((dagPath.hasFn(MFn::kMesh)) &&
			(dagPath.hasFn(MFn::kTransform)))
		{
			// We want only the shape,
			// not the transform-extended-to-shape.
			continue;
		}
		else if (dagPath.hasFn(MFn::kMesh))
		{
			SpMesh curMesh{ new Mesh };
			status = GetMeshFromNode(dagPath, status, *curMesh);
			m_Meshes.push_back(curMesh);
			//WriteTheMesh Here
			if (status == MS::kSuccess) {
				(*m_MeshArch) << (*curMesh);
				MGlobal::displayInfo("Write Mesh finished...\n");
			}
			else {
				MGlobal::displayError("Error GetMesh From Node...\n");
			}
		}
		else if (dagPath.hasFn(MFn::kCamera))
		{
			if (!dagPath.hasFn(MFn::kTransform))
			{
				MGlobal::displayInfo("Find Camera Info.");
				MFnCamera camera(dagPath, &status);
				MPoint point = camera.eyePoint(MSpace::kWorld, &status);
				if (status == MS::kSuccess) {
					MGlobal::displayInfo(MString("camera x=")+point.x);
				}
			}
		}
	}
	return status;
}
/*
	Draw a scene full of bounding boxes
*/
bool
MCustomSceneDraw::draw(MDagPath &cameraPath, unsigned int width, unsigned int height)
{
	if (!cameraPath.isValid())
		return false;

	MDrawTraversal *trav = NULL;
	trav = new MSurfaceDrawTraversal;

	if (!trav)
		return false;

	trav->enableFiltering( true );
	trav->setFrustum( cameraPath, width, height );
	if (!trav->frustumValid())
	{
		delete trav; trav = NULL;
		return false;
	}
	trav->traverse();

	unsigned int numItems = trav->numberOfItems();
	unsigned int i;
	for (i=0; i<numItems; i++)
	{
		MDagPath path;
		trav->itemPath(i, path);

		if (path.isValid())
		{
			bool drawIt = false;

			//
			// Draw surfaces (polys, nurbs, subdivs)
			//
			if ( path.hasFn( MFn::kMesh) ||
				path.hasFn( MFn::kNurbsSurface) ||
				path.hasFn( MFn::kSubdiv) )
			{
				drawIt = true;
				if (trav->itemHasStatus( i, MDrawTraversal::kActiveItem ))
				{
					gGLFT->glColor3f( 1.0f, 1.0f, 1.0f );
				}
				else if (trav->itemHasStatus( i, MDrawTraversal::kTemplateItem ))
				{
					gGLFT->glColor3f( 0.2f, 0.2f, 0.2f );
				}
				else
				{
					if (path.hasFn( MFn::kMesh ))
						gGLFT->glColor3f( 0.286f, 0.706f, 1.0f );
					else if (path.hasFn( MFn::kNurbsSurface))
						gGLFT->glColor3f( 0.486f, 0.306f, 1.0f );
					else
						gGLFT->glColor3f( 0.886f, 0.206f, 1.0f );
				}
			}

			if (drawIt)
			{
				MFnDagNode dagNode(path);
				MBoundingBox box = dagNode.boundingBox();
				drawBounds( path, box );
			}
		}
	}

	if (trav)
	{
		delete trav;
		trav = NULL;
	}
	return true;
}
Exemplo n.º 25
0
    // --------------------------------------------------------------------
    bool SceneGraph::getIsExportNode ( 
        const MDagPath& dagPath, 
        bool& isForced,
        bool& isVisible )
    {
        // Does this dagPath already exist? If so, only recurse if FollowInstancedChildren() is set.
        MFnDagNode dagFn ( dagPath );
        String dagNodeName = dagFn.name().asChar();

        bool isSceneRoot = dagPath.length() == 0;

        // Ignore default and intermediate nodes (history items)
        bool isIntermediateObject = dagFn.isIntermediateObject();
        if ( ( dagFn.isDefaultNode() && !isSceneRoot ) || isIntermediateObject )
        {
            return false;
        }

        MString nodeName = dagPath.partialPathName();
        if ( nodeName == MString ( NIMA_INTERNAL_PHYSIKS ) )
        {
            // Skip this node, which is only used
            // by Nima as a work-around for a Maya bug.
            return false;
        }

        // If we are not already forcing this node, its children
        // check whether we should be forcing it (skinning of hidden joints).
        isForced = isForcedNode ( dagPath );
        DagHelper::getPlugValue ( dagPath.node(), ATTR_VISIBILITY, isVisible );
        bool isInstanced = dagPath.isInstanced();
        uint instanceNumber = dagPath.instanceNumber();

        if ( !isForced )
        {
            // Check for visibility
            if ( !ExportOptions::exportInvisibleNodes() && !isVisible )
            {
                // Check if the visibility of the element is animated.
                AnimationSampleCache* animationCache = mDocumentExporter->getAnimationCache();
                if ( !AnimationHelper::isAnimated ( animationCache, dagPath.node(), ATTR_VISIBILITY ) )
                {
                    return false;
                }
            }
            else if ( !isVisible && !ExportOptions::exportDefaultCameras() )
            {
                // Check for the default camera transform names.
                if ( nodeName == CAMERA_PERSP || nodeName == CAMERA_TOP || nodeName == CAMERA_SIDE || nodeName == CAMERA_FRONT ||
                     nodeName == CAMERA_PERSP_SHAPE || nodeName == CAMERA_TOP_SHAPE || nodeName == CAMERA_SIDE_SHAPE || nodeName == CAMERA_FRONT_SHAPE )
                    return false;
            }
        }

        isForced &= !isVisible;
        if ( !isForced )
        {
            // We don't want to process manipulators
            if ( dagPath.hasFn ( MFn::kManipulator ) || dagPath.hasFn ( MFn::kViewManip ) ) return false;

            // Check for constraints which are not exported
            //if ( !ExportOptions::exportConstraints() && dagPath.hasFn ( MFn::kConstraint ) ) return false;
            if ( dagPath.hasFn ( MFn::kConstraint ) ) return false;

            // Check set membership exclusion/inclusion
            if ( SetHelper::isExcluded ( dagPath ) ) return false;
        }

        return true;
    }
Exemplo n.º 26
0
MayaTransformWriter::MayaTransformWriter(MayaTransformWriter & iParent,
	MDagPath & iDag, Alembic::Util::uint32_t iTimeIndex, const JobArgs & iArgs)
{
	mVerbose = iArgs.verbose;
	mFilterEulerRotations = iArgs.filterEulerRotations;
	mJointOrientOpIndex[0] = mJointOrientOpIndex[1] = mJointOrientOpIndex[2] =
	mRotateOpIndex[0]	  = mRotateOpIndex[1]	  = mRotateOpIndex[2]	  =
	mRotateAxisOpIndex[0]  = mRotateAxisOpIndex[1]  = mRotateAxisOpIndex[2]  = ~size_t(0);

	if (iDag.hasFn(MFn::kJoint))
	{
		MFnIkJoint joint(iDag);
		MString jointName = joint.name();

		mName = util::stripNamespaces(jointName, iArgs.stripNamespace);

		Alembic::AbcGeom::OXform obj(iParent.getObject(), mName.asChar(),
			iTimeIndex);
		mSchema = obj.getSchema();

		Alembic::Abc::OCompoundProperty cp;
		Alembic::Abc::OCompoundProperty up;
		if (AttributesWriter::hasAnyAttr(joint, iArgs))
		{
			cp = mSchema.getArbGeomParams();
			up = mSchema.getUserProperties();
		}

		mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, joint,
			iTimeIndex, iArgs));

		pushTransformStack(joint, iTimeIndex == 0);
	}
	else
	{
		MFnTransform trans(iDag);
		MString transName = trans.name();

		mName = util::stripNamespaces(transName, iArgs.stripNamespace);

		Alembic::AbcGeom::OXform obj(iParent.getObject(), mName.asChar(),
			iTimeIndex);
		mSchema = obj.getSchema();

		Alembic::Abc::OCompoundProperty cp;
		Alembic::Abc::OCompoundProperty up;
		if (AttributesWriter::hasAnyAttr(trans, iArgs))
		{
			cp = mSchema.getArbGeomParams();
			up = mSchema.getUserProperties();
		}

		mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, trans,
			iTimeIndex, iArgs));

		pushTransformStack(trans, iTimeIndex == 0);
	}


	// need to look at inheritsTransform
	MFnDagNode dagNode(iDag);
	MPlug inheritPlug = dagNode.findPlug("inheritsTransform");
	if (!inheritPlug.isNull())
	{
		if (util::getSampledType(inheritPlug) != 0)
			mInheritsPlug = inheritPlug;

		mSample.setInheritsXforms(inheritPlug.asBool());
	}

	// everything is default, don't write anything
	if (mSample.getNumOps() == 0 && mSample.getInheritsXforms())
		return;

	mSchema.set(mSample);
}
Exemplo n.º 27
0
MayaTransformWriter::MayaTransformWriter(Alembic::AbcGeom::OObject & iParent,
	MDagPath & iDag, Alembic::Util::uint32_t iTimeIndex, const JobArgs & iArgs)
{
	mVerbose = iArgs.verbose;
	mFilterEulerRotations = iArgs.filterEulerRotations;
	mJointOrientOpIndex[0] = mJointOrientOpIndex[1] = mJointOrientOpIndex[2] =
	mRotateOpIndex[0]	  = mRotateOpIndex[1]	  = mRotateOpIndex[2]	  =
	mRotateAxisOpIndex[0]  = mRotateAxisOpIndex[1]  = mRotateAxisOpIndex[2]  = ~size_t(0);

	if (iDag.hasFn(MFn::kJoint))
	{
		MFnIkJoint joint(iDag);
		MString jointName = joint.name();

		mName = util::stripNamespaces(jointName, iArgs.stripNamespace);

		Alembic::AbcGeom::OXform obj(iParent, mName.asChar(),
			iTimeIndex);
		mSchema = obj.getSchema();

		Alembic::Abc::OCompoundProperty cp;
		Alembic::Abc::OCompoundProperty up;
		if (AttributesWriter::hasAnyAttr(joint, iArgs))
		{
			cp = mSchema.getArbGeomParams();
			up = mSchema.getUserProperties();
		}

		mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, joint,
			iTimeIndex, iArgs));

		if (!iArgs.worldSpace)
		{
			pushTransformStack(joint, iTimeIndex == 0);

			// need to look at inheritsTransform
			MFnDagNode dagNode(iDag);
			MPlug inheritPlug = dagNode.findPlug("inheritsTransform");
			if (!inheritPlug.isNull())
			{
				if (util::getSampledType(inheritPlug) != 0)
					mInheritsPlug = inheritPlug;

				mSample.setInheritsXforms(inheritPlug.asBool());
			}

			// everything is default, don't write anything
			if (mSample.getNumOps() == 0 && mSample.getInheritsXforms())
				return;

			mSchema.set(mSample);

			return;
		}
	}
	else
	{
		MFnTransform trans(iDag);
		MString transName = trans.name();

		mName = util::stripNamespaces(transName, iArgs.stripNamespace);

		Alembic::AbcGeom::OXform obj(iParent, mName.asChar(),
			iTimeIndex);
		mSchema = obj.getSchema();

		Alembic::Abc::OCompoundProperty cp;
		Alembic::Abc::OCompoundProperty up;
		if (AttributesWriter::hasAnyAttr(trans, iArgs))
		{
			cp = mSchema.getArbGeomParams();
			up = mSchema.getUserProperties();
		}

		mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, trans,
			iTimeIndex, iArgs));

		if (!iArgs.worldSpace)
		{
			pushTransformStack(trans, iTimeIndex == 0);

			// need to look at inheritsTransform
			MFnDagNode dagNode(iDag);
			MPlug inheritPlug = dagNode.findPlug("inheritsTransform");
			if (!inheritPlug.isNull())
			{
				if (util::getSampledType(inheritPlug) != 0)
					mInheritsPlug = inheritPlug;

				mSample.setInheritsXforms(inheritPlug.asBool());
			}


			// everything is default, don't write anything
			if (mSample.getNumOps() == 0 && mSample.getInheritsXforms())
				return;

			mSchema.set(mSample);
			return;
		}
	}

	// if we didn't bail early then we need to add all the transform
	// information at the current node and above

	// copy the dag path because we'll be popping from it
	MDagPath dag(iDag);

	int i;
	int numPaths = dag.length();
	std::vector< MDagPath > dagList;
	for (i = numPaths - 1; i > -1; i--, dag.pop())
	{
		dagList.push_back(dag);

		// inheritsTransform exists on both joints and transforms
		MFnDagNode dagNode(dag);
		MPlug inheritPlug = dagNode.findPlug("inheritsTransform");

		// if inheritsTransform exists and is set to false, then we
		// don't need to worry about ancestor nodes above this one
		if (!inheritPlug.isNull() && !inheritPlug.asBool())
			break;
	}


	std::vector< MDagPath >::iterator iStart = dagList.begin();

	std::vector< MDagPath >::iterator iCur = dagList.end();
	iCur--;

	// now loop backwards over our dagpath list so we push ancestor nodes
	// first, all the way down to the current node
	for (; iCur != iStart; iCur--)
	{
		// only add it to the stack don't write it yet!

		if (iCur->hasFn(MFn::kJoint))
		{
			MFnIkJoint joint(*iCur);
			pushTransformStack(joint, iTimeIndex == 0);
		}
		else
		{
			MFnTransform trans(*iCur);
			pushTransformStack(trans, iTimeIndex == 0);
		}
	}

	// finally add any transform info on the final node and write it
	if (iCur->hasFn(MFn::kJoint))
	{
		MFnIkJoint joint(*iCur);
		pushTransformStack(joint, iTimeIndex == 0);
	}
	else
	{
		MFnTransform trans(*iCur);
		pushTransformStack(trans, iTimeIndex == 0);
	}

	// need to look at inheritsTransform
	MFnDagNode dagNode(iDag);
	MPlug inheritPlug = dagNode.findPlug("inheritsTransform");
	if (!inheritPlug.isNull())
	{
		if (util::getSampledType(inheritPlug) != 0)
			mInheritsPlug = inheritPlug;

		mSample.setInheritsXforms(inheritPlug.asBool());
	}


	// everything is default, don't write anything
	if (mSample.getNumOps() == 0 && mSample.getInheritsXforms())
		return;

	mSchema.set(mSample);

}
Exemplo n.º 28
0
bool DX11ViewportRenderer::drawScene(const MRenderingInfo &renderInfo)
//
// Description:
//		Draw the Maya scene, using a custom traverser.
//
{
	bool useDrawTraversal = true;
	float groundPlaneColor[3] = { 0.8f, 0.8f, 0.8f };

	if (useDrawTraversal)
	{
		const MDagPath &cameraPath = renderInfo.cameraPath();
		if (cameraPath.isValid())
		{
			// You can actually keep the traverser classes around
			// if desired. Here we just create temporary traversers
			// on the fly.
			//
			MDrawTraversal *trav = new MDrawTraversal;
			if (!trav)
			{
				MGlobal::displayWarning("DX11 renderer : failed to create a traversal class !\n");
				return true;
			}

			trav->enableFiltering( false );

			const MRenderTarget &renderTarget = renderInfo.renderTarget();
			trav->setFrustum( cameraPath, renderTarget.width(), 
							  renderTarget.height() );

			if (!trav->frustumValid())
			{
				MGlobal::displayWarning("DX11 renderer : Frustum is invalid !\n");
				return true;
			}

			trav->traverse();

			unsigned int numItems = trav->numberOfItems();
			unsigned int i;
			for (i=0; i<numItems; i++)
			{
				MDagPath path;
				trav->itemPath(i, path);

				if (path.isValid())
				{
					bool drawIt = false;

					// Default traverer may have view manips showing up.
					// This is currently a known Maya bug.
					if ( path.hasFn( MFn::kViewManip ))
						continue;

					//
					// Draw surfaces (polys, nurbs, subdivs)
					//
					bool active = false;
					bool templated = false;
					if ( path.hasFn( MFn::kMesh) || 
						 path.hasFn( MFn::kNurbsSurface) || 
						 path.hasFn( MFn::kSubdiv) )
					{
						drawIt = true;
						if (trav->itemHasStatus( i, MDrawTraversal::kActiveItem ))
						{
							active = true;
						}
						if (trav->itemHasStatus( i, MDrawTraversal::kTemplateItem ))
						{
							templated = true;
						}
					}

					//
					// Draw the ground plane
					//
					else if (path.hasFn( MFn::kSketchPlane ) ||
							 path.hasFn( MFn::kGroundPlane ))
					{
						MMatrix  matrix = path.inclusiveMatrix();
						MFnDagNode dagNode(path);
						MBoundingBox box = dagNode.boundingBox();
						drawBounds( matrix, box, groundPlaneColor );
					}

					if (drawIt)
					{
						drawSurface( path, active, templated );
					}
				}
			}

			if (trav)
				delete trav;

			// Cleanup any unused resource items
			bool onlyInvalidItems = true;
			clearResources( onlyInvalidItems, false );
		}
	}
	else
	{
		// Draw some poly bounding boxes 
		//
		MItDag::TraversalType traversalType = MItDag::kDepthFirst;
		MFn::Type filter = MFn::kMesh;
		MStatus status;

		MItDag dagIterator( traversalType, filter, &status);

		for ( ; !dagIterator.isDone(); dagIterator.next() ) 
		{

			MDagPath dagPath;

			status = dagIterator.getPath(dagPath);
			if ( !status ) {
				status.perror("MItDag::getPath");
				continue;
			}

			MFnDagNode dagNode(dagPath, &status);
			if ( !status ) {
				status.perror("MFnDagNode constructor");
				continue;
			}

			MMatrix  matrix = dagPath.inclusiveMatrix();
			MBoundingBox box = dagNode.boundingBox();
			drawBounds( matrix, box, groundPlaneColor );
		}
	}
	return true;
}
Exemplo n.º 29
0
bool DX11ViewportRenderer::drawSurface( const MDagPath &dagPath, bool active, bool templated)
{
	bool drewSurface = false;

	if ( !dagPath.hasFn( MFn::kMesh ))
	{
		MMatrix  matrix = dagPath.inclusiveMatrix();
		MFnDagNode dagNode(dagPath);
		MBoundingBox box = dagNode.boundingBox();
		float color[3] = {0.6f, 0.3f, 0.0f};
		if (active)
		{
			color[0] = 1.0f;
			color[1] = 1.0f;
			color[2] = 1.0f;
		}
		else if (templated)
		{
			color[0] = 1.0f;
			color[1] = 0.686f;
			color[2] = 0.686f;
		}
		drawBounds( matrix, box, color);
		return true;
	}

	if ( dagPath.hasFn( MFn::kMesh ))
	{
		MMatrix  matrix = dagPath.inclusiveMatrix();
		MFnDagNode dagNode(dagPath);

		// Look for any hardware shaders which can draw D3D first.
		//
		bool drewWithHwShader = false;
		{
			MFnMesh fnMesh(dagPath);
			MObjectArray sets;
			MObjectArray comps;
			unsigned int instanceNum = dagPath.instanceNumber();
			if (!fnMesh.getConnectedSetsAndMembers(instanceNum, sets, comps, true))
				MGlobal::displayError("ERROR : MFnMesh::getConnectedSetsAndMembers");
			for ( unsigned i=0; i<sets.length(); i++ ) 
			{
				MObject set = sets[i];
				MObject comp = comps[i];

				MStatus status;
				MFnSet fnSet( set, &status );
				if (status == MS::kFailure) {
					MGlobal::displayError("ERROR: MFnSet::MFnSet");
					continue;
				}

				MObject shaderNode = findShader(set);
				if (shaderNode != MObject::kNullObj)
				{
					MPxHardwareShader * hwShader = 
						MPxHardwareShader::getHardwareShaderPtr( shaderNode );

					if (hwShader)
					{
						const MRenderProfile & profile = hwShader->profile();
						if (profile.hasRenderer( MRenderProfile::kMayaD3D))
						{
							// Render a Maya D3D hw shader here....
							//printf("Found a D3D hw shader\n");
							//drewWithHwShader = true;
						}
					}
				}
			}
		}

		// Get the geometry buffers for this bad boy and render them
		D3DGeometry* Geometry = m_resourceManager.getGeometry( dagPath, m_pD3DDevice);
		if( Geometry)
		{
			// Transform from object to world space
			//
			XMMATRIX objectToWorld = XMMATRIX
				(
				(float)matrix.matrix[0][0], (float)matrix.matrix[0][1], (float)matrix.matrix[0][2], (float)matrix.matrix[0][3],
				(float)matrix.matrix[1][0], (float)matrix.matrix[1][1], (float)matrix.matrix[1][2], (float)matrix.matrix[1][3],
				(float)matrix.matrix[2][0], (float)matrix.matrix[2][1], (float)matrix.matrix[2][2], (float)matrix.matrix[2][3],
				(float)matrix.matrix[3][0], (float)matrix.matrix[3][1], (float)matrix.matrix[3][2], (float)matrix.matrix[3][3]
			);

			FixedFunctionConstants cb;

			if (!drewWithHwShader)
			{
				// Get material properties for shader associated with mesh
				//
				// 1. Try to draw with the sample internal programmable shader
				bool drewGeometryWithShader = false;

				// 2. Draw with fixed function shader
				if (!drewGeometryWithShader)
				{
					// Set up a default material, just in case there is none.
					//
					float diffuse[3];
					if (active)
					{
						if (templated)
						{
							m_pD3DDeviceCtx->RSSetState( m_pWireframeRS );
							diffuse[0] = 1.0f; diffuse[1] = 0.686f; diffuse[2] = 0.686f;
						}
						else
						{
							m_pD3DDeviceCtx->RSSetState( m_pNormalRS );
							diffuse[0] = 0.6f; diffuse[1] = 0.6f; diffuse[2] = 0.6f;
						}
					}
					else
					{
						if (templated)
						{
							m_pD3DDeviceCtx->RSSetState( m_pWireframeRS );
							diffuse[0] = 1.0f; diffuse[1] = 0.686f; diffuse[2] = 0.686f;
						}
						else
						{
							m_pD3DDeviceCtx->RSSetState( m_pNormalRS );
							diffuse[0] = 0.5f; diffuse[1] = 0.5f; diffuse[2] = 0.5f;
						}
					}

					// Set constant buffer
					XMVECTOR det;
					cb.wvIT = XMMatrixInverse( &det, objectToWorld * m_currentViewMatrix );
					cb.wvp = XMMatrixTranspose( objectToWorld * m_currentViewMatrix * m_currentProjectionMatrix );
					cb.wv = XMMatrixTranspose( objectToWorld * m_currentViewMatrix );
					cb.lightDir = XMFLOAT4( 0.0f, 0.0f, 1.0f, 0.0f );
					cb.lightColor = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f );
					cb.ambientLight = XMFLOAT4( 0.2f, 0.2f, 0.2f, 0.0f );
					cb.diffuseMaterial = XMFLOAT4( diffuse[0], diffuse[1], diffuse[2], 0.0f );
					cb.specularColor = XMFLOAT4( 0.2f, 0.2f, 0.2f, 0.0f );
					cb.diffuseCoeff = 1.0f;
					cb.shininess = 16.0f;
					cb.transparency = 1.0f;
					m_pD3DDeviceCtx->UpdateSubresource( m_pFixedFunctionConstantBuffer, 0, NULL, &cb, 0, 0 );

					// get shader
					SurfaceEffectItemList::const_iterator it = m_resourceManager.getSurfaceEffectItemList().find( "Maya_fixedFunction" );
					if ( it == m_resourceManager.getSurfaceEffectItemList().end() )
						return false;
					const SurfaceEffectItem* sei = it->second;

					// bind shaders
					m_pD3DDeviceCtx->VSSetShader( sei->fVertexShader, NULL, 0 );
					m_pD3DDeviceCtx->VSSetConstantBuffers( 0, 1, &m_pFixedFunctionConstantBuffer );
					m_pD3DDeviceCtx->IASetInputLayout( sei->fInputLayout );
					m_pD3DDeviceCtx->PSSetShader( sei->fPixelShader, NULL, 0 );
					m_pD3DDeviceCtx->PSSetConstantBuffers( 0, 1, &m_pFixedFunctionConstantBuffer );

					Geometry->Render( m_pD3DDeviceCtx );

					drewSurface = true;
				}
			}

			// Draw wireframe on top
			//

			if ( drewSurface && active )
			{
				bool drawActiveWithBounds = false;
				if (drawActiveWithBounds)
				{
					MBoundingBox box = dagNode.boundingBox();
					float color[3] = {1.0f, 1.0f, 1.0f};
					drawBounds( matrix, box, color );
				}
				else
				{
					cb.lightColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f );
					cb.ambientLight = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f );
					cb.diffuseMaterial = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f );
					cb.specularColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f );
					m_pD3DDeviceCtx->UpdateSubresource( m_pFixedFunctionConstantBuffer, 0, NULL, &cb, 0, 0 );

					m_pD3DDeviceCtx->RSSetState( m_pWireframeRS );

					Geometry->Render( m_pD3DDeviceCtx );				
				}
			}
		} // If Geometry
	}
	return drewSurface;
}
Exemplo n.º 30
0
/* virtual */
MStatus	hwColorPerVertexShader::glGeometry( const MDagPath& path,
                                int prim,
								unsigned int writable,
								int indexCount,
								const unsigned int * indexArray,
								int vertexCount,
								const int * vertexIDs,
								const float * vertexArray,
								int normalCount,
								const float ** normalArrays,
								int colorCount,
								const float ** colorArrays,
								int texCoordCount,
								const float ** texCoordArrays)
{
	// If this attribute is enabled, normals, tangents,
	// and binormals can be visualized using false coloring.
	// Negative values will clamp to black however.

#ifdef _TEST_FILE_PATH_DURING_DRAW_
	if (path.hasFn( MFn::kMesh ) )
	{
		// Check the # of uvsets. If no uvsets
		// then can't return tangent or binormals
		//
		MGlobal::displayInfo( path.fullPathName() );

		MFnMesh fnMesh( path.node() );
		numUVSets = fnMesh.numUVSets();
	}
#endif
	if ((unsigned int)normalCount > mNormalsPerVertex)
		normalCount = mNormalsPerVertex;
	if (normalCount > 0)
	{
		glPushAttrib(GL_ALL_ATTRIB_BITS); 
		glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
		glDisable(GL_LIGHTING);
		glDisable(GL_BLEND);

		if (normalCount > 1)
		{
			if (normalCount == 2)
			{
	//#define _TANGENT_DEBUG
	#ifdef _TANGENT_DEBUG
				const float *tangents = (const float *)&normalArrays[1][0];
				for (int  i=0; i< vertexCount; i++)
				{
					cout<<"tangent["<<i<<"] = "<<tangents[i*3]
						<<","<<tangents[i*3+1]<<","<<tangents[i*3+2]<<endl;
				}
	#endif
				glEnableClientState(GL_COLOR_ARRAY);
				glColorPointer(3, GL_FLOAT, 0, &normalArrays[1][0]);
			}
			else
			{
	#ifdef _BINORMAL_DEBUG
				const float *binormals = (const float *)&normalArrays[2][0];
				for (unsigned int  i=0; i< vertexCount; i++)
				{
					cout<<"binormals["<<i<<"] = "<<binormals[i*3]
						<<","<<binormals[i*3+1]<<","<<binormals[i*3+2]<<endl;
				}
	#endif
				glEnableClientState(GL_COLOR_ARRAY);
				glColorPointer(3, GL_FLOAT, 0, &normalArrays[2][0]);
			}
		}
		else if (normalCount)
		{
			glEnableClientState(GL_COLOR_ARRAY);
			glColorPointer(3, GL_FLOAT, 0, &normalArrays[0][0]);
		}

		glEnableClientState(GL_VERTEX_ARRAY);
		glVertexPointer ( 3, GL_FLOAT, 0, &vertexArray[0] );
		glDrawElements ( prim, indexCount, GL_UNSIGNED_INT, indexArray );

		glDisableClientState(GL_COLOR_ARRAY);

		glPopClientAttrib();
		glPopAttrib();

		return MS::kSuccess;
	}
	else
	{
		return draw( prim, writable, indexCount, indexArray,
			vertexCount, vertexArray, colorCount, colorArrays );
	}
}