Example #1
0
MStatus uninitializePlugin(MObject plugin)
{
    MStatus     st;
    MFnPlugin   pluginFn(plugin, "Autodesk, Inc.", "1.0", "Any", &st);
    if (!st) {
        MGlobal::displayError(
            MString("helixQtCmd - could not uninitialize plugin: ")
            + st.errorString()
            );
        return st;
    }
    //  Make sure that there is no UI left hanging around.
    HelixQtCmd::cleanup();
    //  Deregister the command.
    st = pluginFn.deregisterCommand(HelixQtCmd::commandName);
    if (!st) {
        MGlobal::displayError(
            MString("helixQtCmd - could not deregister '")
            + HelixQtCmd::commandName + "' command: "
            + st.errorString()
            );
        return st;
    }
    return st;
}
Example #2
0
MStatus replaceDagObject(MObject & oldObject, MObject & newObject,
            const MString & name)
{
    MStatus status;
    MFnDagNode mFnOld(oldObject, &status);
    if (status == MS::kSuccess)
    {
        unsigned int numChild = mFnOld.childCount();

        std::vector<MObject> children;
        children.reserve(numChild);
        for (unsigned int i = 0; i < numChild; i++)
        {
            MObject child = mFnOld.child(i, &status);
            if (status == MS::kSuccess)
            {
                children.push_back(child);
            }
            else
            {
                MString theError("Failed to get child ");
                theError += i;
                theError += " of ";
                theError += mFnOld.name();
                theError += ", status = ";
                theError += status.errorString();
                MGlobal::displayError(theError);
            }
        }

        MFnDagNode mFnNew(newObject, &status);
        if (status == MS::kSuccess)
        {
            for (unsigned int i = 0; i < numChild; i++)
            {
                status = mFnNew.addChild(children[i]);
                if (status != MS::kSuccess)
                {
                    MString theError("Failed to add child ");
                    theError += i;
                    theError += " of ";
                    theError += mFnOld.name();
                    theError += " to ";
                    theError += name;
                    theError += ", status = ";
                    theError += status.errorString();
                    MGlobal::displayError(theError);
                }
            }
        }
    }
    return status;
}
Example #3
0
MStatus disconnectAllPlugsTo(MPlug & dstPlug)
{
    MStatus status = MS::kSuccess;
    MPlugArray array;
    dstPlug.connectedTo(array, true, false, &status);
    unsigned int arrayLength = array.length();

    for (unsigned int i = 0; i < arrayLength; i++)
    {
        MPlug srcPlug = array[i];
        if (status == MS::kSuccess)
        {
            MDGModifier modifier;
            status = modifier.disconnect(srcPlug, dstPlug);
            status = modifier.doIt();
            if (status != MS::kSuccess)
            {
                MString theError("Disconnect ");
                theError += srcPlug.name();
                theError += MString(" -> ");
                theError += dstPlug.name();
                theError += MString(" failed, status = ");
                theError += status.errorString();
                MGlobal::displayError(theError);
                return status;
            }
        }
    }
    return MS::kSuccess;
}
Example #4
0
void err_code(MStatus & stat)
{
	if( stat != MS::kSuccess ) { 
		std::cout << "[ERROR: " << stat.errorString().asChar() << "]" <<std::endl; 		
		exit(-1);
	}
}
Example #5
0
MStatus ClothSimMayaPlugin::compute(const MPlug& plug, MDataBlock& data)
{
	MStatus returnStatus;

	if (plug == g_aOutputMesh)
	{
		MDataHandle timeData = data.inputValue(g_aTime, &returnStatus);
		McheckErr(returnStatus, "Error getting time data handle\n");
		MTime time = timeData.asTime();

		/* Get output object */

		MDataHandle outputHandle = data.outputValue(g_aOutputMesh, &returnStatus);
		McheckErr(returnStatus, "ERROR getting polygon data handle\n");

		MFnMeshData dataCreator;
		MObject newOutputData = dataCreator.create(&returnStatus);
		McheckErr(returnStatus, "ERROR creating outputData");

		createMesh(time, newOutputData, returnStatus);
		if (!returnStatus)
		{
			std::cerr << "ERROR creating new Cube: " << returnStatus.errorString() << std::endl;
			return returnStatus;
		}

		outputHandle.set(newOutputData);
		data.setClean(plug);
	}
	else
		return MS::kUnknownParameter;

	return MS::kSuccess;
}
Example #6
0
void UsdMayaJobExportArgs::AddFilteredTypeName(const MString& typeName)
{
    MNodeClass cls(typeName);
    unsigned int id = cls.typeId().id();
    if (id == 0) {
        TF_WARN("Given excluded node type '%s' does not exist; ignoring",
                typeName.asChar());
        return;
    }
    _filteredTypeIds.insert(id);
    // We also insert all inherited types - only way to query this is through mel,
    // which is slower, but this should be ok, as these queries are only done
    // "up front" when the export starts, not per-node
    MString queryCommand("nodeType -isTypeName -derived ");
    queryCommand += typeName;
    MStringArray inheritedTypes;
    MStatus status = MGlobal::executeCommand(queryCommand, inheritedTypes, false, false);
    if (!status) {
        TF_WARN("Error querying derived types for '%s': %s",
                typeName.asChar(), status.errorString().asChar());
        return;
    }

    for (unsigned int i=0; i < inheritedTypes.length(); ++i) {
        if (inheritedTypes[i].length() == 0) continue;
        id = MNodeClass(inheritedTypes[i]).typeId().id();
        if (id == 0) {
            // Unfortunately, the returned list will often include weird garbage, like
            // "THconstraint" for "constraint", which cannot be converted to a MNodeClass,
            // so just ignore these...
            continue;
        }
        _filteredTypeIds.insert(id);
    }
}
Example #7
0
Model* MayaReader::read(const char* filename) {

	MStatus status = MLibrary::initialize(filename);
	if (!status) {
		std::cerr << "Failed to initialize Maya" << std::endl;
		return NULL;
	}

	MFileIO::newFile(true);

	status = MFileIO::open(filename);
	if ( !status ) {
		std::cerr << "Failed to open Maya source file: " << status.errorString().asUTF8() << std::endl;
		return NULL;
	}

	status = MGlobal::executeCommand( "delete -ch" );
	if (!status) {
		std::cerr << "Failed to cleanup maya source objects" << std::endl;
		return NULL;
	}

	Model* model = new Model();
	//extractLayers(model);
	extractPolygons(model);

	//MLibrary::cleanup();

	//extractGeometry(model);

	return model;
}
Example #8
0
	// Break connections to this blendshape
	void BlendShape::breakConnections()
	{
		MStatus stat;
		MDagModifier dagModifier;
		// Clear the stored connections
		m_weightConnections.clear();
		// Save node connections and break them
		MPlug weightsPlug = m_pBlendShapeFn->findPlug("weight",true);
		for (int i=0; i<weightsPlug.evaluateNumElements(); i++)
		{
			MPlug wPlug = weightsPlug.elementByPhysicalIndex(i);
			MPlugArray srcConnections;
			MPlugArray dstConnections;
			wPlug.connectedTo(srcConnections,false,true);
			wPlug.connectedTo(dstConnections,true,false);
			weightConnections wcon;
			for (int j=0; j<srcConnections.length(); j++)
			{
				wcon.srcConnections.append(srcConnections[j]);
				dagModifier.disconnect(wPlug,srcConnections[j]);
				dagModifier.doIt();
			}
			for (int j=0; j<dstConnections.length(); j++)
			{
				wcon.dstConnections.append(dstConnections[j]);
				stat = dagModifier.disconnect(dstConnections[j],wPlug);
				if (MS::kSuccess != stat)
				{
					std::cout << "Error trying to disconnect plug " << wPlug.name().asChar() << " and plug " << dstConnections[j].name().asChar() << "\n";
					std::cout << stat.errorString().asChar() << "\n";
					std::cout.flush();
				}
				stat = dagModifier.doIt();
				if (MS::kSuccess != stat)
				{
					std::cout << "Error trying to disconnect plug " << wPlug.name().asChar() << " and plug " << dstConnections[j].name().asChar() << "\n";
					std::cout << stat.errorString().asChar() << "\n";
					std::cout.flush();
				}
			}
			m_weightConnections.push_back(wcon);
		}
	}
MStatus uninitializePlugin( MObject obj )
{
	MFnPlugin plugin( obj );

	MStatus	stat;
	stat = plugin.deregisterCommand( "molecule3" );
	if ( !stat )
		MGlobal::displayError( MString( "deregisterCommand failed: " ) + stat.errorString() );

	return stat;
}
MayaException::MayaException(const MStatus& status, const char* file, int line):
	std::runtime_error
	(
		std::string(status.errorString().asChar())+
		std::string(". ")+
		file+
		std::string(", line ")+
		static_cast<std::ostringstream*>( &(std::ostringstream() << line) )->str()
	),
	status(status)
{}
Example #11
0
MObject AppleseedRenderer::checkSmoothMesh(MObject& meshObject, MFnMeshData& smoothMeshData)
{
	MStatus stat;
	MObject object = MObject::kNullObj;

	MFnMesh mesh(meshObject, &stat);
	if(!stat)
	{
		logger.error(MString("checkSmoothMesh : could not get mesh: ") + stat.errorString());
		return object;
	}

	bool displaySmoothMesh = false;
	if( getBool("displaySmoothMesh", mesh, displaySmoothMesh) )
	{
		if( !displaySmoothMesh )
			return object;
	}else{
		logger.error(MString("generateSmoothMesh : could not get displaySmoothMesh attr "));
		return object;
	}
	
	MObject meshDataObj = smoothMeshData.create();
	MObject smoothMeshObj = mesh.generateSmoothMesh(meshDataObj, &stat);
	if(!stat)
	{
		logger.error(MString("generateSmoothMesh : failed"));
		return object;
	}
	
	MFnMesh smoothMeshDn(smoothMeshObj, &stat);
	if(!stat)
	{
		logger.error(MString("generateSmoothMesh : could not create smoothMeshDn: ") + stat.errorString());
		return object;
	}
		
	return smoothMeshObj;
}
Example #12
0
void MayaMeshExporter::ExportMayaFile(std::string const & open_file)
{
	MStatus status = MFileIO::open(open_file.c_str(), NULL, true);
	if (!status)
	{
		std::cout << "MFileIO::open(" << open_file << ") failed - " << status.errorString() << std::endl;
		return;
	}

	// Add meshes
	MItDag dag_iterator(MItDag::kDepthFirst, MFn::kInvalid, &status);
	this->ExportMayaNodes(dag_iterator);
}
MStatus initializePlugin( MObject obj )
{
	MFnPlugin plugin( obj, "David Gould", "1.0" );

	MStatus stat;
	stat = plugin.registerCommand( "molecule3", 
								   Molecule3Cmd::creator,
								   Molecule3Cmd::newSyntax );
	if( !stat )
	{
		MGlobal::displayError( MString( "registerCommand failed: " ) + stat.errorString() );
		return stat;
	}

	stat = plugin.registerUI( "molecule3CreateUI", "molecule3DeleteUI");
	if( !stat ) 
	{
		MGlobal::displayError( MString( "registerUI failed: " ) + stat.errorString() );
		return stat;
	}

	return stat;
}
Example #14
0
// ==========================================================================
//
//          Plugin load/unload
//
// ==========================================================================
MStatus initializePlugin(MObject plugin)
{
    MStatus     st;
    MFnPlugin   pluginFn(plugin, "Autodesk, Inc.", "1.0", "Any", &st);
    if (!st) {
        MGlobal::displayError(
            MString("helixQtCmd - could not initialize plugin: ")
            + st.errorString()
            );
        return st;
    }
    //  Register the command.
    st = pluginFn.registerCommand(HelixQtCmd::commandName, HelixQtCmd::creator);
    if (!st) {
        MGlobal::displayError(
            MString("helixQtCmd - could not register '")
            + HelixQtCmd::commandName + "' command: "
            + st.errorString()
            );
        return st;
    }
    return st;
}
Example #15
0
//! Uninitialize plugin for LaplacianSmoother.
MStatus uninitializePlugin ( MObject obj )
{
    MStatus status;
    MFnPlugin plugin ( obj );

    status = plugin.deregisterNode ( LaplacianSmoother::id );

    if ( !status )
    {
        status.perror ( "uninitialized plug-in" );
        status.perror ( status.errorString( ) );
    }
    return status;
}
	void Renderer::generate_shavehair(liqRibNodePtr &ribNode__, liqRibShaveData* pData, const int degree)
	{
		CM_TRACE_FUNC("generate_pfxhair("<<ribNode__->getTransformNodeFullPath().asChar()<<")");

		MStatus status;

		shaveAPI::HairInfo hairInfo;
		status = shaveAPI::exportAllHair(&hairInfo);
		if(MFAIL(status)){
			liquidMessage2(messageError,"shaveAPI::exportAllHair(&hairInfo)=[%s]", status.errorString().asChar());
			return;
		}

		//todo
	}
Example #17
0
//! Initialize plugin for LaplacianSmoother.
MStatus initializePlugin ( MObject obj )
{
    MStatus status;
    MFnPlugin plugin ( obj, "Tody", "1.0", "Any" );
    status = plugin.registerNode ( LaplacianSmoother::getMayaName(), LaplacianSmoother::id, LaplacianSmoother::creator,
                                   LaplacianSmoother::initialize,  MPxNode::kDeformerNode );

    if ( !status )
    {
        status.perror ( "initialized plug-in" );
        status.perror ( status.errorString( ) );
    }

    return status;
}
Example #18
0
__declspec(dllexport) MStatus uninitializePlugin( MObject io_object )
{
	// Create a plugin function set
	MFnPlugin plugin( io_object );

	// Register the exporter
	MStatus status;
	{
		status = plugin.deregisterFileTranslator( s_pluginName );
		if ( !status )
		{
			MGlobal::displayError( MString( "Failed to deregister mesh exporter: " ) + status.errorString() );
		}
	}
    return status;
}
MStatus AlembicWriteJob::Process(double frame)
{
  ESS_PROFILE_SCOPE("AlembicWriteJob::Process");
  // find the right time frame!
  int i = -1;
  for (size_t j = 0; j < mFrames.size(); ++j) {
    // compare the frames
    if (fabs(mFrames[j] - frame) <= 0.001) {
      i = (int)j;
      break;
    }
  }

  if (i < 0) {
    return MS::kSuccess;
  }

  // run the export for all objects
  MayaProgressBar pBar;
  pBar.init(0, (int)mapObjects.size(), 1);
  pBar.start();

  int interrupt = 20;
  MStatus status;
  const double currentFrame = mFrames[i];
  const bool isFirstFrame = (i == 0);

  for (multiMapStrAbcObj::iterator it = mapObjects.begin();
       it != mapObjects.end(); ++it, --interrupt) {
    if (interrupt == 0) {
      interrupt = 20;
      if (pBar.isCancelled()) {
        break;
      }
      pBar.incr(20);
    }
    status = it->second->Save(currentFrame, mTs, isFirstFrame);
    if (status != MStatus::kSuccess) {
      MPxCommand::setResult("Error caught in AlembicWriteJob::Process: " +
                            status.errorString());
      break;
    }
  }
  pBar.stop();
  return status;
}
Example #20
0
__declspec(dllexport) MStatus initializePlugin(MObject io_object)
{
	// Create a plugin function set
	MFnPlugin plugin(io_object);

	// Register the exporter
	MStatus status;
	{
		char* icon = "none";
		status = plugin.registerFileTranslator(s_pluginName, icon, GAnimExporter::Create);
		if (!status)
		{
			MGlobal::displayError(MString("Failed to register exporter: ") + status.errorString());
		}
	}
	return status;
}
Example #21
0
void HelixButton::createHelix()
{
    MStatus st;
    const unsigned deg = 3;             // Curve Degree
    const unsigned ncvs = 20;            // Number of CVs
    const unsigned spans = ncvs - deg;    // Number of spans
    const unsigned nknots = spans + 2 * deg - 1; // Number of knots
    double         radius = 4.0;           // Helix radius
    double         pitch = 0.5;           // Helix pitch
    unsigned       i;
    MPointArray controlVertices;
    MDoubleArray knotSequences;
    // Set up cvs and knots for the helix
    for (i = 0; i < ncvs; i++) {
        controlVertices.append(
            MPoint(
                radius * cos((double)i),
                pitch * (double)i,
                radius * sin((double)i)
                )
            );
    }
    for (i = 0; i < nknots; i++)
        knotSequences.append((double)i);
    // Now create the curve
    MFnNurbsCurve curveFn;
    MObject curve = curveFn.create(
        controlVertices,
        knotSequences,
        deg,
        MFnNurbsCurve::kOpen,
        false,
        false,
        MObject::kNullObj,
        &st
        );
    MGlobal::displayInfo("Helix curve created!");

    if (!st) {
        MGlobal::displayError(
            HelixQtCmd::commandName + " - could not create helix: "
            + st.errorString()
            );
    }
}
Example #22
0
__declspec(dllexport) MStatus initializePlugin( MObject io_object )
{
	// Create a plugin function set
	MFnPlugin plugin( io_object );

	// Register the exporter
	MStatus status;
	{
		char* noIcon = "none";
		status = plugin.registerFileTranslator( s_pluginName, noIcon,
			// This function is what Maya should call to create a new instance of the mesh exporter
			eae6320::cMayaMeshExporter::Create );
		if ( !status )
		{
			MGlobal::displayError( MString( "Failed to register mesh exporter: " ) + status.errorString() );
		}
	}
    return status;
}
Example #23
0
void MayaObject::getMeshData(MPointArray& points, MFloatVectorArray& normals)
{
	MStatus stat;
	MObject meshObject = this->mobject;
	MMeshSmoothOptions options;
	MFnMesh tmpMesh(this->mobject);
	MFnMeshData meshData;
	MObject dataObject;
	MObject smoothedObj;

	// create smooth mesh if needed
	if (tmpMesh.findPlug("displaySmoothMesh").asBool())
	{
		stat = tmpMesh.getSmoothMeshDisplayOptions(options);
		if (stat)
		{
			if (!tmpMesh.findPlug("useSmoothPreviewForRender", false, &stat).asBool())
			{
				//Logging::debug(MString("useSmoothPreviewForRender turned off"));
				int smoothLevel = tmpMesh.findPlug("renderSmoothLevel", false, &stat).asInt();
				options.setDivisions(smoothLevel);
			}
			if (options.divisions() > 0)
			{
				dataObject = meshData.create();
				smoothedObj = tmpMesh.generateSmoothMesh(dataObject, &options, &stat);
				if (stat)
				{
					meshObject = smoothedObj;
				}
			}
		}
	}
	MFnMesh meshFn(meshObject, &stat);
	if (!stat)
	{
		MString error = stat.errorString();
		Logging::error(error);
	}
	meshFn.getPoints(points);
	meshFn.getNormals(normals, MSpace::kObject);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVstSelectCoincidentFacesCmd::redoIt()
{
	MStatus mStatus;

	if ( !mStatus )
	{
		setResult( MString( "Cannot parse command line" ) + mStatus.errorString() );
		return MS::kFailure;
	}

	const MArgDatabase &mArgDatabase( m_undo.ArgDatabase() );

	m_undo.SaveCurrentSelection();

	if ( mArgDatabase.isFlagSet( kOptHelp ) )
	{
		GetSyntaxHelp()->PrintHelp( GetName(), GetDesc() );
		return MS::kSuccess;
	}

	return DoSelect();
}
Example #25
0
MStatus nodeCreatedCB::doIt( const MArgList& args )
//
//	Description:
//		implements the MEL nodeCreatedCB command.
//
{
	MStatus stat = MS::kSuccess;

	MArgDatabase argData( syntax(), args );

	// Parse command flags.
	//
	if ( argData.isFlagSet( kRegisterFlag ) ) {
		// Register a new procedure.
		//
		MString proc;
		argData.getFlagArgument( kRegisterFlag, 0, proc );
		stat = registerMelProc( proc, argData.isFlagSet( kFullDagPathFlag ) );
	} else if ( argData.isFlagSet( kUnregisterFlag ) ) {
		// Unregister a procedure.
		//
		MString proc;
		argData.getFlagArgument( kUnregisterFlag, 0, proc );
		stat = unregisterMelProc( proc );
	} else if ( argData.isFlagSet( kFilterFlag ) ) {
		// Change the filter being applied.
		//
		MString filter;
		argData.getFlagArgument( kFilterFlag, 0, filter );
		stat = changeFilter( filter );
	}
	
	if ( stat.error() ) {
		MGlobal::displayError( stat.errorString() );
	}

	return stat;
}
MStatus updateTCCDataFty::remapMeshData(MFnMesh &meshFn)
{
    MIntArray o_nFV, o_F;
    meshFn.getVertices(o_nFV, o_F);
    size_t o_nF  = o_nFV.length();
    size_t o_nHE = o_F.length();
    size_t o_nV  = meshFn.numVertices();

    MIntArray o_F2H(o_nF); // maps face index to halfedge index
    {
        size_t kS=0;
        for (size_t k=0; k<o_nF; k++)
        {
            o_F2H[k] = kS;
            kS+=o_nFV[k];
        }
    }

    size_t nF  = fPolyOrder.length();
    size_t nHE = compute_nHE(fPolyOrder, o_nFV, fDelta_nFV);
    size_t nV  = fnV;

    HalfedgeData he(o_nHE, nHE);
    VertexData   v(o_nV, nV);

    MFloatPointArray V(nV);
    MIntArray nFV(nF);
    MIntArray F(nHE);

    get_vertex_blindData(meshFn, v);
    get_halfedge_blindData(meshFn, he);

    // add old/new faces in the order given by fPolyOrder and remap their halfedge data (if exists)

    size_t delta_kF = 0, delta_kHE=0;
    size_t kF = 0, kHE = 0;
    for (size_t k=0; k<fPolyOrder.length(); k++)
    {
        if (fPolyOrder[k]>=0)
        {
            size_t cF = fPolyOrder[k], cnFV = o_nFV[cF];

            size_t o_cF2H = o_F2H[cF];
            size_t cShift = fCShift[cF];
            for (size_t kFV=0; kFV<cnFV; kFV++)
            {
                size_t o_kHE = o_cF2H + ((kFV + cShift) % cnFV);

                F[kHE] = fVtxRemap[o_F[o_kHE]];

                remap_HalfedgeData(he, o_kHE, kHE);

                kHE++;
            }

            nFV[kF] = cnFV;
            kF++;
        }
        else // this is a new face
        {
            size_t cnFV = fDelta_nFV[delta_kF];
            delta_kF++;
            for (size_t kFV=0; kFV<cnFV; kFV++)
            {
                F[kHE] = fDelta_F[delta_kHE];

                kHE++;
                delta_kHE++;
            }
            nFV[kF] = cnFV;
            kF++;
        }
    }

    // remap vertex data
    for (size_t k=0; k<o_nV; k++)
    {
        if (fVtxRemap[k]>=0)
        {
            remap_VertexData(v, k, fVtxRemap[k]);
        }
    }

    MStatus stat = meshFn.createInPlace(nV, nF, V, nFV, F);
    if (stat != MS::kSuccess)
    {
        std::cerr<<"createInPlace failed"<<endl;
        std::cerr<<stat.errorString()<<endl;
    }


    update_tags(nFV, F, v, he);

    set_vertex_blindData(meshFn, v);
    set_halfedge_blindData(meshFn, he);

    return stat;
}
Example #27
0
	// Load blend shape poses for shared geometry
	MStatus BlendShape::loadPosesShared(MDagPath& meshDag,ParamList &params,
		std::vector<vertex> &vertices,long numVertices,long offset)
	{
		MStatus stat;
		// Set blend shape target
		m_target = T_MESH;
		// Set blend shape deformer envelope to 1 to get target shapes
		m_pBlendShapeFn->setEnvelope(1);
		// Break connections on weights
		breakConnections();
		// Set weight to 0 for all targets
		MIntArray indexList;
		m_pBlendShapeFn->weightIndexList(indexList);
		for (int i=0; i<indexList.length(); i++)
		{
			stat = m_pBlendShapeFn->setWeight(indexList[i],0);
			if (MS::kSuccess != stat)
			{
				std::cout << "Error setting weight " << indexList[i] << " to 0 on blendhape deformer " << m_pBlendShapeFn->name().asChar() << "\n";
				std::cout << stat.errorString().asChar() << "\n";
				std::cout.flush();
			}
		}
		// Get pose names
		MStringArray poseNames;
		MString cmd = "aliasAttr -q " + m_pBlendShapeFn->name();
		MGlobal::executeCommand(cmd,poseNames,false,false);
		// Get all poses: set iteratively weight to 1 for current target shape and keep 0 for the other targets
		for (int i=0; i<indexList.length(); i++)
		{
			MString poseName = "pose" + i;
			// get pose name
			bool foundName = false;
			for (int j=1; j<poseNames.length() && !foundName; j+=2)
			{
				int idx = -1;
				sscanf(poseNames[j].asChar(),"weight[%d]",&idx);
				if (idx == i)
				{
					poseName = poseNames[j-1];
					foundName = true;
					std::cout << "pose num: " << i << " name: " << poseName.asChar() << "\n";
					std::cout.flush();
				}
			}
			// set weight to 1
			stat = m_pBlendShapeFn->setWeight(indexList[i],1);
			if (MS::kSuccess != stat)
			{
				std::cout << "Error setting weight " << indexList[i] << " to 1 on blend shape deformer " << m_pBlendShapeFn->name().asChar() << "\n";
				std::cout << stat.errorString().asChar() << "\n";
				std::cout.flush();
			}
			// load the pose
			stat = loadPoseShared(meshDag,params,vertices,numVertices,offset,poseName,i);
			if (stat != MS::kSuccess)
			{
				std::cout << "Failed loading target pose " << indexList[i] << "\n";
				std::cout << stat.errorString().asChar();
				std::cout.flush();
			}
			// set weight to 0
			stat = m_pBlendShapeFn->setWeight(indexList[i],0);
			if (MS::kSuccess != stat)
			{
				std::cout << "Error resetting weight " << indexList[i] << " to 0 on blend shape deformer " << m_pBlendShapeFn->name().asChar() << "\n";
				std::cout << stat.errorString().asChar() << "\n";
				std::cout.flush();
			}
		}
		// Set blend shape envelope to 0
		m_pBlendShapeFn->setEnvelope(0);
		// Restore targets weights
		for (int i=0; i<indexList.length(); i++)
		{
			m_pBlendShapeFn->setWeight(indexList[i],m_origWeights[i]);
		}
		// Restore connections on weights
		restoreConnections();
		return MS::kSuccess;
	}
Example #28
0
//-----------------------------------------------------------------
MStatus		ByronsPolyTools::doIt(const MArgList& args)
//-----------------------------------------------------------------
{
    // Ist die version abgelaufen ?
    //
#ifdef EXPIRES

    if( ! checkExpires() )
    {
        MGlobal::displayError( "This AlphaVersion is expired. Scenes will still load properly. " );

        return MS::kSuccess;
    }

#endif

    MSelectionList sList;


    MStatus	status;
    MArgDatabase	argData(syntax(),args);



    if(argData.isFlagSet("-help"))
    {
        MGlobal::executeCommand("showBPTHelpWindow",false,false);
        return MS::kSuccess;
    }



//SELECTION UEBERPRUEFEN

//	Selection holen
//
    argData.getObjects(sList);

//	OrigList fuer UndoZwecke speichern
    origList = sList;






//	Check, ob ueberhaupt Objekt gewaehlt

    if ( (sList.length() == 0) )

    {

        displayError("ONE mesh or its transform node must be selected.");

        return MStatus::kFailure;

    }



    //MDagPath			meshDagPath;

    MItSelectionList sIter(sList);//,MFn::kMesh);
    bool meshOK = false,hasComps = false;

    INVIS(cout<<"SELECTIONLIST LAENGE: "<<sList.length()<<endl);

    for(; !sIter.isDone(); sIter.next())
    {
        sIter.getDagPath(meshDagPath, components);
        //sList.getDagPath(0, meshDagPath, components);








        //if(!meshDagPath.hasFn(MFn::kPluginDependNode))
        if(meshDagPath.apiType() == (MFn::kMesh))
        {

            if(!meshDagPath.hasFn(MFn::kMesh) )
                meshOK = false;
            else
                meshOK = true;





            if( components.apiType() == MFn::kInvalid )
                hasComps = false;
            else
            {
                hasComps = true;
                break;
            }

        }


    }


    if(!meshOK)
    {
        displayError("Invalid type!  Only a mesh or its transform with selected components can be specified!");
        return MStatus::kFailure;
    }



#ifdef	DEMO

    MFnMesh	meshFn(meshDagPath);
    if(meshFn.numPolygons() > 500)
    {
        MGlobal::displayError("This DEMO will only work on meshes with a maximum number of 500 polygons");
        return MS::kFailure;
    }

#endif



    if(!hasComps)
    {
        displayError("Please select some components to operate on");
        return MStatus::kFailure;
    }



//	Flags und Argumente Holen
//----------------------------------

    if(argData.isFlagSet("-iv"))
        operationMode = 0;
    else
        operationMode = 1;


    //zuerst mal edgeComoponents holen - wenn welche vorhanden und -peb flag gesetzt, dann wird auf jeden Fall der case 0 mode verwendet
    getEdgeComponents(sList);

    if( argData.isFlagSet("-peb") && edgeIDs.length() != 0 )
        operationMode = 0;


//------------------------------------
//	OPTIONS
//------------------------------------


    switch(operationMode)
    {
    case 0://insert Vtx mode
    {
        if(argData.isFlagSet("-ic"))
            argData.getFlagArgument("-ic",0,initialCount);
        else
            initialCount = 1;

        goto default_values;

    }

    case 1:	//PolyToolsMode
    {


        //------------------------------------
        //	FLAGS
        //------------------------------------








        smartSplitFlagSet = argData.isFlagSet("-smartSplit");
        edgeLoopFlagSet = argData.isFlagSet("-edgeLoop");
        edgeRingFlagSet = argData.isFlagSet("-edgeRing");
        boundaryFlagSet = argData.isFlagSet("-boundary");

        chamferFlagSet = argData.isFlagSet("-chamfer");
        solidChamferFlagSet = argData.isFlagSet("-solidChamfer");

        smcFlagSet = argData.isFlagSet("-smartMoveComponent");

        growFlagSet = argData.isFlagSet("-gro");
        schrinkFlagSet = argData.isFlagSet("-shr");



        //	abbruch, wenn flags nicht eindeutig und actionMode nicht gesetzt werden kann
        status = setActionMode();

        if(status == MS::kFailure)
            return status;


        //-------------------ENDE-----------------------------


        goto default_values;


    }
    default:
    {
default_values:




        avt = (argData.isFlagSet("-avf"))?true:false;
        avm = (argData.isFlagSet("-avm"))?true:false;


        options.setLength(10);

        options[0] = argData.isFlagSet("-connectEnds");

        options[1] = argData.isFlagSet("-triangulateEnds");

        if(argData.isFlagSet("-maxEdgeCount"))
            argData.getFlagArgument("-maxEdgeCount",0,options[2]);
        else
            options[2] = 16666666;

        options[3] = 0;	//side ist standardmaessig 0:


        if(argData.isFlagSet("-snl") )
            options[4] = 1;
        else
            options[4] = 0;


        options[5] = (argData.isFlagSet("-ast"))?1:0;

        options[6] = 0;
        if(argData.isFlagSet("-se"))
            options[6] = 1;

        if( CMDactionMode == 5 && argData.isFlagSet("-") )
            options[6] += 3;

        if(argData.isFlagSet("-sf"))
            options[6] = 2;

        if(argData.isFlagSet("-sv"))
            options[6] = 5;


        //IV flag - wenn -peb aktiv ist, wird er auf jeden Fall gesetzt
        if( argData.isFlagSet("-peb") )
            options[9] = 1;
        else
            options[9] = argData.isFlagSet("-civ")?true:false;

        //----------------------------------------OPTIONS ENDE

        slideIsRelative = argData.isFlagSet("-sir");

        //slideIsRelative ist an, wenn Chamfer aktiv ist
        if(chamferFlagSet+solidChamferFlagSet > 0)
            slideIsRelative = 1;

        if(CMDactionMode == 6)
            slideIsRelative = true;

        normalIsRelative = argData.isFlagSet("-nir");

        //slide soll automatisch auf  gesetzt werden, wenn -peb aktiv (dies entspricht einem slidewert von 1
        if( argData.isFlagSet("-peb") && edgeIDs.length() != 0)
            directSlide = 1;
        else
        {
            if(argData.isFlagSet("-slide"))

                argData.getFlagArgument("-slide",0,directSlide);
            else
                directSlide = 0.5;	//defaultValue
        }

    }


    }

    //undoIndo sammeln

    MSelectionMask tmpMask(MGlobal::componentSelectionMask());
    undoMask = tmpMask;



    /*
    	CallWindowProc(	(WNDPROC)(GetWindowLong(mayaWin, GWL_WNDPROC)),
    					mayaWin, WM_CLOSE, NULL, NULL);



    DWORD dwStyle = WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
    //MessageBox(mayaWin, "Help", "Whatever", MB_OK);
    HWND myWin = CreateWindowEx( 0,"MyFirstWin","Lala" , dwStyle, 0, 0,
    							300, 400,
    							mayaWin, NULL, NULL, NULL);

    ShowWindow(myWin, SW_SHOWNORMAL);
    SetFocus(myWin);
    UpdateWindow(myWin);
    */

    //checken ob makeHistory aus ist. Wenn ja, dann wieder an machen, weil maya sonst crashed
    int result;
    MGlobal::executeCommand( "constructionHistory -q -tgl", result );

    if(!result)
        MGlobal::executeCommand( "constructionHistory -tgl 1",false,false);




    meshDagPath.extendToShape();
//	Mesh von polyModifierCommand setzen
    setMeshNode(meshDagPath);



    switch(operationMode)
    {
    case 0:
    {
        //getEdgeComponents(sList);
        convertToEdges(sList, argData.isFlagSet("-peb") );

        // setCreateAnimCurves(false);//damit nicht versucht wird, auf dieser Node animCurves fuer tweak zu erstellen
        // Jetzt sind tweaks vonnten

        setModifierNodeType( BPT_InsertVtx::IVid );
        break;
    }
    case 1:
    {
        //	Komponenten herausfiltern und IntIDArrays schreiben

        //getEdgeComponents(sList);
        getVertComponents(sList);
        getPolyComponents(sList);

        setModifierNodeType( ByronsPolyToolsNode::id );
        break;
    }
    }

//	Aktion ausfuehren

    if(CMDactionMode == 0 || CMDactionMode == 4 || CMDactionMode == 5 || CMDactionMode == 6 || operationMode == 0)
    {

        MGlobal::executeCommand("setToolTo selectSuperContext",false,false);

        status = doModifyPoly();

        MFnDependencyNode depNodeFn(bptNode);
        setResult(depNodeFn.name());

        if( !(status == MS::kSuccess) )
        {
            MGlobal::displayError( "An error occoured." );
            MGlobal::displayError( status.errorString() );

        }
    }
    else
    {
//		Wenn mesh nicht veraendert wird, wird einfach so die Factory gerufen
        directModifier(meshDagPath.node());
        //setResult( "BPTOperation succeeded" );
    }


    //Command wird nur einmal verwendet, also muessen die Datenarrays auch m#keinen Speicher mehr verschwenden
    //.clear() wuerde sie nicht physisch loeschen
    polyIDs.setLength(0);
    edgeIDs.setLength(0);
    vertIDs.setLength(0);

//	return status;
    return MS::kSuccess;
}
MStatus	Molecule3Cmd::redoIt()
{
	MStatus stat;
	MDagPath dagPath;
	MFnMesh meshFn;
		
	// Create a ball
	int nBallPolys;
	MPointArray ballVerts;
	MIntArray ballPolyCounts;
	MIntArray ballPolyConnects;
	MFloatArray ballUCoords;
	MFloatArray ballVCoords;
	MIntArray ballFvUVIDs;
	genBall( MPoint::origin, ballRodRatio * radius.value(), segs, nBallPolys, 
			 ballVerts, ballPolyCounts, ballPolyConnects,
			 true, ballUCoords, ballVCoords, ballFvUVIDs );
		
	unsigned int i, j, vertOffset;
	MPointArray meshVerts;
	MPoint p0, p1;
	MObject objTransform;
	
	// Setup for rods
	int nRodPolys;
	MPointArray rodVerts;
	MIntArray rodPolyCounts;
	MIntArray rodPolyConnects;
	MFloatArray rodUCoords;
	MFloatArray rodVCoords;
	MIntArray rodFvUVIDs;
	
	// Setup for newMesh
	int nNewPolys;
	MPointArray newVerts;
	MIntArray newPolyCounts;
	MIntArray newPolyConnects;
	MFloatArray newUCoords;
	MFloatArray newVCoords;
	MIntArray newFvUVIDs;
	
	int uvOffset; 
	MDagModifier dagMod;
	MFnDagNode dagFn;
	
	objTransforms.clear();
	
	// Iterate over the meshes
	unsigned int mi;
	for( mi=0; mi < selMeshes.length(); mi++ )
	{								
		dagPath = selMeshes[mi];
		meshFn.setObject( dagPath );
		
		uvOffset = 0;
		nNewPolys = 0;
		newVerts.clear();
		newPolyCounts.clear();
		newPolyConnects.clear();
		newUCoords.clear();
		newVCoords.clear();
		newFvUVIDs.clear();
		
		// Generate balls
		meshFn.getPoints( meshVerts, MSpace::kWorld );
		for( i=0; i < meshVerts.length(); i++ )
		{
			vertOffset = newVerts.length();
			
			// Add the ball to the new mesh
			nNewPolys += nBallPolys;
			
			// Move the ball vertices to the mesh vertex. Add it to the newMesh
			for( j=0; j < ballVerts.length(); j++ )
				newVerts.append( meshVerts[i] + ballVerts[j] );
				
			for( j=0; j < ballPolyCounts.length(); j++ )
				newPolyCounts.append( ballPolyCounts[j] );
				
			for( j=0; j < ballPolyConnects.length(); j++ )
				newPolyConnects.append( vertOffset + ballPolyConnects[j] );
		
			// Only add the uv coordinates once, since they are shared
			// by all balls
			if( i == 0 )
			{
				for( j=0; j < ballUCoords.length(); j++ )
				{
					newUCoords.append( ballUCoords[j] );
					newVCoords.append( ballVCoords[j] );
				}				
			}
			
			for( j=0; j < ballFvUVIDs.length(); j++ )
			{
				newFvUVIDs.append( uvOffset + ballFvUVIDs[j] );
			}
		}
		
		uvOffset = newUCoords.length();
		
		// Generate rods
		int nRods = 0;
		MItMeshEdge edgeIter( dagPath );
		for( ; !edgeIter.isDone(); edgeIter.next(), nRods++  )
		{	
			p0 = edgeIter.point( 0, MSpace::kWorld );		
			p1 = edgeIter.point( 1, MSpace::kWorld );
			
			// N.B. Generate the uv coordinates only once since they
			// are referenced by all rods
			genRod( p0, p1, 
					radius.value(), segs, nRodPolys, 
					rodVerts, rodPolyCounts, rodPolyConnects,
					nRods == 0,	rodUCoords, rodVCoords,
					rodFvUVIDs ); 

			vertOffset = newVerts.length();
			
			// Add the rod to the mesh
			nNewPolys += nRodPolys;
			
			for( i=0; i < rodVerts.length(); i++ )
				newVerts.append( rodVerts[i] );
				
			for( i=0; i < rodPolyCounts.length(); i++ )
				newPolyCounts.append( rodPolyCounts[i] );
				
			for( i=0; i < rodPolyConnects.length(); i++ )
				newPolyConnects.append( vertOffset + rodPolyConnects[i] );

			// First rod
			if( nRods == 0 )
			{
				// Add rod's uv coordinates to the list
				for( i=0; i < rodUCoords.length(); i++ )
				{
					newUCoords.append( rodUCoords[i] );
					newVCoords.append( rodVCoords[i] );
				}
			}
			
			// Set the face-vertex-uvIDs
			for( i=0; i < rodFvUVIDs.length(); i++ )
			{
				newFvUVIDs.append( uvOffset + rodFvUVIDs[i] );
			}
		}
		
		objTransform = meshFn.create( newVerts.length(), nNewPolys, newVerts, 
									  newPolyCounts, newPolyConnects,
									  newUCoords, newVCoords, 
									  MObject::kNullObj, &stat ); 
		if( !stat )
		{
			MGlobal::displayError( MString( "Unable to create mesh: " ) + stat.errorString() );
			return stat;
		}	
		
		objTransforms.append( objTransform );
				
		meshFn.assignUVs( newPolyCounts, newFvUVIDs );
				
		meshFn.updateSurface();
		
		// Rename transform node
		dagFn.setObject( objTransform );
		dagFn.setName( "molecule" );
				
		// Put mesh into the initial shading group
		dagMod.commandToExecute( MString( "sets -e -fe initialShadingGroup " ) + meshFn.name() );
	}

	// Select all the newly created molecule meshes
	MString cmd( "select -r" );
	for( i=0; i < objTransforms.length(); i++ )
	{
		dagFn.setObject( objTransforms[i] );
		cmd += " " + dagFn.name();	
	}

	dagMod.commandToExecute( cmd );
	
	return dagMod.doIt();
}
bool ToMayaCurveConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
	MStatus s;

	IECore::ConstCurvesPrimitivePtr curves = IECore::runTimeCast<const IECore::CurvesPrimitive>( from );
	
	assert( curves );

	if ( !curves->arePrimitiveVariablesValid() || !curves->numCurves() )
	{
		return false;
	}
	
	int curveIndex = indexParameter()->getNumericValue();
	if( curveIndex < 0 || curveIndex >= (int)curves->numCurves() )
	{
		IECore::msg( IECore::Msg::Warning,"ToMayaCurveConverter::doConversion",  boost::format(  "Invalid curve index \"%d\"") % curveIndex );
		return false;
	}
	
	IECore::ConstV3fVectorDataPtr p = curves->variableData< IECore::V3fVectorData >( "P", IECore::PrimitiveVariable::Vertex );
	if( !p )
	{
		IECore::msg( IECore::Msg::Warning,"ToMayaCurveConverter::doConversion",  "Curve has no \"P\" data" );
		return false;
		
	}
	
	const std::vector<int>& verticesPerCurve = curves->verticesPerCurve()->readable();
	int curveBase = 0;
	for( int i=0; i<curveIndex; ++i )
	{
		curveBase += verticesPerCurve[i];
	}
	
	MPointArray vertexArray;
	
	int numVertices = verticesPerCurve[curveIndex];
	
	int cvOffset = 0;
	if( curves->basis() != IECore::CubicBasisf::linear() && !curves->periodic() )
	{
		// Maya implicitly duplicates end points, so they're explicitly duplicated in the CurvePrimitives.
		// We need to remove those duplicates when converting back to Maya. Remove 2 cvs at start, 2 at end.
		if( numVertices < 8 )
		{
			IECore::msg( IECore::Msg::Warning,"ToMayaCurveConverter::doConversion",  "The Curve Primitive does not have enough CVs to be converted into a Maya Curve. Needs at least 8." );
			return false;
		}
		
		cvOffset = 2;
	}
	
	const std::vector<Imath::V3f>& pts = p->readable();
	
	// triple up the start points for cubic periodic curves:
	if( curves->periodic() && curves->basis() != IECore::CubicBasisf::linear() )
	{
		vertexArray.append( IECore::convert<MPoint, Imath::V3f>( pts[curveBase] ) );
		vertexArray.append( vertexArray[0] );
	}
	
	for( int i = cvOffset; i < numVertices-cvOffset; ++i )
	{
		vertexArray.append( IECore::convert<MPoint, Imath::V3f>( pts[i + curveBase] ) );
	}
	
	// if the curve is periodic, the first N cvs must be identical to the last N cvs, where N is the degree
	// of the curve:
	if( curves->periodic() )
	{
		if( curves->basis() == IECore::CubicBasisf::linear() )
		{
			// linear: N = 1
			vertexArray.append( vertexArray[0] );
		}
		else
		{
			// cubic: N = 3
			vertexArray.append( vertexArray[0] );
			vertexArray.append( vertexArray[1] );
			vertexArray.append( vertexArray[2] );
		}
	}
	
	unsigned vertexArrayLength = vertexArray.length();
	
	MDoubleArray knotSequences;
	if( curves->basis() == IECore::CubicBasisf::linear() )
	{
		for( unsigned i=0; i < vertexArrayLength; ++i )
		{
			knotSequences.append( i );
		}
	}
	else
	{
		if( curves->periodic() )
		{
			// Periodic curve, knots must be spaced out.
			knotSequences.append( -1 );
			for( unsigned i=0; i < vertexArrayLength+1; ++i )
			{
				knotSequences.append( i );
			}
		}
		else
		{
			// For a cubic curve, the first three and last three knots must be duplicated for the curve start/end to start at the first/last CV.
			knotSequences.append( 0 );
			knotSequences.append( 0 );
			for( unsigned i=0; i < vertexArrayLength-2; ++i )
			{
				knotSequences.append( i );
			}
			knotSequences.append( vertexArrayLength-3 );
			knotSequences.append( vertexArrayLength-3 );
		}
	}
	
	MFnNurbsCurve fnCurve;
	fnCurve.create( vertexArray, knotSequences, curves->basis() == IECore::CubicBasisf::linear() ? 1 : 3, curves->periodic() ? MFnNurbsCurve::kPeriodic : MFnNurbsCurve::kOpen, false, false, to, &s );
	if (!s)
	{
		IECore::msg( IECore::Msg::Warning,"ToMayaCurveConverter::doConversion",  s.errorString().asChar() );
		return false;
	}
	
	return true;
}