Example #1
0
MStatus customAttrManip::connectToDependNode(const MObject &node)
//
// Description
// 	  This method activates the manip on the given transform node.
//
{
    MStatus stat = MStatus::kSuccess;

	// Get the DAG path
	//
	MFnDagNode dagNodeFn(node);
	dagNodeFn.getPath(fNodePath);

    // Connect the plugs to the manip.
    MFnDependencyNode nodeFn(node);    
	MFnDistanceManip distManipFn(fManip);
    MPlug cPlug = nodeFn.findPlug(customAttributeString, &stat);
	if( stat == MStatus::kSuccess )
		distManipFn.connectToDistancePlug(cPlug);

    finishAddingManips();
	updateManipLocations();

    MPxManipContainer::connectToDependNode(node);        
    return stat;
}
Example #2
0
//
// Write out the 'addAttr' and 'setAttr' commands for a node.
//
void maTranslator::writeNodeAttrs(
		fstream& f, const MObject& node, bool isSelected
)
{
	MFnDependencyNode	nodeFn(node);

	if (nodeFn.canBeWritten())
	{
		MStringArray	addAttrCmds;
		MStringArray	setAttrCmds;

		getAddAttrCmds(node, addAttrCmds);
		getSetAttrCmds(node, setAttrCmds);

		unsigned int	numAddAttrCmds = addAttrCmds.length();
		unsigned int	numSetAttrCmds = setAttrCmds.length();

		if (numAddAttrCmds + numSetAttrCmds > 0)
		{
			//
			// If the node is not already selected, then issue a command to
			// select it.
			//
			if (!isSelected) writeSelectNode(f, node);

			unsigned int i;

			for (i = 0; i < numAddAttrCmds; i++)
				f << addAttrCmds[i].asChar() << endl;

			for (i = 0; i < numSetAttrCmds; i++)
				f << setAttrCmds[i].asChar() << endl;
		}
	}
}
Example #3
0
//
// Write out a 'createNode' command for a DAG node.
//
void maTranslator::writeCreateNode(
		fstream& f, const MDagPath& nodePath, const MDagPath& parentPath
)
{
	MObject		node(nodePath.node());
	MFnDagNode	nodeFn(node);

	//
	// Write out the 'createNode' command for this node.
	//
	f << "createNode " << nodeFn.typeName().asChar();

	//
	// If the node is shared, then add a "-s/shared" flag to the command.
	//
	if (nodeFn.isShared()) f << " -s";

	f << " -n \"" << nodeFn.name().asChar() << "\"";

	//
	// If this is not a top-level node, then include its first parent in the
	// command.
	//
	if (parentPath.length() > 0)
		f << " -p \"" << parentPath.partialPathName().asChar() << "\"";
   
	f << ";" << endl;
}
Example #4
0
MStatus
MannequinMoveManipulator::connectToDependNode(const MObject &dependNode) {
  MStatus status;
  MFnDependencyNode nodeFn(dependNode, &status);

  if (!status)
     return MS::kFailure;

  MPlug translatePlug = nodeFn.findPlug("translate", &status);

  if (!status)
     return MS::kFailure;

  int plugIndex = 0;
  status = connectPlugToValue(translatePlug, _translateIndex, plugIndex);

  if (!status)
     return MS::kFailure;

  MFnDagNode dagNodeFn(dependNode);
  MDagPath nodePath;
  dagNodeFn.getPath(nodePath);

  MTransformationMatrix m(nodePath.exclusiveMatrix());
  _parentXform = m;

  MTransformationMatrix n(nodePath.inclusiveMatrix());
  _childXform = n;

  finishAddingManips();
  return MPxManipulatorNode::connectToDependNode(dependNode);
}
MObject slopeShaderBehavior::findShadingEngine(MObject &node)
//
//	Description:
//		Given the material MObject this method will
//	return the shading group that it is assigned to.
//	if there is no shading group associated with
//	the material than a null MObject is apssed back.
//
{
	MFnDependencyNode nodeFn(node);
	MPlug srcPlug = nodeFn.findPlug("outColor");
	MPlugArray nodeConnections;
	srcPlug.connectedTo(nodeConnections, false, true);
	//loop through the connections
	//and find the shading engine node that
	//it is connected to
	//
	for(unsigned i = 0; i < nodeConnections.length(); i++)
	{
		if(nodeConnections[i].node().hasFn(MFn::kShadingEngine))
			return nodeConnections[i].node();
	}

	//no shading engine associated so return a
	//null MObject
	//
	return MObject();
}
Example #6
0
void maTranslator::getSetAttrCmds(const MObject& node, MStringArray& cmds)
{
	//
	// Get rid of any garbage already in the array.
	//
	cmds.clear();

	//
	// Run through the node's attributes.
	//
	MFnDependencyNode	nodeFn(node);
	unsigned int		numAttrs = nodeFn.attributeCount();
	unsigned int		i;

	for (i = 0; i < numAttrs; i++)
	{
		//
		// Use the attribute ordering which Maya uses when doing I/O.
		//
		MObject			attr = nodeFn.reorderedAttribute(i);
		MFnAttribute	attrFn(attr);
		MStatus			status;

		attrFn.parent(&status);

		bool			isChild = (status != MS::kNotFound);

		//
		// We don't want attributes which are children of other attributes
		// because they will be processed when we process the parent.
		//
		// And we only want storable attributes which accept inputs.
		//
		if (!isChild && attrFn.isStorable() && attrFn.isWritable())
		{
			//
			// Get a plug for the attribute.
			//
			MPlug	plug(node, attr);

			//
			// Get setAttr commands for this attribute, and any of its
			// children, which have had their values changed by the scene.
			//
			MStringArray	newCmds;

			plug.getSetAttrCmds(newCmds, MPlug::kChanged, false);

			unsigned int	numCommands = newCmds.length();
			unsigned int	c;

			for (c = 0; c < numCommands; c++)
			{
				if (newCmds[c] != "")
					cmds.append(newCmds[c]);
			}
		}
	}
}
void liquidIPR_NodeDirtyCallback( MObject& node,void *userData )
{
	MFnDependencyNode nodeFn(node);
	MGlobal::displayInfo( "liquidIPR_NodeDirtyCallback(" + nodeFn.name()+", userData)");

	//liquid::RendererMgr::getInstancePtr()->getRenderer()
	//	->IPR_NodeDirtyCallback(node, userData);
}
Example #8
0
//
// Write out a "lockNode" command.
//
void maTranslator::writeLockNode(fstream& f, const MObject& node)
{
	MFnDependencyNode	nodeFn(node);

	//
	// By default, nodes are not locked, so we only have to issue a
	// "lockNode" command if the node is locked.
	//
	if (nodeFn.isLocked()) f << "lockNode;" << endl;
}
Example #9
0
void deletedMessage::aboutToDeleteCB(MObject& node, MDGModifier& modifier, void* clientData) {
	MFnDependencyNode nodeFn(node);
	MGlobal::displayInfo(MString("About to delete callback for node: ") + nodeFn.name());

	//
	// If there were any other operations on the DG that needed to be performed
	// before the node was removed, they could be added to the MDGModifier.
	// For example, attributes could be removed from other nodes or connections
	// on related nodes could be disconnected.  In this case there are no 
	// operations to be added so just return.
	//
}
void liquidIPR_NodeDirtyPlugCallback( MObject& node,MPlug& plug,void* userData )
{
	MFnDependencyNode nodeFn(node);
	MGlobal::displayInfo( "liquidIPR_NodeDirtyPlugCallback( " + nodeFn.name()+","+plug.name()+", userData)");


	liqRibTranslator::getInstancePtr()->IPRRenderBegin();

	liquid::RendererMgr::getInstancePtr()->getRenderer()
		->IPR_NodeDirtyPlugCallback(node, plug, userData);

	liqRibTranslator::getInstancePtr()->IPRRenderEnd();
}
Example #11
0
void tm_polySlot::getModifierNodeName()
{
	MDagPath dagPath = getMeshNode();
	MObject meshObject = dagPath.node();
	MFnDependencyNode nodeFn( meshObject);
	MPlug inMeshPlug = nodeFn.findPlug( "inMesh");
	MPlugArray connectedPlugsArray;
	if(	inMeshPlug.connectedTo( connectedPlugsArray, 1, 0))
	{
		MObject modifierNodeObj = connectedPlugsArray[0].node();
		MFnDependencyNode modifierNode( modifierNodeObj);
		modifierNodeName = modifierNode.name();
	}
}
//------------------------------------------------------------
MStatus moveManip::connectToDependNode(const MObject &node)
//------------------------------------------------------------
{
    MStatus stat;

    // Connect the plugs
    //    
	//für späteres onScreenGl
	view = M3dView::active3dView();

	

    MFnDependencyNode nodeFn(node,&stat);
    if(stat == MS::kFailure)stat.perror("Fehler bei depNode: ");


    MPlug tPlug = nodeFn.findPlug("endPoint", &stat);
	if(stat == MS::kFailure)stat.perror("Fehler bei tPlug: ");


    MFnFreePointTriadManip freePointManipFn(fFreePointManip);

	//transFn initialisieren
	transFn.setObject(fFreePointManip);
	
	stat = freePointManipFn.connectToPointPlug(tPlug);
	if(stat == MS::kFailure)stat.perror("Fehler bei connectToPlug: ");

	freePointIndex = freePointManipFn.pointIndex(); 	
/*	
	translatePlugIndex = addManipToPlugConversionCallback(tPlug, 
										 (manipToPlugConversionCallback) 
										 &moveManip::moveOthersCB);
/*
	addPlugToManipConversionCallback(freePointManipFn.pointIndex(),
										 (plugToManipConversionCallback) 
										 &moveManip::moveOthersCBReverse);
*/
	MPlug togglePlug = nodeFn.findPlug("fv");
	
	MFnToggleManip toggleFn(fToggleManip);
	toggleFn.connectToTogglePlug(togglePlug);

	toggleFn.setLength(0.0);
	addPlugToManipConversionCallback(toggleFn.startPointIndex(),
										 (plugToManipConversionCallback) 
										 &moveManip::setPointCB2);

	INVIS(cout<<freePointIndex<<" = freePointIndex "<<endl;)
Example #13
0
MStatus MeshControlCmd::doIt( const MArgList& args )
{
	MStatus s;

	MSelectionList selection;
	MSyntax syn = syntax();
	MArgDatabase argData(syn, args);
	setResult(0);
	if (argData.isFlagSet(m_nameFlag[1], &s))
	{
		MString nodeName;											// 提取某个名字的节点
		s = argData.getFlagArgument(m_nameFlag[1],0, nodeName);
		s = MGlobal::getSelectionListByName(nodeName, selection);
	}
	else
		s = MGlobal::getActiveSelectionList(selection);				// 提取选中节点
	if (!s)return MS::kSuccess;

	bool isInitFlagSet = argData.isFlagSet(m_initFlag[1], &s);

	MItSelectionList pSel(selection, MFn::kDependencyNode , &s);
	MObject obj;
	for (; !pSel.isDone(); pSel.next())
	{
		MObject depNode;
		pSel.getDependNode(depNode);
		MFnDependencyNode nodeFn(depNode, &s);
		MString typeName = nodeFn.typeName(&s);

		if (typeName != NODE_CAGE_DEFORMER_NAME)
			continue;

		CageDeformerNode* node = (CageDeformerNode*)nodeFn.userNode(&s);
		if (!s)
			continue;

		if (isInitFlagSet)
		{
			s = node->computeWeight();
		}
		if (!s)
		{
			MGlobal::displayError("faild to compute weight");
		}
		else
			MGlobal::displayInfo("succeed to compute weight");
	}
	return MS::kSuccess;
}
Example #14
0
bool testExCameraSetCmd::getExCameraSetNode(MObject &dirObj)
{
	// Get the specified cameraSet node.
	MObject dirNode = MObject::kNullObj;
	list.getDependNode(0, dirNode);
	if (dirNode == MObject::kNullObj)
		return false;

	MFnDependencyNode nodeFn(dirNode);
	if (nodeFn.typeId() != exCameraSet::id)
		return false;

	dirObj = dirNode;
	return true;
}
Example #15
0
//
// Write out a 'createNode' command for a non-DAG node.
//
void maTranslator::writeCreateNode(fstream& f, const MObject& node)
{
	MFnDependencyNode	nodeFn(node);

	//
	// Write out the 'createNode' command for this node.
	//
	f << "createNode " << nodeFn.typeName().asChar();

	//
	// If the node is shared, then add a "-s/shared" flag to the command.
	//
	if (nodeFn.isShared()) f << " -s";

	f << " -n \"" << nodeFn.name().asChar() << "\";" << endl;
}
Example #16
0
//
// Write out a "select" command.
//
void maTranslator::writeSelectNode(fstream& f, const MObject& node)
{
	MStatus				status;
	MFnDependencyNode	nodeFn(node);
	MString				nodeName;

	//
	// If the node has a unique name, then we can just go ahead and use
	// that.  Otherwise we will have to use part of its DAG path to to
	// distinguish it from the others with the same name.
	//
	if (nodeFn.hasUniqueName())
		nodeName = nodeFn.name();
	else
	{
		//
		// Only DAG nodes are allowed to have duplicate names.
		//
		MFnDagNode	dagNodeFn(node, &status);

		if (!status)
		{
			MGlobal::displayWarning(
				MString("Node '") + nodeFn.name()
				+ "' has a non-unique name but claimes to not be a DAG node.\n"
				+ "Using non-unique name."
			);

			nodeName = nodeFn.name();
		}
		else
			nodeName = dagNodeFn.partialPathName();
	}

	//
	// We use the "-ne/noExpand" flag so that if the node is a set, we
	// actually select the set itself, rather than its members.
	//
	f << "select -ne ";

	//
	// Default nodes get a colon slapped onto the start of their names.
	//
	if (nodeFn.isDefaultNode()) f << ":";

	f << nodeName.asChar() << ";\n";
}
Example #17
0
void maTranslator::writeDefaultNodes(fstream& f)
{
	//
	// For default nodes we don't write out a createNode statement, but we
	// still write added attributes and changed attribute values.
	//
	unsigned int	numNodes = fDefaultNodes.length();
	unsigned int	i;

	for (i = 0; i < numNodes; i++)
	{
		writeNodeAttrs(f, fDefaultNodes[i], false);

		MFnDependencyNode	nodeFn(fDefaultNodes[i]);

		nodeFn.setFlag(fAttrFlag, true);
	}
}
Example #18
0
//
// If a DAG node is instanced (i.e. has multiple parents), this method
// will put it under its remaining parents.  It will already have been put
// under its first parent when it was created.
//
void maTranslator::writeInstances(fstream& f)
{
	unsigned int numInstancedNodes = fInstanceChildren.length();
	unsigned int i;

	for (i = 0; i < numInstancedNodes; i++)
	{
		MFnDagNode	nodeFn(fInstanceChildren[i]);

		unsigned int numParents = nodeFn.parentCount();
		unsigned int p;

		for (p = 0; p < numParents; p++)
		{
			//
			// We don't want to issue a 'parent' command for the node's
			// existing parent.
			//
			if (nodeFn.parent(i) != fInstanceParents[i].node())
			{
				MObject		parent = nodeFn.parent(i);
				MFnDagNode	parentFn(parent);

				if (!parentFn.isFromReferencedFile())
				{
					//
					// Get the first path to the parent node.
					//
					MDagPath	parentPath;

					MDagPath::getAPathTo(parentFn.object(), parentPath);

					writeParent(f, parentPath, fInstanceChildren[i], true);
				}
			}
		}
	}

	//
	// We don't need this any more, so free up the space.
	//
	fInstanceChildren.clear();
	fInstanceParents.clear();
}
MStatus lrutils::getMetaRootByName(MObject & obj, MString name) {
    MStatus status = MS::kFailure;

    for( MItDependencyNodes nodeIt(MFn::kPluginDependNode);
        !nodeIt.isDone(); nodeIt.next() ) {
        MFnDependencyNode nodeFn( nodeIt.item() );
        if(nodeFn.typeId() == MetaDataManagerNode::id) {
            //Get the plug for the list of metaRoots
            MPlug metaRootsPlug = nodeFn.findPlug(MString("metaRoots"),true,&status);
            MyCheckStatusReturn(status,"findPlug failed");
            //MGlobal::displayInfo( metaRootsPlug.name() );
            
            //follow its connection to all the plugs on connected metaRoots
            MPlugArray rootPlugs;
            metaRootsPlug.connectedTo(rootPlugs,false,true,&status);
            MyCheckStatusReturn(status,"MPlug.connectedTo failed");
            unsigned int numRootPlugs = rootPlugs.length();

            for(unsigned int i = 0; i < numRootPlugs; i++) {
                MObject rootNodeObj = rootPlugs[i].node(&status);
                MyCheckStatusReturn(status,"MPlug.node() failed");
                MFnDependencyNode rootNodeFn( rootNodeObj );

                //get the name of the metaRoot node and compare it to the search string
                MString rootName = rootNodeFn.name();
                rootName = rootName.substring(4,rootName.numChars());
                if( rootName == name ) {
                    obj = rootNodeObj;
                    status = MS::kSuccess;
                    break;
                }
            }
        }
    }

    if(status == MS::kFailure) {
        MGlobal::displayInfo("MetaDataManager node does not exist.\n");        
    }

    return status;
}
Example #20
0
void maTranslator::writeNonDagNodes(fstream& f)
{
	MItDependencyNodes	nodeIter;

	for (; !nodeIter.isDone(); nodeIter.next())
	{
		MObject				node = nodeIter.item();
		MFnDependencyNode	nodeFn(node);

		//
		// Save default nodes for later processing.
		//
		if (nodeFn.isDefaultNode())
		{
			fDefaultNodes.append(node);
		}
		else if (!nodeFn.isFromReferencedFile()
		&&	!nodeFn.isFlagSet(fCreateFlag))
		{
			//
			// If this node is either writable or shared, then write it out.
			// Otherwise don't, but still mark it as having been written so
			// that we don't end up processing it again at some later time.
			//
			if (nodeFn.canBeWritten() || nodeFn.isShared())
			{
				writeCreateNode(f, node);
				writeNodeAttrs(f, node, true);
				writeLockNode(f, node);
			}

			nodeFn.setFlag(fCreateFlag, true);
			nodeFn.setFlag(fAttrFlag, true);
		}
	}
}
void liqIPRNodeMessage::gatherUpdateObjects(std::vector<MString>& objects)
{
	MStatus status;

	//get selection list
	MSelectionList 	selection;
	IfMErrorWarn(MGlobal::getActiveSelectionList( selection ));

	for ( unsigned int i=0; i<selection.length(); i++ )
	{
		MObject node;
		IfMErrorWarn(selection.getDependNode( i, node ));

		MFnDependencyNode nodeFn(node, &status);
		IfMErrorWarn(status);

		const MString nodeName(nodeFn.name());
		objects.push_back(nodeName);//record current node

		if( isShaderNode(nodeName) )
		{
			onShaderNode(nodeName, objects);
		}
		else{
			onOtherNode(nodeName, objects);
		}
	}

	//add current camera shape node
	MStringArray cameraShapeFullPaths;
	IfMErrorWarn(MGlobal::executeCommand("string $cam = `getAttr liquidGlobals.renderCamera`; ls -long $cam;", cameraShapeFullPaths));
	objects.push_back(cameraShapeFullPaths[0]);

	//add current camera transform node

}
Example #22
0
//
// Maya calls this method to have the translator write out a file.
//
MStatus maTranslator::writer(
		const MFileObject& file,
		const MString& /* options */,
		MPxFileTranslator::FileAccessMode mode
)
{
	//
	// For simplicity, we only do full saves/exports.
	//
	if ((mode != kSaveAccessMode) && (mode != kExportAccessMode))
	   	return MS::kNotImplemented;

	//
	// Let's see if we can open the output file.
	//
	fstream	output(file.fullName().asChar(), ios::out | ios::trunc);

	if (!output.good()) return MS::kNotFound;

	//
	// Get some node flags to keep track of those nodes for which we
	// have already done various stages of processing.
	//
	MStatus	status;

	fCreateFlag = MFnDependencyNode::allocateFlag(fPluginName, &status);

	if (status)
		fAttrFlag = MFnDependencyNode::allocateFlag(fPluginName, &status);

	if (status)
		fConnectionFlag = MFnDependencyNode::allocateFlag(fPluginName, &status);

	if (!status)
	{
		MGlobal::displayError(
			"Could not allocate three free node flags."
			"  Try unloading some other plugins."
		);

		return MS::kFailure;
	}

	//
	// Run through all of the nodes in the scene and clear their flags.
	//
	MItDependencyNodes	nodesIter;

	for (; !nodesIter.isDone(); nodesIter.next())
	{
		MObject				node = nodesIter.item();
		MFnDependencyNode	nodeFn(node);

		nodeFn.setFlag(fCreateFlag, false);
		nodeFn.setFlag(fAttrFlag, false);
		nodeFn.setFlag(fConnectionFlag, false);
	}

	//
	// Write out the various sections of the file.
	//
	writeHeader(output, file.name());
	writeFileInfo(output);
	writeReferences(output);
	writeRequirements(output);
	writeUnits(output);
	writeDagNodes(output);
	writeNonDagNodes(output);
	writeDefaultNodes(output);
	writeReferenceNodes(output);
	writeConnections(output);
	writeFooter(output, file.name());

	output.close();

	MFnDependencyNode::deallocateFlag(fPluginName, fCreateFlag);

	return MS::kSuccess;
}
Example #23
0
//
//      Deform computation
//
MStatus jhMeshBlur::deform( MDataBlock& block,MItGeometry& iter,const MMatrix& m,unsigned int multiIndex)
{
    MStatus returnStatus;

    // Envelope
    float envData = block.inputValue(envelope, &returnStatus).asFloat();
	CHECK_MSTATUS(returnStatus);

    if(envData == 0)
		return MS::kFailure;

    /*
     VARIABLES
     */
    //float factor = block.inputValue(aShapeFactor, &returnStatus).asFloat();
    float fStrength = block.inputValue(aStrength, &returnStatus).asFloat();
	CHECK_MSTATUS(returnStatus);
	
	if (fStrength == 0)
		return MS::kFailure;
	
    float fThreshold = block.inputValue(aTreshhold, &returnStatus).asFloat();
	CHECK_MSTATUS(returnStatus);
    float fW = 0.0f; // weight
    float fDistance;
    fStrength *= envData;

    double dKracht = block.inputValue(aInterpPower, &returnStatus).asDouble();
	CHECK_MSTATUS(returnStatus);
    double dDotProduct;  // Dotproduct of the point

    bool bTweakblur = block.inputValue(aTweakBlur, &returnStatus).asBool();
	CHECK_MSTATUS(returnStatus);
	
    bool bQuad = block.inputValue(aQuadInterp, &returnStatus).asBool();
	CHECK_MSTATUS(returnStatus);
	
	MTime inTime = block.inputValue(aTime).asTime();
    int nTijd = (int)inTime.as(MTime::kFilm);


    MFloatVectorArray currentNormals;   // normals of mesh
    MFnPointArrayData fnPoints;         // help converting to MPointArrays
    MFloatVector dirVector;             // direction vector of the point
    MFloatVector normal;                // normal of the point
    MPointArray savedPoints;            // save all point before edited
    MMatrix matInv = m.inverse();       // inversed matrix
    MPoint ptA;                         // current point (iter mesh)
    MPoint ptB;                         // previous point (iter mesh)
    MPoint ptC;                         // mesh before previous point (iter mesh)

    // get node, use node to get inputGeom, use inputGeom to get mesh data, use mesh data to get normal data
    MFnDependencyNode nodeFn(this->thisMObject());

    MPlug inGeomPlug(nodeFn.findPlug(this->inputGeom,true));
    MObject inputObject(inGeomPlug.asMObject());
    MFnMesh inMesh(inputObject);

    inMesh.getVertexNormals(true, currentNormals);

    // get the previous mesh data
    MPlug oldMeshPlug = nodeFn.findPlug(MString("oldMesh"));
    MPlug oldMeshPositionsAPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 0);
    MPlug oldMeshPositionsBPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 1);
    MPlug oldMeshPositionsCPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 2); // cache for tweak mode
    MPlug oldMeshPositionsDPlug = oldMeshPlug.elementByLogicalIndex((multiIndex*4) + 3); // cache for tweak mode

    // convert to MPointArrays
    MObject objOldMeshA;
    MObject objOldMeshB;
    MObject objOldMeshC; // cache
    MObject objOldMeshD; // cache

    oldMeshPositionsAPlug.getValue(objOldMeshA);
    oldMeshPositionsBPlug.getValue(objOldMeshB);
    oldMeshPositionsCPlug.getValue(objOldMeshC); // cache
    oldMeshPositionsDPlug.getValue(objOldMeshD); // cache

    fnPoints.setObject(objOldMeshA);
    MPointArray oldMeshPositionsA = fnPoints.array();
    
    fnPoints.setObject(objOldMeshB);
    MPointArray oldMeshPositionsB = fnPoints.array();
    
    fnPoints.setObject(objOldMeshC);
    MPointArray oldMeshPositionsC = fnPoints.array(); // cache
    
    fnPoints.setObject(objOldMeshD);
    MPointArray oldMeshPositionsD = fnPoints.array(); // cache

    
    
    // If mesh position variables are empty,fill them with default values
    if(oldMeshPositionsA.length() == 0 || nTijd <= 1){
        iter.allPositions(oldMeshPositionsA);

        for(int i=0; i < oldMeshPositionsA.length(); i++)
        {
            // convert to world
            oldMeshPositionsA[i] = oldMeshPositionsA[i] * m;
        }
		
        oldMeshPositionsB.copy(oldMeshPositionsA);
        oldMeshPositionsC.copy(oldMeshPositionsA); // cache
        oldMeshPositionsD.copy(oldMeshPositionsA); // cache
    }
	
	// get back old date again
	if (bTweakblur == true) { // restore cache
		oldMeshPositionsA.copy(oldMeshPositionsC);
		oldMeshPositionsB.copy(oldMeshPositionsD);
	}
    
    
    iter.allPositions(savedPoints);
    for(int i=0; i < savedPoints.length(); i++)
    {
        // convert points to world points
        savedPoints[i] = savedPoints[i] * m;
    }

    // Actual Iteration through points
    for (; !iter.isDone(); iter.next()){
        // get current position
        ptA = iter.position();
        // get old positions
        ptB = oldMeshPositionsA[iter.index()] * matInv;
        ptC = oldMeshPositionsB[iter.index()] * matInv;

        fDistance = ptA.distanceTo(ptB);
        fW = weightValue(block,multiIndex,iter.index());


        if (fDistance * (fStrength*fW) < fThreshold && fThreshold > 0){
            iter.setPosition(ptA);
        } else {
            // aim/direction vector to calculate strength
            dirVector = (ptA - ptB); // (per punt)
            dirVector.normalize();

            normal = currentNormals[iter.index()];

            dDotProduct = normal.x * dirVector.x + normal.y * dirVector.y + normal.z * dirVector.z;

            
            if(bQuad == true){
                MVector vecA(((ptB - ptC) + (ptA - ptB)) / 2);
                vecA.normalize();

                MPoint hiddenPt(ptB + (vecA * fDistance) * dKracht);
                ptA = quadInterpBetween(ptB, hiddenPt, ptA, (1 - fStrength * fW) + (linearInterp(dDotProduct, -1, 1) * (fStrength * fW) ) );
            } else {
                MPoint halfway = (ptA - ptB) * 0.5;
                MPoint offset = halfway * dDotProduct * (fStrength*fW);
                ptA = ptA - ((halfway * (fStrength*fW)) - offset); // + (offset * strength);
            }
            // set new value

            iter.setPosition(ptA);
        }
    }
    if(bTweakblur == false){
        oldMeshPositionsD.copy(oldMeshPositionsB);
        oldMeshPositionsC.copy(oldMeshPositionsA);
        oldMeshPositionsB.copy(oldMeshPositionsA);
        oldMeshPositionsA.copy(savedPoints);

        // Save back to plugs
        objOldMeshA = fnPoints.create(oldMeshPositionsA);
        objOldMeshB = fnPoints.create(oldMeshPositionsB);
        objOldMeshC = fnPoints.create(oldMeshPositionsC);
        objOldMeshD = fnPoints.create(oldMeshPositionsD);
		
        oldMeshPositionsAPlug.setValue(objOldMeshA);
        oldMeshPositionsBPlug.setValue(objOldMeshB);
        oldMeshPositionsCPlug.setValue(objOldMeshC);
        oldMeshPositionsDPlug.setValue(objOldMeshD);
    }
    
    return returnStatus;
}
MStatus	liqAttachPrefAttribute::redoIt()
{
  MFnTypedAttribute tAttr;
  MStatus status;

  for ( unsigned i( 0 ); i < objectNames.length(); i++ ) 
  {
    MSelectionList		nodeList;
    nodeList.add( objectNames[i] );
    MObject depNodeObj;
    nodeList.getDependNode( 0, depNodeObj );
    MDagPath dagNode;
    nodeList.getDagPath( 0, dagNode );
    MFnDependencyNode depNode( depNodeObj );
    MObject prefAttr;
    MString attrName, varName;

    // make sure the renderer description is up to date
    liqglo.liquidRenderer.setRenderer();

    // build the name of the attribute
    varName = ( ( exportN && depNodeObj.hasFn( MFn::kMesh ) )? "N":"P" );
    attrName = "rman";
    attrName += varName;
    attrName += ( ( liqglo.liquidRenderer.requires__PREF )? "__":"" );
    attrName += varName + "ref";

    // create the attribute
    prefAttr = tAttr.create( attrName, attrName, MFnData::kPointArray );


    if ( depNodeObj.hasFn( MFn::kNurbsSurface ) ) 
    {
      MFnNurbsSurface nodeFn( depNodeObj );
      MPointArray nodePArray;
      MItSurfaceCV cvs( dagNode, MObject::kNullObj, liqglo.liquidRenderer.requires_SWAPPED_UVS == false, &status );

      while( !cvs.isDone() ) 
      {
        while( !cvs.isRowDone() ) 
        {
          MPoint pt = (worldSpace)? cvs.position( MSpace::kWorld ) : cvs.position( MSpace::kObject );
          nodePArray.append( pt );
          cvs.next();
        }
        cvs.nextRow();
      }

      nodeFn.addAttribute( prefAttr );
      MFnPointArrayData pArrayData;

      MObject prefDefault = pArrayData.create( nodePArray );
      MPlug nodePlug( depNodeObj, prefAttr );
      nodePlug.setValue( prefDefault );
    } 
    else if ( depNodeObj.hasFn( MFn::kNurbsCurve ) ) 
    {
      // Carsten: added support for PREF on nurbs curves
      //
      MFnNurbsCurve nodeFn( depNodeObj );
      MPointArray nodePArray;
      nodeFn.getCVs( nodePArray );

      nodeFn.addAttribute( prefAttr );
      MFnPointArrayData pArrayData;

      MObject prefDefault = pArrayData.create( nodePArray );
      MPlug nodePlug( depNodeObj, prefAttr );
      nodePlug.setValue( prefDefault );
    } 
    else if ( depNodeObj.hasFn( MFn::kMesh ) ) 
    {
      MFnMesh nodeFn( depNodeObj );
      // Moritz: modified this line to dim nodePArray -- otherwise
      // nodePArray.set() in the wile loop below throws an exception
      // which was why __Pref didn't work
      MPointArray nodePArray( MFnMesh( depNodeObj ).numVertices() );
      unsigned count;

      nodeFn.addAttribute( prefAttr );

      if ( exportN ) 
      {
        // export Nref
        unsigned vertex;
        unsigned normal;
        unsigned face = 0;
        unsigned faceVertex = 0;
        unsigned int numNormals = nodeFn.numNormals();
        unsigned int numPoints  = nodeFn.numVertices();
        MFloatVectorArray normals;
        MVectorArray normalAttArray;
        nodeFn.getNormals( normals );

        if ( numNormals > numPoints ) 
        {
          // if we get more than 1 normal per vertex,
          // force the arraysize to the full facevarying size
          unsigned faceVaryingCount( 0 );
          for ( unsigned pOn( 0 ); pOn < nodeFn.numPolygons(); pOn++ ) 
            faceVaryingCount += nodeFn.polygonVertexCount( pOn );
          
          normalAttArray.setLength( faceVaryingCount );
        } 
        else 
          normalAttArray.setLength(normals.length());
        
        for ( MItMeshPolygon polyIt ( depNodeObj ); polyIt.isDone() == false; polyIt.next() ) 
        {
          count = polyIt.polygonVertexCount();
          while ( count > 0 ) 
          {
            --count;
            normal = polyIt.normalIndex( count );
            vertex = polyIt.vertexIndex( count );

            if( numNormals == numPoints )
              normalAttArray.set(normals[normal], vertex);
            else
              normalAttArray.set(normals[normal], faceVertex);

            ++faceVertex;
          }
          ++face;
        }

        MFnVectorArrayData pArrayData;
        MObject prefDefault = pArrayData.create( normalAttArray );
        MPlug nodePlug( depNodeObj, prefAttr );
        nodePlug.setValue( prefDefault );

      } 
      else 
      {
        // TODO: do we need to account for the altMeshExport algo that's
        // used in liquidRibMeshData?
        // Moritz: no, it's basically the same as the algo below
        for ( MItMeshPolygon polyIt( dagNode, MObject::kNullObj ); !polyIt.isDone(); polyIt.next()) 
        {
          count = polyIt.polygonVertexCount();

          while ( count > 0 ) 
          {
            --count;
            unsigned	vertexIndex = polyIt.vertexIndex( count );
            MPoint nodePoint = (worldSpace)? polyIt.point( count, MSpace::kWorld ) : polyIt.point( count, MSpace::kObject );
            // Moritz: this returns MS::kFailure but seems to work?!
            nodePArray.set( nodePoint, vertexIndex );
          }
        }

        MFnPointArrayData pArrayData;
        MObject prefDefault = pArrayData.create( nodePArray );
        MPlug nodePlug( depNodeObj, prefAttr );
        nodePlug.setValue( prefDefault );

      }
    } else cerr << "Neither a Nurbs nor a Mesh !!" << endl;
  }
  return MS::kSuccess;
}
Example #25
0
void liqRibData::addAdditionalSurfaceParameters( MObject node )
{
  LIQDEBUGPRINTF("-> scanning for additional rman surface attributes \n");
  MStatus status = MS::kSuccess;
  unsigned i;

  // work out how many elements there would be in a facevarying array if a mesh or subD
  // faceVaryingCount is a private data member
  if ( ( type() == MRT_Mesh ) || ( type() == MRT_Subdivision ) ) {
    faceVaryingCount = 0;
    MFnMesh fnMesh( node );
    for ( uint pOn = 0; pOn < fnMesh.numPolygons(); pOn++ ) {
      faceVaryingCount += fnMesh.polygonVertexCount( pOn );
    }
  }

  // find how many additional
  MFnDependencyNode nodeFn( node );

  // find the attributes
  MStringArray floatAttributesFound  = findAttributesByPrefix( "rmanF", nodeFn );
  MStringArray pointAttributesFound  = findAttributesByPrefix( "rmanP", nodeFn );
  MStringArray vectorAttributesFound = findAttributesByPrefix( "rmanV", nodeFn );
  MStringArray normalAttributesFound = findAttributesByPrefix( "rmanN", nodeFn );
  MStringArray colorAttributesFound  = findAttributesByPrefix( "rmanC", nodeFn );
  MStringArray stringAttributesFound = findAttributesByPrefix( "rmanS", nodeFn );


  if ( floatAttributesFound.length() > 0 ) {
    for ( i = 0; i < floatAttributesFound.length(); i++ ) {
      liqTokenPointer tokenPointerPair;
      MString cutString = floatAttributesFound[i].substring(5, floatAttributesFound[i].length());
      MPlug fPlug = nodeFn.findPlug( floatAttributesFound[i] );
      MObject plugObj;
      status = fPlug.getValue( plugObj );
      if ( plugObj.apiType() == MFn::kDoubleArrayData ) {
        MFnDoubleArrayData  fnDoubleArrayData( plugObj );
        MDoubleArray doubleArrayData = fnDoubleArrayData.array( &status );
        tokenPointerPair.set( cutString.asChar(),
                              rFloat,
                              ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                              true,
                              false,
                              doubleArrayData.length() );
        for( unsigned int kk = 0; kk < doubleArrayData.length(); kk++ ) {
          tokenPointerPair.setTokenFloat( kk, doubleArrayData[kk] );
        }
        if ( ( type() == MRT_NuCurve ) && ( cutString == MString( "width" ) ) ) {
          tokenPointerPair.setDetailType( rVarying);
        } else if ( ( ( type() == MRT_Mesh ) || ( type() == MRT_Subdivision ) ) && ( doubleArrayData.length() == faceVaryingCount ) ) {
          tokenPointerPair.setDetailType( rFaceVarying);
        } else {
          tokenPointerPair.setDetailType( rVertex );
        }
      } else {

        if( fPlug.isArray() ) {

          int nbElts = fPlug.evaluateNumElements();
          float floatValue;
          tokenPointerPair.set( cutString.asChar(),
                                rFloat,
                                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                                false,
                                true, // philippe :passed as uArray, otherwise it will think it is a single float
                                nbElts );
          MPlug elementPlug;
          for( unsigned int kk = 0; kk < nbElts; kk++ ) {
            elementPlug = fPlug.elementByPhysicalIndex(kk);
            elementPlug.getValue( floatValue );
            tokenPointerPair.setTokenFloat( kk, floatValue );
          }
          tokenPointerPair.setDetailType( rConstant );

        } else {

          float floatValue;
          tokenPointerPair.set( cutString.asChar(),
                                rFloat,
                                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                                false,
                                false,
                                0 );
          fPlug.getValue( floatValue );
          tokenPointerPair.setTokenFloat( 0, floatValue );
          tokenPointerPair.setDetailType( rConstant );

        }

      }
      tokenPointerArray.push_back( tokenPointerPair );
    }
  }

  if ( pointAttributesFound.length() > 0 ) {
    for ( i = 0; i < pointAttributesFound.length(); i++ ) {
      liqTokenPointer tokenPointerPair;
      MString cutString = pointAttributesFound[i].substring(5, pointAttributesFound[i].length());
      MPlug pPlug = nodeFn.findPlug( pointAttributesFound[i] );
      MObject plugObj;
      status = pPlug.getValue( plugObj );
      if ( plugObj.apiType() == MFn::kPointArrayData ) {
        MFnPointArrayData  fnPointArrayData( plugObj );
        MPointArray pointArrayData = fnPointArrayData.array( &status );
        tokenPointerPair.set( cutString.asChar(),
                              rPoint,
                              ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                              true,
                              false,
                              pointArrayData.length() );
        if ( type() == MRT_Nurbs || type() == MRT_NuCurve ) {
          for ( int kk = 0; kk < pointArrayData.length(); kk++ ) {
            tokenPointerPair.setTokenFloat( kk, pointArrayData[kk].x, pointArrayData[kk].y, pointArrayData[kk].z, pointArrayData[kk].w );
          }
        } else {
          for ( int kk = 0; kk < pointArrayData.length(); kk++ ) {
            tokenPointerPair.setTokenFloat( kk, pointArrayData[kk].x, pointArrayData[kk].y, pointArrayData[kk].z );
          }
        }
        tokenPointerPair.setDetailType( rVertex );
      } else {
        // Hmmmm float ? double ?
        float x, y, z;
        tokenPointerPair.set(
                cutString.asChar(),
                rPoint,
                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                false,
                false,
                0 );
        // Hmmm should check as for arrays if we are in nurbs mode : 4 values
        pPlug.child(0).getValue( x );
        pPlug.child(1).getValue( y );
        pPlug.child(2).getValue( z );
        tokenPointerPair.setTokenFloat( 0, x, y, z );
        tokenPointerPair.setDetailType( rConstant );
      }
      tokenPointerArray.push_back( tokenPointerPair );
    }
  }
  parseVectorAttributes( nodeFn, vectorAttributesFound, rVector );
  parseVectorAttributes( nodeFn, normalAttributesFound, rNormal );
  parseVectorAttributes( nodeFn, colorAttributesFound,  rColor  );

  if ( stringAttributesFound.length() > 0 ) {
    for ( i = 0; i < stringAttributesFound.length(); i++ ) {
      liqTokenPointer tokenPointerPair;
      MString cutString = stringAttributesFound[i].substring(5, stringAttributesFound[i].length());
      MPlug sPlug = nodeFn.findPlug( stringAttributesFound[i] );
      MObject plugObj;
      status = sPlug.getValue( plugObj );
      tokenPointerPair.set(
        cutString.asChar(),
        rString,
        ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
        false,
        false,
        0 );
      MString stringVal;
      sPlug.getValue( stringVal );
      tokenPointerPair.setTokenString( 0, stringVal.asChar(), stringVal.length() );
      tokenPointerPair.setDetailType( rConstant );
      tokenPointerArray.push_back( tokenPointerPair );
    }
  }
}
Example #26
0
MStatus CmpMeshModifierCmd::doIt( const MDagPath &dagPath, const MTypeId &meshModType )
{
	MStatus stat;
	
	meshShapePath = dagPath;
	if( !meshShapePath.isValid() )
	{
		displayError( "Invalid mesh shape path: " + meshShapePath.fullPathName() );
		return MS::kFailure;
	}
	
	meshModifierNodeType = meshModType;
	
	//
	// Get the current state of the history
	//
	MFnDagNode origShapeNodeFn( meshShapePath );
	
	// Determine if the mesh has history
	MPlug inMeshOrigPlug = origShapeNodeFn.findPlug( "inMesh" );
	hasHistory = inMeshOrigPlug.isConnected();
	
	// Determine if the mesh has tweaks
	hasInternalTweaks = false;
	MPlug tweaksPlug = origShapeNodeFn.findPlug( "pnts" );
	if( !tweaksPlug.isNull() )
	{
		MObject obj;
		MPlug tweakPlug;
		MFloatVector tweak;
		unsigned int i;
		unsigned int nTweaks = tweaksPlug.numElements();
		for( i=0; i < nTweaks; i++ )
		{
			tweakPlug = tweaksPlug.elementByPhysicalIndex( i, &stat );
			if( stat && !tweakPlug.isNull() )
			{
				tweakPlug.getValue( obj );
				MFnNumericData numDataFn( obj );
				numDataFn.getData( tweak[0], tweak[1], tweak[2] );
				
				if( tweak[0] != 0.0f || tweak[1] != 0.0f || tweak[2] != 0.0f )
				{
					hasInternalTweaks = true;
					break;
				}
			}
		}
	}
	
	int res;
	MGlobal::executeCommand( "constructionHistory -query -toggle", res );
	genHistory = res != 0;
	
	//MGlobal::displayInfo( MString("resulting: ") + hasHistory + " " + hasInternalTweaks + " " + genHistory + "\n" );
	
	// When there is no existing history
	// cache the mesh data for later undoing
	//
	if( !hasHistory )
	{
		MPlug meshPlug = origShapeNodeFn.findPlug( hasInternalTweaks ? "cachedInMesh" : "outMesh" );
		meshPlug.getValue( origMeshData );
	}
	
	// Create the modifier node
	MObject modNode = dagMods[0].MDGModifier::createNode( meshModifierNodeType, &stat );
	// Create tweak node
	MObject tweakNode = dagMods[0].MDGModifier::createNode( "polyTweak", &stat );
	// Execute DAG modifier to ensure that the nodes actually exist
	dagMods[0].doIt(); 
	
	// Check that the inMesh and outMesh attributes exist in the modifier node
	MFnDependencyNode nodeFn( modNode );
	if( nodeFn.attribute( "inMesh" ).isNull() || nodeFn.attribute( "outMesh" ).isNull() )
	{
		displayError( "Invalid modifier node. It doesn't have inMesh and/or outMesh attributes" );
		return MS::kFailure;
	}

	// Let the derived command class initialize the modifier node
	initModifierNode( modNode, dagMods[1] );
	MFnDependencyNode modNodeFn( modNode );
		
	// Get plug that is the start of the new stream
	MPlug newStreamInMeshPlug = modNodeFn.findPlug( "inMesh" );
		
	// Get the plug connecting into original shape's inMesh
	MPlugArray inPlugs;
	inMeshOrigPlug.connectedTo( inPlugs, true, false );
	MPlug oldStreamOutMeshPlug;
	// N.B. For meshes without construction history
	// there won't be incoming connection
	if( inPlugs.length() )
	{
		oldStreamOutMeshPlug = inPlugs[0];		
		
		// Disconnect the connection into the mesh shape's inMesh attribute.
		// The outMesh of the modifier node will later connect into this.
		dagMods[1].disconnect( oldStreamOutMeshPlug, inMeshOrigPlug );
	}
		
	if( hasInternalTweaks )
	{
		// Transfer tweaks from the mesh shape to the tweak node
		transferTweaks( meshShapePath, tweakNode, dagMods[1] );
		
		MFnDependencyNode tweakNodeFn( tweakNode );
		newStreamInMeshPlug = tweakNodeFn.findPlug( "inputPolymesh" );
		
		// Connect output of tweak node into modifier node		
		MPlug inMeshModPlug = modNodeFn.findPlug( "inMesh" );
		MPlug outMeshTweakPlug = tweakNodeFn.findPlug( "output" );
		dagMods[1].connect( outMeshTweakPlug, inMeshModPlug );
	}

	dagMods[1].doIt();
	
	copyTransform = MObject::kNullObj;
	
	// Generate history for shape that doesn't have one
	if( !hasHistory ) //&& genHistory )
	{		
		// Duplicate the mesh shape node
		copyTransform = origShapeNodeFn.duplicate();
		MFnDagNode copyTransformFn( copyTransform );
		
		MObject copyShapeNode = copyTransformFn.child(0);
		MFnDagNode copyShapeNodeFn( copyShapeNode );
		
		//MGlobal::displayInfo( MString("copy: transform: ") + copyTransformFn.fullPathName() + " shape name: " + copyShapeNodeFn.fullPathName() + "\n" );
				
		// Set it to be an intermediate object
		dagMods[2].commandToExecute( "setAttr " + copyShapeNodeFn.fullPathName() + ".intermediateObject true" );
		
		// Set output plug of old stream to be the outMesh of the duplicated shape
		oldStreamOutMeshPlug = copyShapeNodeFn.findPlug( "outMesh" );
				
		// Rename the duplicate
		dagMods[2].renameNode( copyShapeNode, copyShapeNodeFn.name() + "Orig" );
		
		// Reparent the shape
		MObject origTransform = meshShapePath.transform();
		dagMods[2].reparentNode( copyShapeNode, origTransform );
		
		// Remove the now orphaned transform
		// N.B. calling deleteNode( transformCopy ) causes the shape node to
		// also be deleted, even though it has been reparented to the original mesh.
		// As such, the MEL command "delete" was used instead.
		//
		// The deleteNode() method does some
		// preparation work before it enqueues itself in the MDagModifier list
		// of operations, namely, it looks at it's parents and children and
		// deletes them as well if they are the only parent/child of the node
		// scheduled to be deleted.
		dagMods[2].commandToExecute( "delete " + copyTransformFn.fullPathName() );
	}	
	
	if( !oldStreamOutMeshPlug.isNull() )
		// Connect output mesh of the previous stream the input of the new stream
		dagMods[2].connect( oldStreamOutMeshPlug, newStreamInMeshPlug );
		
	// Connect output of the mesh modifier node to the input of the original mesh shape
	MPlug outMeshModPlug = modNodeFn.findPlug( "outMesh" );
	dagMods[2].connect( outMeshModPlug, inMeshOrigPlug );
	
	if( !hasHistory && !genHistory )
		// Collapse the history
		dagMods[2].commandToExecute( MString("delete -constructionHistory ") + meshShapePath.fullPathName() );
	
	dagMods[2].doIt();
	
	return MS::kSuccess;
}
Example #27
0
void maTranslator::writeReferenceNodes(fstream& f)
{
	//
	// We don't write out createNode commands for reference nodes, but
	// we do write out parenting between them and non-reference nodes,
	// as well as attributes added and attribute values changed after the
	// referenced file was loaded
	//
	writeRefNodeParenting(f);

	//
	// Output the commands for DAG nodes first.
	//
	MItDag	dagIter;

	for (dagIter.next(); !dagIter.isDone(); dagIter.next())
	{
		MObject				node = dagIter.item();
		MFnDependencyNode	nodeFn(node);

		if (nodeFn.isFromReferencedFile()
		&&	!nodeFn.isFlagSet(fAttrFlag))
		{
			writeNodeAttrs(f, node, false);

			//
			// Make note of any connections to this node which have been
			// broken by the main scene.
			//
			MFileIO::getReferenceConnectionsBroken(
				node, fBrokenConnSrcs, fBrokenConnDests, true, true
			);

			nodeFn.setFlag(fAttrFlag, true);
		}
	}

	//
	// Now do the remaining, non-DAG nodes.
	//
	MItDependencyNodes	nodeIter;

	for (; !nodeIter.isDone(); nodeIter.next())
	{
		MObject				node = nodeIter.item();
		MFnDependencyNode	nodeFn(node);

		if (nodeFn.isFromReferencedFile()
		&&	!nodeFn.isFlagSet(fAttrFlag))
		{
			writeNodeAttrs(f, node, false);

			//
			// Make note of any connections to this node which have been
			// broken by the main scene.
			//
			MFileIO::getReferenceConnectionsBroken(
				node, fBrokenConnSrcs, fBrokenConnDests, true, true
			);

			nodeFn.setFlag(fAttrFlag, true);
		}
	}
}
Example #28
0
/** Create a RIB representation of the given node in the DAG as a ribgen.
 */
liqRibObj::liqRibObj( const MDagPath &path, ObjectType objType )
:
  written( 0 ),
  instanceMatrices(),
  objectHandle( NULL ),
  referenceCount( 0 ),
  data()
{
  LIQDEBUGPRINTF( "-> creating dag node handle rep\n");

  MStatus status;
  MObject obj( path.node() );
  MObject skip;

  //lightSources = NULL;
  MFnDagNode nodeFn( obj );

  // Store the matrices for all instances of this node at this time
  // so that they can be used to determine if this node's transformation
  // is animated.  This information is used for doing motion blur.
  MDagPathArray instanceArray;
  nodeFn.getAllPaths( instanceArray );
  unsigned last( instanceArray.length() );
  instanceMatrices.resize( last );
  for ( unsigned i( 0 ); i < last; i++ ) instanceMatrices[ i ] = instanceArray[ i ].inclusiveMatrix();

  LIQDEBUGPRINTF( "-> checking handles display status\n");

  ignore = !areObjectAndParentsVisible( path );
  if ( !ignore ) ignore = !areObjectAndParentsTemplated( path );
  if ( !ignore ) ignore = !isObjectPrimaryVisible( path );

  // check that the shape's transform does not a have a liqIgnoreShapes attribute.
  ignoreShapes = false;
  MDagPath searchPath( path );
  while ( searchPath.apiType() != ( MFn::kTransform ) && searchPath.length() > 1 ) searchPath.pop();
  
  MFnDagNode transformDN( searchPath );
  status.clear();
  MPlug ignorePlug = transformDN.findPlug( "liqIgnoreShapes", &status );
  if ( status == MS::kSuccess ) ignorePlug.getValue( ignoreShapes );

  ignoreShadow = !isObjectCastsShadows( path );
  if ( !ignoreShadow ) ignoreShadow = !areObjectAndParentsVisible( path );
  if ( !ignoreShadow ) ignoreShadow = !areObjectAndParentsTemplated( path );
  
  receiveShadow = isObjectReceivesShadows( path );

  // don't bother storing it if it's not going to be visible!
  LIQDEBUGPRINTF( "-> about to create rep\n");

  if ( !ignore || !ignoreShadow ) 
  {
    if ( objType == MRT_RibGen ) 
    {
      type = MRT_RibGen;
      data = liqRibDataPtr( new liqRibGenData( obj, path ) );
    } 
    else 
    {
      // check to see if object's class is derived from liqCustomNode
      liqCustomNode *customNode( NULL );
      MFnDependencyNode mfnDepNode( obj, &status );
      if ( status ) 
      {
        MPxNode *mpxNode( mfnDepNode.userNode() );
        if ( mpxNode ) 
          customNode = dynamic_cast< liqCustomNode* >( mpxNode ); // will be NULL if cast is not invalid
      }
      // Store the geometry/light/shader data for this object in RIB format
      if ( customNode ) 
      {
        type = MRT_Custom;
        data = liqRibDataPtr( new liqRibCustomNode( (( !ignoreShapes )? obj : skip ), customNode ) );
      } 
      else if ( obj.hasFn(MFn::kNurbsSurface) ) 
      {
        type = MRT_Nurbs;
        data = liqRibDataPtr( new liqRibSurfaceData( ( !ignoreShapes )? obj : skip ) );
      } 
      else if ( obj.hasFn(MFn::kSubdiv) ) 
      {
        type = MRT_Subdivision;
        data = liqRibDataPtr( new liqRibMayaSubdivisionData( ( !ignoreShapes )? obj : skip ) );
      } 
      else if ( obj.hasFn(MFn::kNurbsCurve) ) 
      {
        type = MRT_NuCurve;
        data = liqRibDataPtr( new liqRibNuCurveData( ( !ignoreShapes )? obj : skip ) );
      } 
      else if ( obj.hasFn(MFn::kPfxGeometry) ) 
      {
	      type = objType;
        data = liqRibDataPtr( new liqRibPfxData( (( !ignoreShapes )? obj : skip), objType ) );
      } 
      else if ( obj.hasFn( MFn::kPfxToon ) ) 
      {
        type = MRT_PfxToon;
        data = liqRibDataPtr( new liqRibPfxToonData( ( !ignoreShapes )? obj : skip ) );
      } 
      else if ( obj.hasFn( MFn::kPfxHair ) ) 
      {
        type = MRT_PfxHair;
        //LIQDEBUGPRINTF( "--> new liqRibPfxHairData\n");
        data = liqRibDataPtr( new liqRibPfxHairData( ( !ignoreShapes )? obj : skip ) );
      } 
      else if ( obj.hasFn( MFn::kParticle ) || obj.hasFn( MFn::kNParticle ) ) 
      {
        type = MRT_Particles;
        data = liqRibDataPtr( new liqRibParticleData( ( !ignoreShapes )? obj : skip ) );
      } 
      // if you want to use plugin shapes as placeholders for example
			// i.e. you want to use shave & haircut and attach a custom shader to it
			else if ( obj.hasFn( MFn::kPluginShape ) )
			{
				type = MRT_Weirdo; // lets use this at least once :)
				data = liqRibDataPtr( new liqRibSurfaceData( skip ) ); // you could use any here
			}
      else if ( obj.hasFn( MFn::kMesh ) ) 
      {
        float   	areaIntensity;
        // may be explicit "areaLight" attribute would be better ...
        liquidGetPlugValue( nodeFn, "areaIntensity", areaIntensity, status );
        if ( status == MS::kSuccess )
        {
          // it should be AreaLight ( until better solution...)
          type = MRT_Light;
          data = liqRibDataPtr( new liqAreaLightData( ( !ignoreShapes )? obj : skip ) );
        }
        else
        { 
          // we know we are dealing with a mesh here, now we check to see if it
          // needs to be handled as a subdivision surface
          bool usingSubdiv ( false );
          liquidGetPlugValue( nodeFn, "liqSubdiv", usingSubdiv, status );

          bool usingSubdivOld ( false );
          liquidGetPlugValue( nodeFn, "subDMesh", usingSubdivOld, status );
 
          // make Liquid understand MTOR subdiv attribute
          bool usingSubdivMtor ( false );
          if ( liqglo_useMtorSubdiv ) 
            liquidGetPlugValue( nodeFn, "mtorSubdiv", usingSubdivMtor, status );

          usingSubdiv |= usingSubdivMtor | usingSubdivOld;
          if ( usingSubdiv ) 
          {
            // we've got a subdivision surface
            bool useHierarchicalSubdiv ( false );
            liquidGetPlugValue( nodeFn, "liqHierarchicalSubdiv", useHierarchicalSubdiv, status );
            
            type = MRT_Subdivision;
					  if ( useHierarchicalSubdiv )
						  data = liqRibDataPtr( new liqRibHierarchicalSubdivisionData( ( !ignoreShapes )? obj : skip ) );
					  else
						  data = liqRibDataPtr( new liqRibSubdivisionData( ( !ignoreShapes )? obj : skip ) );
          } 
          else 
          {
            // it's a regular mesh
            type = MRT_Mesh;
            data = liqRibDataPtr( new liqRibMeshData( ( !ignoreShapes )? obj : skip ) );
          }
        }
      } 
      else if ( obj.hasFn( MFn::kLight ) ) 
      {
        type = MRT_Light;
        data = liqRibDataPtr( new liqRibLightData( path ) );
      } 
      else if ( obj.hasFn( MFn::kLocator ) ) 
      {
        if ( mfnDepNode.typeName() == "liquidCoordSys" ) 
        {
          MStatus status;
          int coordSysType = 0;
          MPlug typePlug( mfnDepNode.findPlug( "type", &status ) );
          if ( MS::kSuccess == status ) typePlug.getValue( coordSysType );
          if ( coordSysType == 5 ) 
          {
            type = MRT_ClipPlane;
            data = liqRibDataPtr( new liqRibClipPlaneData( obj ) );
          } 
          else 
          {
            type = MRT_Coord;
            data = liqRibDataPtr( new liqRibCoordData( obj ) );
          }
        } 
        else
        {
          bool isCurveGroup( false );
				  if ( mfnDepNode.typeName() == "liqBoundingBoxLocator" )
				  {
            liquidGetPlugValue( mfnDepNode, "liquidCurveGroup", isCurveGroup, status );
					  if ( isCurveGroup )
					  {
						  type = MRT_Curves;
						  //if ( liqglo_renderAllCurves ) data = liqRibDataPtr( new liqRibCurvesData( obj ) );
						  //else                          data = liqRibDataPtr( new liqRibCurvesData( skip ) );
              data = liqRibDataPtr( new liqRibCurvesData( obj ) );
					  }
				  }
				  if ( !isCurveGroup )
				  {
					  type = MRT_Locator;
					  data = liqRibDataPtr( new liqRibLocatorData( obj ) );
				  }
        }
      } 
      else if ( obj.hasFn( MFn::kImplicitSphere ) ) 
      {
        type = MRT_ImplicitSphere;
        if ( !ignoreShapes ) data = liqRibDataPtr( new liqRibImplicitSphereData( obj ) );
        else                 data = liqRibDataPtr( new liqRibImplicitSphereData( skip ) );
      }
    }

    data->objDagPath = path;
  } 
  LIQDEBUGPRINTF( "==> done creating rep %s\n", path.fullPathName().asChar() );
}
Example #29
0
void deletedMessage::removeCB(MObject& node, void* clientData) {
	MFnDependencyNode nodeFn(node);
	MGlobal::displayInfo(MString("Removal callback node: ") + nodeFn.name());
}
Example #30
0
MStatus testExCameraSetCmd::doIt( const MArgList& args)
//
// Parses the given command line arguments and executes them.
//
{
	MStatus status = parseArgs(args);
	if (status != MS::kSuccess)
	{
		MGlobal::displayError("Error parsing argument list");
		return status;
	}

	bool nothingSet = (	!createUsed && !appendCameraUsed && !appendCameraAndSetUsed && !deleteLayerUsed && !cameraUsed && 
						!layerUsed && !helpUsed && !setUsed && !layerTypeUsed && !numLayersUsed);

	if (nothingSet)
	{
		MGlobal::displayError("A flag must be used. testCameraSet -help for availible flags.");
		return MS::kFailure;
	}

	if (helpUsed) {
		MGlobal::displayInfo("testExCameraSet -help");
		MGlobal::displayInfo("\ttestExCameraSet tests the functionality of the exCameraSet node.");
		MGlobal::displayInfo("");
		MGlobal::displayInfo("\t-h -help : This message is printed");
		MGlobal::displayInfo("\t-a -active [true/false]: Set/get whether a particular layer is active");
		MGlobal::displayInfo("\t-ac -appendCamera <cameraName>: Append a new camera layer to the cameraSet using the specified camera");
		MGlobal::displayInfo("\t-acs -appendCameraAndSet <cameraName> <setName>: Append a new camera layer to the cameraSet using the specified camera and set");
		MGlobal::displayInfo("\t-cam -camera [<cameraName>]: Set/get the camera for a particular layer");
		MGlobal::displayInfo("\t-c -create : Create a new cameraSet node");
		MGlobal::displayInfo("\t-d -deleteLayer <layerIndex>: Delete the layer at the given index");
		MGlobal::displayInfo("\t-nl -numLayers: Returns the number of layers defined in the specified cameraSet");
		MGlobal::displayInfo("\t-l -layer <layerIndex>: Specifies the layer index to be used when accessing layer information");
		MGlobal::displayInfo("\t-lt -layerType [<layerTypeName>]: Set/get the layer type for a particular layer.  Possible values are Mono, Left, and Right.");
		MGlobal::displayInfo("\t-s -set [<setName>]: Set/get the set for a particular layer");
		MGlobal::displayInfo("\t-e -edit : Perform an edit operation");
		MGlobal::displayInfo("\t-q -query : Perform a query operation");
		MGlobal::displayInfo("");
	}

	unsigned nObjs = list.length();
	if (nObjs == 0)
	{
		if (createUsed)
		{
			// Create a new cameraSet node.
			MFnDependencyNode dirFn;
			MString noName;
			MObject dirObj = dirFn.create(exCameraSet::id, noName, &status);
			if (!status)
			{
				MGlobal::displayError("Could not create a cameraSet node");
				return status;
			}

			MGlobal::select(dirObj, MGlobal::kReplaceList);
			return status;
		}

		if (appendCameraUsed || appendCameraAndSetUsed || deleteLayerUsed || editUsed || cameraUsed || 
				setUsed || layerTypeUsed || activeUsed || numLayersUsed) {
			MGlobal::displayError("Must specify a cameraSet node");
			status = MS::kFailure;
			return status;
		}
	}
	else
	{
		if (createUsed)
		{
			MGlobal::displayError("-create cannot have any object specifed");
			status = MS::kFailure;
			return status;
		}

		if (appendCameraUsed)
		{
			if (nObjs != 1)
			{
				MGlobal::displayError("-appendCamera must have a single cameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified cameraSet node.
			MObject dirNode = MObject::kNullObj;
			if (!getExCameraSetNode(dirNode))
			{
				MGlobal::displayError("-appendCamera must have a valid exCameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			// Get a dag path to the specified camera.
			MSelectionList camList;
			camList.add(camName);
			MDagPath camPath;
			camList.getDagPath(0, camPath);
			if (!camPath.isValid())
			{
				MGlobal::displayError("-appendCamera must have a valid camera node specified");
				status = MS::kFailure;
				return status;
			}

			// Call the MFnCameraSet method to append the layer.
			MFnCameraSet dirFn(dirNode);
			dirFn.appendLayer(camPath, MObject::kNullObj);

			return status;
		}

		if (appendCameraAndSetUsed)
		{
			if (nObjs != 1)
			{
				MGlobal::displayError("-appendCameraAndSet must have a single cameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified cameraSet node.
			MObject dirNode = MObject::kNullObj;
			if (!getExCameraSetNode(dirNode))
			{
				MGlobal::displayError("-appendCameraAndSet must have a valid exCameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			// Get a dag path to the specified camera.
			MSelectionList camList;
			camList.add(camName);
			MDagPath camPath;
			camList.getDagPath(0, camPath);
			if (!camPath.isValid())
			{
				MGlobal::displayError("-appendCameraAndSet must have a valid camera node specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified set node.
			MSelectionList setList;
			setList.add(setName);
			MObject setObj = MObject::kNullObj;
			setList.getDependNode(0, setObj);
			if (setObj == MObject::kNullObj)
			{
				MGlobal::displayError("-appendCameraAndSet must have a valid set node specified");
				status = MS::kFailure;
				return status;
			}

			// Call the MFnCameraSet method to append the layer.
			MFnCameraSet dirFn(dirNode);
			dirFn.appendLayer(camPath, setObj);

			return status;
		}


		if (deleteLayerUsed)
		{
			if (nObjs != 1)
			{
				MGlobal::displayError("-deleteLayer must have a single cameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified cameraSet node.
			MObject dirNode = MObject::kNullObj;
			if (!getExCameraSetNode(dirNode))
			{
				MGlobal::displayError("-deleteLayer must have a valid exCameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			// Call the MFnCameraSet method to delete the layer.
			MFnCameraSet dirFn(dirNode);
			dirFn.deleteLayer(cameraLayer);
	
			return status;
		}

		if (numLayersUsed)
		{
			if (queryUsed)
			{
				// Get the specified cameraSet node.
				MObject dirNode = MObject::kNullObj;
				if (!getExCameraSetNode(dirNode))
				{
					MGlobal::displayError("-numLayers must have a valid exCameraSet node specified");
					status = MS::kFailure;
					return status;
				}

				// Call the MFnCameraSet method to get the number of layers.
				MFnCameraSet dirFn(dirNode);
				unsigned int numLayers = dirFn.getNumLayers(&status);
				if (status != MS::kSuccess)	
					MGlobal::displayError("Error getting the number of layers");
				setResult((int)numLayers);
			}
			else
			{
				MGlobal::displayError("-numLayers requires the query flag to be used");
				status = MS::kFailure;
			}
			return status;
		}

		if (cameraUsed)
		{
			if ((nObjs != 1) || (!layerUsed))
			{
				MGlobal::displayError("-camera must have a cameraSet node and layer specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified cameraSet node.
			MObject dirNode = MObject::kNullObj;
			if (!getExCameraSetNode(dirNode))
			{
				MGlobal::displayError("-camera must have a valid exCameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			if (editUsed)
			{
				// Get a dag path to the specified camera.
				MSelectionList camList;
				camList.add(camName);
				MDagPath camPath;
				camList.getDagPath(0, camPath);
				if (!camPath.isValid())
				{
					MGlobal::displayError("-camera must have a valid camera node specified");
					status = MS::kFailure;
					return status;
				}

				// Call the MFnCameraSet method to set the camera.
				MFnCameraSet dirFn(dirNode);
				dirFn.setLayerCamera((unsigned int)cameraLayer, camPath);
			}
			else if (queryUsed)
			{
				// Call the MFnCameraSet method to get the camera.
				MDagPath camPath;
				MFnCameraSet dirFn(dirNode);
				status = dirFn.getLayerCamera((unsigned int)cameraLayer, camPath);
				if (status == MS::kSuccess)
				{
					MObject camNode = camPath.node();
					MFnDependencyNode nodeFn(camNode);
					setResult(nodeFn.name());
				}
				else
					setResult("");
			}
		}

		if (setUsed)
		{
			if ((nObjs != 1) || (!layerUsed))
			{
				MGlobal::displayError("-set must have a cameraSet node and layer specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified cameraSet node.
			MObject dirNode = MObject::kNullObj;
			if (!getExCameraSetNode(dirNode))
			{
				MGlobal::displayError("-set must have a valid exCameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			if (editUsed)
			{
				// Get the specified set node.
				MObject setObj = MObject::kNullObj;
				if (setName != "")
				{
					MSelectionList setList;
					setList.add(setName);
					setList.getDependNode(0, setObj);
					if (setObj == MObject::kNullObj)
					{
						MGlobal::displayError("-set must have a valid set node specified");
						status = MS::kFailure;
						return status;
					}
				}

				// Call the MFnCameraSet method to set the set node.
				MFnCameraSet dirFn(dirNode);
				dirFn.setLayerSceneData((unsigned int)cameraLayer, setObj);
			}
			else if (queryUsed)
			{
				// Call the MFnCameraSet method to get the set node.
				MObject setObj;
				MFnCameraSet dirFn(dirNode);
				status = dirFn.getLayerSceneData((unsigned int)cameraLayer, setObj);
				if (status == MS::kSuccess)
				{
					MFnDependencyNode nodeFn(setObj);
					setResult(nodeFn.name());
				}
				else
					setResult("");
			}
		}

		if (layerTypeUsed)
		{
			if ((nObjs != 1) || (!layerUsed))
			{
				MGlobal::displayError("-layerType must have a cameraSet node and layer specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified cameraSet node.
			MObject dirNode = MObject::kNullObj;
			if (!getExCameraSetNode(dirNode))
			{
				MGlobal::displayError("-layerType must have a valid exCameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			MFnDependencyNode nodeFn(dirNode);
			exCameraSet *exDir = (exCameraSet *)nodeFn.userNode();

			if (editUsed)
			{
				// Get the specified layer type.
				int pt = -1;
				if (layerTypeVal == "Mono")
					pt = 0;
				else if (layerTypeVal == "Left")
					pt = 1;
				else if (layerTypeVal == "Right")
					pt = 2;
				else
				{
					MGlobal::displayError("-layerType must have a valid type specified");
					status = MS::kFailure;
					return status;
				}

				// Call the exCameraSet method to set the layer type.
				exDir->setLayerType((unsigned int)cameraLayer, pt);
			}
			else if (queryUsed)
			{
				// Call the exCameraSet method to get the layer type.
				int lt;
				status = exDir->getLayerType((unsigned int)cameraLayer, lt);
				if (status == MS::kSuccess)
				{
					if (lt == 0)
						setResult("Mono");
					else if (lt == 1)
						setResult("Left");
					else if (lt == 2)
						setResult("Right");
				}
				else
				{
					MGlobal::displayError("exCameraSet node does not have a valid layer type");
					status = MS::kFailure;
					return status;
				}
			}
		}

		if (activeUsed)
		{
			if ((nObjs != 1) || (!layerUsed))
			{
				MGlobal::displayError("-active must have a cameraSet node and layer specified");
				status = MS::kFailure;
				return status;
			}

			// Get the specified cameraSet node.
			MObject dirNode = MObject::kNullObj;
			if (!getExCameraSetNode(dirNode))
			{
				MGlobal::displayError("-active must have a valid exCameraSet node specified");
				status = MS::kFailure;
				return status;
			}

			if (editUsed)
			{
				// Call the MFnCameraSet method to set the set node.
				MFnCameraSet dirFn(dirNode);
				dirFn.setLayerActive((unsigned int)cameraLayer, activeVal);
			}
			else if (queryUsed)
			{
				// Call the MFnCameraSet method to get the active value.
				MStatus stat = MS::kSuccess;
				MFnCameraSet dirFn(dirNode);
				activeVal = dirFn.isLayerActive((unsigned int)cameraLayer, &stat);
				if (stat == MS::kSuccess)
					setResult(activeVal);
				else
					MGlobal::displayError("Could not get active value");
			}
		}
	}
	
	return status;
}