MayaObject::MayaObject(MObject& mobject) { this->mobject = mobject; MFnDagNode dagNode(mobject); dagNode.getPath(this->dagPath); this->initialize(); }
bool MayaObject::isObjVisible() { MFnDagNode dagNode(this->mobject); if (!IsVisible(dagNode) || IsTemplated(dagNode) || !IsInRenderLayer(this->dagPath) || !IsPathVisible(this->dagPath) || !IsLayerVisible(this->dagPath)) return false; return true; }
// Node added to model callback. static void userNodeRemovedCB(MObject& node,void *clientData) { if (! node.isNull()) { bool doDisplay = true; MStatus status; MFnDagNode dagNode(node,&status); if ( status.error() ) { doDisplay = false; MGlobal::displayInfo("Error: failed to get dag node."); } if ( doDisplay ) { MString s = dagNode.name(); MString info("DAG Model - Node removed: "); info+= s; MGlobal::displayInfo(info); } } // remove the callback MCallbackId id = MMessage::currentCallbackId(); MMessage::removeCallback(id); }
MObject GetObjectOrParentsOfType(MObject & object, MTypeId & type, MStatus & status) { MFnDagNode dagNode(object); if (dagNode.typeId(&status) == type) return object; unsigned int numParents = dagNode.parentCount(&status); if (!status) { status.perror("MFnDagNode::parentCount"); return MObject::kNullObj; } for(unsigned int i = 0; i < numParents; ++i) { MObject parent; parent = dagNode.parent(i, &status); if (!status) { status.perror("MFnDagNode::parent"); return MObject::kNullObj; } MObject relative = GetObjectOrParentsOfType(parent, type, status); if (relative != MObject::kNullObj) return relative; } return MObject::kNullObj; }
MStatus RadiosityRenderer::IterateThroughDag() { MStatus status; MItDag::TraversalType traversalType = MItDag::kDepthFirst; MFn::Type filter = MFn::kMesh; MItDag dagIterator( traversalType, filter, &status); for ( ; !dagIterator.isDone(); dagIterator.next() ) { MDagPath dagPath; status = dagIterator.getPath(dagPath); if ( !status ) { status.perror("MItDag::getPath"); continue; } MFnDagNode dagNode(dagPath, &status); if ( !status ) { status.perror("MFnDagNode constructor"); continue; } //objectCount += 1; if (dagPath.hasFn(MFn::kMesh)) { MFnMesh shape (dagPath, &status); printTransformData(dagPath); } } return status; }
bool IsVisible(MDagPath& node) { MFnDagNode dagNode(node.node()); if (!IsVisible(dagNode) || IsTemplated(dagNode) || IsPathTemplated(node) || !IsInRenderLayer(node) || !IsPathVisible(node) || !IsLayerVisible(node)) return false; return true; }
MStatus recoverVisibleCmd::doIt(const MArgList&) { MStatus status; MItDag dagItr(MItDag::kDepthFirst, MFn::kInvalid,&status); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in DAG iterator");return status;} for(;!dagItr.isDone();dagItr.next()) { MDagPath dagPath; status = dagItr.getPath(dagPath); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting path");return status;} MFnDagNode dagNode(dagPath,&status); if(dagNode.isIntermediateObject())continue; if(!dagPath.hasFn(MFn::kDependencyNode))continue; MObject mObj=dagNode.object(&status); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting object");return status;} //getParticle MFnDependencyNode fnNode(mObj, &status); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting dependency node");return status;} if(fnNode.typeId() == OParticleNode::typeId) MPlug(mObj, OParticleNode::isVisible).setValue(true); if(fnNode.typeId() == edgeNode::typeId) MPlug(mObj, edgeNode::isVisible).setValue(true); } return status; }
MStatus radiusCmd::doIt(const MArgList&args) { MStatus status=MStatus::kSuccess; MArgDatabase argData(syntax(),args,&status); if(argData.isFlagSet(rFlag))argData.getFlagArgument(rFlag,0,radius); MItDag dagItr(MItDag::kDepthFirst, MFn::kInvalid,&status); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in DAG iterator");return status;} for(;!dagItr.isDone();dagItr.next()) { MDagPath dagPath; status = dagItr.getPath(dagPath); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting path");return status;} MFnDagNode dagNode(dagPath,&status); if(dagNode.isIntermediateObject())continue; if(!dagPath.hasFn(MFn::kDependencyNode))continue; MObject mObj=dagNode.object(&status); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting object");return status;} //getParticle MFnDependencyNode fnNode(mObj, &status); if(status!=MS::kSuccess){MGlobal::displayError(" Failure in getting dependency node");return status;} if(fnNode.typeId() == OParticleNode::typeId) MPlug(mObj, OParticleNode::radius).setValue(radius); } return status; }
void MSceneMessage_AfterImportOpen_CallbackFunc(void *callbackData) { MStatus status; MItDag it(MItDag::kBreadthFirst, MFn::kTransform, &status); if (!status) { status.perror("MItDag::#ctor"); return; } for(; !it.isDone(); it.next()) { MObject object = it.item(&status); if (!status) { status.perror("MObject::item"); return; } /* * Make sure the object is a Helix */ MFnDagNode dagNode(object); if (dagNode.typeId(&status) == ::Helix::Helix::id) { /* * This object is a helix, iterate over all of its bases and set their translation */ Model::Helix helix(object); for(Model::Helix::BaseIterator it = helix.begin(); it != helix.end(); ++it) { MFnTransform base_transform(it->getDagPath(status)); if (!status) { status.perror("MFnTransform::getDagPath"); return; } MVector translation = base_transform.getTranslation(MSpace::kTransform, &status); if (!status) { status.perror("MFnTransform::getTranslation"); return; } if (!(status = base_transform.setTranslation(translation, MSpace::kTransform))) { status.perror("MFnTransform::setTranslation"); return; } } } } }
bool HelixBase_NextBase(const MObject & base, const MObject & attribute, MDagPath & result, MStatus *retStatus) { MStatus status; MPlug plug(base, attribute); MPlugArray plugArray; if (plug.connectedTo(plugArray, true, true, &status)) { unsigned int plugArray_length = plugArray.length(); for(unsigned int i = 0; i < plugArray_length; ++i) { MObject target = plugArray[i].node(&status); if (!status) { status.perror("MPlugArray[i]::node"); if (retStatus) *retStatus = status; return false; } MFnDagNode dagNode(target); if (dagNode.typeId(&status) == HelixBase::id) { if (!(status = dagNode.getPath(result))) { status.perror("MFnDagNode::getPath"); if (retStatus) *retStatus = status; return false; } return true; } if (!status) { status.perror("MFnDagNode::typeId"); if (retStatus) *retStatus = status; return false; } } } if (!status) { status.perror("MPlug::connectedTo"); if (retStatus) *retStatus = status; return false; } return false; }
// // Get the geometry buffers for this bad boy // D3DGeometry* DX11ResourceManager::getGeometry( const MDagPath& dagPath, ID3D11Device* D3D) { D3DGeometry* Geometry = NULL; // Look for a cached mesh ... // // Check to see if object is in the list, if not added a // new item and cache some geometry GeometryItem *itemFound = NULL; GeometryItemList::const_iterator it, end_it; end_it = m_geometryItemList.end(); for (it = m_geometryItemList.begin(); it != end_it; it++) { GeometryItem *item = *it; if (item && item->m_objectPath == dagPath) { itemFound = item; } } // Build a new item, and add it to the list if (!itemFound) { itemFound = new GeometryItem; itemFound->m_objectPath = dagPath; Geometry = itemFound->m_objectGeometry = new D3DGeometry(); if (Geometry) { Geometry->Populate( dagPath, D3D); } MFnDagNode dagNode(dagPath); MObject &obj = (MObject &) dagNode.object(); itemFound->m_objectDeleteMonitor = MNodeMessage::addNodeAboutToDeleteCallback( obj, geometryDeleteCallback, (void *)itemFound ); // Add callback for node deleted. // Don't get attr change messages during playback, so use node dirty also..sigh //itemFound->m_objectChangeMonitor = // MNodeMessage::addAttributeChangedCallback( obj, geometryChangedCallback, (void *)itemFound); // Add callback for attr changed. itemFound->m_objectChangeMonitor = 0; itemFound->m_objectChangeMonitor = MNodeMessage::addNodeDirtyCallback( obj, geometryDirtyCallback, (void *)itemFound); // Add callback for node changed. m_geometryItemList.push_back( itemFound ); } else { Geometry = itemFound->m_objectGeometry; } // Create a new set of buffers for this mesh // return Geometry; }
MayaTransformWriter::MayaTransformWriter(double iFrame, MayaTransformWriter & iParent, MDagPath & iDag, uint32_t iTimeIndex, bool iWriteVisibility) { if (iDag.hasFn(MFn::kJoint)) { MFnIkJoint joint(iDag); Alembic::AbcGeom::OXform obj(iParent.getObject(), joint.name().asChar(), iTimeIndex); mSchema = obj.getSchema(); Alembic::Abc::OCompoundProperty cp = obj.getProperties(); mAttrs = AttributesWriterPtr(new AttributesWriter(iFrame, cp, joint, iTimeIndex, iWriteVisibility)); pushTransformStack(iFrame, joint); } else { MFnTransform trans(iDag); Alembic::AbcGeom::OXform obj(iParent.getObject(), trans.name().asChar(), iTimeIndex); mSchema = obj.getSchema(); Alembic::Abc::OCompoundProperty cp = obj.getProperties(); mAttrs = AttributesWriterPtr(new AttributesWriter(iFrame, cp, trans, iTimeIndex, iWriteVisibility)); pushTransformStack(iFrame, trans); } // need to look at inheritsTransform MFnDagNode dagNode(iDag); MPlug inheritPlug = dagNode.findPlug("inheritsTransform"); if (!inheritPlug.isNull()) { if (util::getSampledType(inheritPlug) != 0) mInheritsPlug = inheritPlug; mSample.setInheritsXforms(inheritPlug.asBool()); } // everything is default, don't write anything if (mSample.getNumOps() == 0 && mSample.getInheritsXforms()) return; mSchema.set(mSample); }
MStatus FillStrandGaps::doIt(const MArgList & args) { std::list<MObject> targets; MStatus status = ArgList_GetModelObjects(args, syntax(), "-t", targets); if (status != MStatus::kNotFound && status != MStatus::kSuccess) { HMEVALUATE_RETURN_DESCRIPTION("ArgList_GetModelObjects", status); } if (targets.empty()) { MSelectionList activeSelectionList; HMEVALUATE_RETURN(status = MGlobal::getActiveSelectionList(activeSelectionList), status); if (activeSelectionList.length() > 0) { for (unsigned int i = 0; i < activeSelectionList.length(); ++i) { MObject object; HMEVALUATE_RETURN(status = activeSelectionList.getDependNode(i, object), status); MFnDagNode dagNode(object); MTypeId typeId; HMEVALUATE_RETURN(typeId = dagNode.typeId(&status), status); if (typeId == HelixBase::id || typeId == Helix::id) targets.push_back(object); else MGlobal::displayWarning(MString("Ignoring unknown object \"") + dagNode.fullPathName() + "\""); } } else { /* * Extract all helices */ MItDag itDag(MItDag::kDepthFirst, MFn::kPluginTransformNode, &status); HMEVALUATE_RETURN_DESCRIPTION("MItDag::#ctor", status); for (; !itDag.isDone(); itDag.next()) { MObject object; HMEVALUATE_RETURN(object = itDag.currentItem(&status), status); bool is_helix; HMEVALUATE_RETURN(is_helix = MFnDagNode(object).typeId(&status) == Helix::id, status); if (is_helix) targets.push_back(object); } } } return m_operation.fill(targets); }
std::string UsdMayaAdaptor::GetMayaNodeName() const { if (!*this) { return std::string(); } if (_handle.object().hasFn(MFn::kDagNode)) { MFnDagNode dagNode(_handle.object()); return dagNode.fullPathName().asChar(); } else { MFnDependencyNode depNode(_handle.object()); return depNode.name().asChar(); } }
// If a problem occurs, this function returns an empty string. MString getNameFromObj(MObject obj) { MString nodeName; // If this object is a MFnDagNode, we should store the dag name. // Otherwise, use the MFnDependencyNode name. if (obj.hasFn(MFn::kDagNode)) { MFnDagNode dagNode(obj); nodeName = dagNode.fullPathName(); } else if (obj.hasFn(MFn::kDependencyNode)) { MFnDependencyNode node(obj); nodeName = node.name(); } return nodeName; }
void DXMNodeDagAdapter::Initialize(DXMNode* node) { DXMNodeAdapter::Initialize(node); if( g_DebugBasic ) { MFnDependencyNode depNode(node->GetSite()); MString name= depNode.name(); DXCC_DPFA_REPORT("%s", name.asChar()); } MDagPathArray dagPathArray; MFnDagNode dagNode(node->GetSite()); dagNode.getAllPaths(dagPathArray); for(UINT index= 0; index < dagPathArray.length(); index++) { AddRoute(dagPathArray[index]); } SyncFlags= DAGSYNC_TRANSFORM | DAGSYNC_VISIBILITY_OF_NODE | DAGSYNC_VISIBILITY_OF_ROUTES; GetOwnerGraphAdapter()->AddSyncRequest(this); }
int testRIBStatus::GenRIB( liquidRIBStatus * ribStatus ) { /* initialize the rib generator! */ initRibGen( ribStatus ); MFnDagNode dagNode( ribStatus->dagPath ); RiArchiveRecord( RI_COMMENT, "Liquid Rib Generation Test!" ); RiAttributeBegin(); RtColor col = { 1.0, 1.0, 1.0}; RiColor( col ); RiAttributeEnd(); MString comment("Dag Path: "); comment += ribStatus->dagPath.fullPathName(); comment += " Frame : "; comment += ribStatus->sampleTimes[0]; RiArchiveRecord( RI_COMMENT, (char *)comment.asChar()); RtColor myColor; myColor[0] = 0.1; myColor[1] = 0.2; myColor[2] = 0.3; RiColor( myColor ); return 1; }
MStatus SelectedBases(MObjectArray & result) { MStatus status; MSelectionList selectionList; if (!(status = MGlobal::getActiveSelectionList(selectionList))) { status.perror("MGlobal::getActiveSelectionList"); return status; } if (!(status = result.clear())) { status.perror("MDagPathArray::clear"); return status; } unsigned int selectionList_length = selectionList.length(&status); if (!status) { status.perror("MSelectionList::length"); return status; } for(unsigned int i = 0; i < selectionList_length; ++i) { MObject depNode; if (!(status = selectionList.getDependNode(i, depNode))) { status.perror("MSelectionList::getDependNode"); return status; } MFnDagNode dagNode(depNode); if (dagNode.typeId(&status) == HelixBase::id) result.append(depNode); else { // This is not a HelixBase, but it's parent might be? unsigned int parentCount = dagNode.parentCount(&status); if (!status) { status.perror("MFnDagNode::parentCount"); continue; } for(unsigned int j = 0; j < parentCount; ++j) { MObject parent = dagNode.parent(j, &status); if (!status) { status.perror("MFnDagNode::parent"); break; } MFnDagNode parent_dagNode(parent); if (parent_dagNode.typeId(&status) == HelixBase::id) { if (!(status = result.append(parent))) { status.perror("MObjectArray::append"); return status; } } } } } return MStatus::kSuccess; }
MStatus AlembicWriteJob::PreProcess() { ESS_PROFILE_SCOPE("AlembicWriteJob::PreProcess"); // check filenames if (mFileName.length() == 0) { MGlobal::displayError("[ExocortexAlembic] No filename specified."); MPxCommand::setResult( "Error caught in AlembicWriteJob::PreProcess: no filename specified"); return MStatus::kInvalidParameter; } // check objects if (mSelection.length() == 0) { MGlobal::displayError("[ExocortexAlembic] No objects specified."); MPxCommand::setResult( "Error caught in AlembicWriteJob::PreProcess: no objects specified"); return MStatus::kInvalidParameter; } // check frames if (mFrames.size() == 0) { MGlobal::displayError("[ExocortexAlembic] No frames specified."); MPxCommand::setResult( "Error caught in AlembicWriteJob::PreProcess: no frame specified"); return MStatus::kInvalidParameter; } // check if the file is currently in use if (getRefArchive(mFileName) > 0) { MGlobal::displayError("[ExocortexAlembic] Error writing to file '" + mFileName + "'. File currently in use."); MPxCommand::setResult( "Error caught in AlembicWriteJob::PreProcess: no filename already in " "use"); return MStatus::kInvalidParameter; } // init archive (use a locally scoped archive) // TODO: determine how to access the current maya scene path // MString sceneFileName = "Exported from: // "+Application().GetActiveProject().GetActiveScene().GetParameterValue("FileName").GetAsText(); try { createArchive("Exported from Maya."); mTop = mArchive.getTop(); // get the frame rate mFrameRate = MTime(1.0, MTime::kSeconds).as(MTime::uiUnit()); const double timePerSample = 1.0 / mFrameRate; std::vector<AbcA::chrono_t> frames; for (LONG i = 0; i < mFrames.size(); i++) { frames.push_back(mFrames[i] * timePerSample); } // create the sampling if (frames.size() > 1) { const double timePerCycle = frames[frames.size() - 1] - frames[0]; AbcA::TimeSamplingType samplingType((Abc::uint32_t)frames.size(), timePerCycle); AbcA::TimeSampling sampling(samplingType, frames); mTs = mArchive.addTimeSampling(sampling); } else { AbcA::TimeSampling sampling(1.0, frames[0]); mTs = mArchive.addTimeSampling(sampling); } Abc::OBox3dProperty boxProp = AbcG::CreateOArchiveBounds(mArchive, mTs); MDagPath dagPath; { MItDag().getPath(dagPath); } SceneNodePtr exoSceneRoot = buildMayaSceneGraph(dagPath, this->replacer); const bool bFlattenHierarchy = GetOption("flattenHierarchy") == "1"; const bool bTransformCache = GetOption("transformCache") == "1"; const bool bSelectChildren = false; { std::map<std::string, bool> selectionMap; for (int i = 0; i < (int)mSelection.length(); ++i) { MFnDagNode dagNode(mSelection[i]); selectionMap[dagNode.fullPathName().asChar()] = true; } selectNodes(exoSceneRoot, selectionMap, !bFlattenHierarchy || bTransformCache, bSelectChildren, !bTransformCache, true); } // create object for each MProgressWindow::reserve(); MProgressWindow::setTitle("Alembic Export: Listing objects"); MProgressWindow::setInterruptable(true); MProgressWindow::setProgressRange(0, mSelection.length()); MProgressWindow::setProgress(0); MProgressWindow::startProgress(); int interrupt = 20; bool processStopped = false; std::deque<PreProcessStackElement> sceneStack; sceneStack.push_back(PreProcessStackElement(exoSceneRoot, mTop)); while (!sceneStack.empty()) { if (--interrupt == 0) { interrupt = 20; if (MProgressWindow::isCancelled()) { processStopped = true; break; } } PreProcessStackElement &sElement = sceneStack.back(); SceneNodePtr eNode = sElement.eNode; sceneStack.pop_back(); Abc::OObject oParent = sElement.oParent; Abc::OObject oNewParent; AlembicObjectPtr pNewObject; if (eNode->selected) { switch (eNode->type) { case SceneNode::SCENE_ROOT: break; case SceneNode::ITRANSFORM: case SceneNode::ETRANSFORM: pNewObject.reset(new AlembicXform(eNode, this, oParent)); break; case SceneNode::CAMERA: pNewObject.reset(new AlembicCamera(eNode, this, oParent)); break; case SceneNode::POLYMESH: pNewObject.reset(new AlembicPolyMesh(eNode, this, oParent)); break; case SceneNode::SUBD: pNewObject.reset(new AlembicSubD(eNode, this, oParent)); break; case SceneNode::CURVES: pNewObject.reset(new AlembicCurves(eNode, this, oParent)); break; case SceneNode::PARTICLES: pNewObject.reset(new AlembicPoints(eNode, this, oParent)); break; case SceneNode::HAIR: pNewObject.reset(new AlembicHair(eNode, this, oParent)); break; default: ESS_LOG_WARNING("Unknown type: not exporting " << eNode->name); } } if (pNewObject) { AddObject(pNewObject); oNewParent = oParent.getChild(eNode->name); } else { oNewParent = oParent; } if (oNewParent.valid()) { for (std::list<SceneNodePtr>::iterator it = eNode->children.begin(); it != eNode->children.end(); ++it) { if (!bFlattenHierarchy || (bFlattenHierarchy && eNode->type == SceneNode::ETRANSFORM && isShapeNode((*it)->type))) { // If flattening the hierarchy, we want to attach each external // transform to its corresponding geometry node. // All internal transforms should be skipped. Geometry nodes will // never have children (If and XSI geonode is parented // to another geonode, each will be parented to its extracted // transform node, and one node will be parented to the // transform of the other. sceneStack.push_back(PreProcessStackElement(*it, oNewParent)); } else { // if we skip node A, we parent node A's children to the parent of A sceneStack.push_back(PreProcessStackElement(*it, oParent)); } } } //* else { ESS_LOG_ERROR("Do not have reference to parent."); MPxCommand::setResult( "Error caught in AlembicWriteJob::PreProcess: do not have " "reference to parent"); return MS::kFailure; } //*/ } MProgressWindow::endProgress(); return processStopped ? MStatus::kEndOfFile : MStatus::kSuccess; } catch (AbcU::Exception &e) { this->forceCloseArchive(); MString exc(e.what()); MGlobal::displayError("[ExocortexAlembic] Error writing to file '" + mFileName + "' (" + exc + "). Do you still have it opened?"); MPxCommand::setResult( "Error caught in AlembicWriteJob::PreProcess: error writing file"); } return MS::kFailure; }
/* Draw a scene full of bounding boxes */ bool MCustomSceneDraw::draw(MDagPath &cameraPath, unsigned int width, unsigned int height) { if (!cameraPath.isValid()) return false; MDrawTraversal *trav = NULL; trav = new MSurfaceDrawTraversal; if (!trav) return false; trav->enableFiltering( true ); trav->setFrustum( cameraPath, width, height ); if (!trav->frustumValid()) { delete trav; trav = NULL; return false; } trav->traverse(); unsigned int numItems = trav->numberOfItems(); unsigned int i; for (i=0; i<numItems; i++) { MDagPath path; trav->itemPath(i, path); if (path.isValid()) { bool drawIt = false; // // Draw surfaces (polys, nurbs, subdivs) // if ( path.hasFn( MFn::kMesh) || path.hasFn( MFn::kNurbsSurface) || path.hasFn( MFn::kSubdiv) ) { drawIt = true; if (trav->itemHasStatus( i, MDrawTraversal::kActiveItem )) { gGLFT->glColor3f( 1.0f, 1.0f, 1.0f ); } else if (trav->itemHasStatus( i, MDrawTraversal::kTemplateItem )) { gGLFT->glColor3f( 0.2f, 0.2f, 0.2f ); } else { if (path.hasFn( MFn::kMesh )) gGLFT->glColor3f( 0.286f, 0.706f, 1.0f ); else if (path.hasFn( MFn::kNurbsSurface)) gGLFT->glColor3f( 0.486f, 0.306f, 1.0f ); else gGLFT->glColor3f( 0.886f, 0.206f, 1.0f ); } } if (drawIt) { MFnDagNode dagNode(path); MBoundingBox box = dagNode.boundingBox(); drawBounds( path, box ); } } } if (trav) { delete trav; trav = NULL; } return true; }
MStatus HairToolContext::doPress( MEvent& event ) { // if we have a left mouse click if(event.mouseButton() == MEvent::kLeftMouse) { //Our Viewer m_View = M3dView::active3dView(); //Get Screen click position event.getPosition( m_storage[0], m_storage[1] ); screenPoints = vector<vec2>(); screenPoints.push_back(vec2(m_storage[0], m_storage[1])); //char buffer[200]; //sprintf(buffer, "print \"%i, %i\\n\"", m_storage[0], m_storage[1]); //MGlobal::executeCommand(buffer); //Camera stuff MPoint origin = MPoint(); MVector direction = MVector(); m_View.viewToWorld(m_storage[0], m_storage[1], origin, direction); //Iterate through meshes in scene bool intersection = false; MPointArray points = MPointArray(); MIntArray polygonIds = MIntArray(); MItDag dagIter = MItDag(MItDag::kBreadthFirst, MFn::kInvalid); for( ; !dagIter.isDone(); dagIter.next() ){ MDagPath dagPath; dagIter.getPath(dagPath); MFnDagNode dagNode( dagPath); //Object cannot be intermediate, it must be a mesh if( dagNode.isIntermediateObject() ) continue; if( !dagPath.hasFn(MFn::kMesh) ) continue; if( dagPath.hasFn(MFn::kTransform) ) continue; MGlobal::executeCommand(MString("print \"node is a mesh \\n\"")); //MFnMesh mesh = MFnMesh(dagPath); MFnMesh mesh(dagPath); points = MPointArray(); polygonIds = MIntArray(); intersection = mesh.intersect(origin, direction, points, 1e-010, MSpace::kWorld, &polygonIds); if(intersection){ break; } } if(intersection){ intersectionFound = true; MDagPath dagPath; dagIter.getPath(dagPath); // MFnMesh mesh = MFnMesh(dagPath); MFnMesh mesh(dagPath); //Polygon Normal MVector polygonNormal; mesh.getPolygonNormal(polygonIds[0], polygonNormal, MSpace::kWorld); if(polygonNormal.normal().angle(direction.normal()) < 20.0f){ //polygonNormal = mesh.get } //Camera Right m_View.getCamera(dagPath); MFnCamera camera(dagPath); MVector cameraRight = camera.rightDirection(MSpace::kWorld); //Resulting Plane //Point point = points[0]; //Normal normal = cameraRight^polygonNormal; //pushback point splinePoints = vector<MPoint>(); splinePoints.push_back(MPoint(points[0].x, points[0].y, points[0].z, points[0].w)); /*//Calculate Tvalue tValue = (points[0].x - origin.x)/direction.x;*/ } else{ intersectionFound = false; MGlobal::executeCommand("print \" No Intersection \\n\""); } // yay! return MS::kSuccess; } // just let the base class handle the event*/ return MPxContext::doPress(event); }
MBoundingBox AbcWriteJob::getBoundingBox(double iFrame, const MMatrix & eMInvMat) { MStatus status; MBoundingBox curBBox; if (iFrame == mFirstFrame) { // Set up bbox shape map in the first frame. // If we have a lot of transforms and shapes, we don't need to // iterate them for each frame. MItDag dagIter; for (dagIter.reset(mCurDag); !dagIter.isDone(); dagIter.next()) { MObject object = dagIter.currentItem(); MDagPath path; dagIter.getPath(path); // short-circuit if the selection flag is on but this node is not in the // active selection // MGlobal::isSelected(ob) doesn't work, because DG node and DAG node is // not the same even if they refer to the same MObject if (mArgs.useSelectionList && !mSList.hasItem(path)) { dagIter.prune(); continue; } MFnDagNode dagNode(path, &status); if (status == MS::kSuccess) { // check for riCurves flag for flattening all curve object to // one curve group MPlug riCurvesPlug = dagNode.findPlug("riCurves", &status); if ( status == MS::kSuccess && riCurvesPlug.asBool() == true) { MBoundingBox box = dagNode.boundingBox(); box.transformUsing(path.exclusiveMatrix()*eMInvMat); curBBox.expand(box); // Prune this curve group dagIter.prune(); // Save children paths std::map< MDagPath, util::ShapeSet, util::cmpDag >::iterator iter = mBBoxShapeMap.insert(std::make_pair(mCurDag, util::ShapeSet())).first; if (iter != mBBoxShapeMap.end()) (*iter).second.insert(path); } else if (object.hasFn(MFn::kParticle) || object.hasFn(MFn::kMesh) || object.hasFn(MFn::kNurbsCurve) || object.hasFn(MFn::kNurbsSurface) ) { if (util::isIntermediate(object)) continue; MBoundingBox box = dagNode.boundingBox(); box.transformUsing(path.exclusiveMatrix()*eMInvMat); curBBox.expand(box); // Save children paths std::map< MDagPath, util::ShapeSet, util::cmpDag >::iterator iter = mBBoxShapeMap.insert(std::make_pair(mCurDag, util::ShapeSet())).first; if (iter != mBBoxShapeMap.end()) (*iter).second.insert(path); } } } } else { // We have already find out all the shapes for the dag path. std::map< MDagPath, util::ShapeSet, util::cmpDag >::iterator iter = mBBoxShapeMap.find(mCurDag); if (iter != mBBoxShapeMap.end()) { // Iterate through the saved paths to calculate the box. util::ShapeSet& paths = (*iter).second; for (util::ShapeSet::iterator pathIter = paths.begin(); pathIter != paths.end(); pathIter++) { MFnDagNode dagNode(*pathIter, &status); if (status == MS::kSuccess) { MBoundingBox box = dagNode.boundingBox(); box.transformUsing((*pathIter).exclusiveMatrix()*eMInvMat); curBBox.expand(box); } } } } return curBBox; }
PxrUsdMayaShadingModeExportContext::AssignmentVector PxrUsdMayaShadingModeExportContext::GetAssignments() const { AssignmentVector ret; MStatus status; MFnDependencyNode seDepNode(_shadingEngine, &status); if (!status) { return ret; } MPlug dsmPlug = seDepNode.findPlug("dagSetMembers", true, &status); if (!status) { return ret; } SdfPathSet seenBoundPrimPaths; for (unsigned int i = 0; i < dsmPlug.numConnectedElements(); i++) { MPlug dsmElemPlug(dsmPlug.connectionByPhysicalIndex(i)); MStatus status = MS::kFailure; MFnDagNode dagNode(PxrUsdMayaUtil::GetConnected(dsmElemPlug).node(), &status); if (!status) { continue; } MDagPath dagPath; if (!dagNode.getPath(dagPath)) continue; SdfPath usdPath = PxrUsdMayaUtil::MDagPathToUsdPath(dagPath, _mergeTransformAndShape); // If _overrideRootPath is not empty, replace the root namespace with it if (!_overrideRootPath.IsEmpty() ) { usdPath = usdPath.ReplacePrefix(usdPath.GetPrefixes()[0], _overrideRootPath); } // If this path has already been processed, skip it. if (!seenBoundPrimPaths.insert(usdPath).second) continue; // If the bound prim's path is not below a bindable root, skip it. if (SdfPathFindLongestPrefix(_bindableRoots.begin(), _bindableRoots.end(), usdPath) == _bindableRoots.end()) { continue; } MObjectArray sgObjs, compObjs; // Assuming that instancing is not involved. status = dagNode.getConnectedSetsAndMembers(0, sgObjs, compObjs, true); if (!status) continue; for (size_t j = 0; j < sgObjs.length(); j++) { // If the shading group isn't the one we're interested in, skip it. if (sgObjs[j] != _shadingEngine) continue; VtIntArray faceIndices; if (!compObjs[j].isNull()) { MItMeshPolygon faceIt(dagPath, compObjs[j]); faceIndices.reserve(faceIt.count()); for ( faceIt.reset() ; !faceIt.isDone() ; faceIt.next() ) { faceIndices.push_back(faceIt.index()); } } ret.push_back(std::make_pair(usdPath, faceIndices)); } } return ret; }
MayaTransformWriter::MayaTransformWriter(MayaTransformWriter & iParent, MDagPath & iDag, Alembic::Util::uint32_t iTimeIndex, const JobArgs & iArgs) { mVerbose = iArgs.verbose; mFilterEulerRotations = iArgs.filterEulerRotations; mJointOrientOpIndex[0] = mJointOrientOpIndex[1] = mJointOrientOpIndex[2] = mRotateOpIndex[0] = mRotateOpIndex[1] = mRotateOpIndex[2] = mRotateAxisOpIndex[0] = mRotateAxisOpIndex[1] = mRotateAxisOpIndex[2] = ~size_t(0); if (iDag.hasFn(MFn::kJoint)) { MFnIkJoint joint(iDag); MString jointName = joint.name(); mName = util::stripNamespaces(jointName, iArgs.stripNamespace); Alembic::AbcGeom::OXform obj(iParent.getObject(), mName.asChar(), iTimeIndex); mSchema = obj.getSchema(); Alembic::Abc::OCompoundProperty cp; Alembic::Abc::OCompoundProperty up; if (AttributesWriter::hasAnyAttr(joint, iArgs)) { cp = mSchema.getArbGeomParams(); up = mSchema.getUserProperties(); } mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, joint, iTimeIndex, iArgs)); pushTransformStack(joint, iTimeIndex == 0); } else { MFnTransform trans(iDag); MString transName = trans.name(); mName = util::stripNamespaces(transName, iArgs.stripNamespace); Alembic::AbcGeom::OXform obj(iParent.getObject(), mName.asChar(), iTimeIndex); mSchema = obj.getSchema(); Alembic::Abc::OCompoundProperty cp; Alembic::Abc::OCompoundProperty up; if (AttributesWriter::hasAnyAttr(trans, iArgs)) { cp = mSchema.getArbGeomParams(); up = mSchema.getUserProperties(); } mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, trans, iTimeIndex, iArgs)); pushTransformStack(trans, iTimeIndex == 0); } // need to look at inheritsTransform MFnDagNode dagNode(iDag); MPlug inheritPlug = dagNode.findPlug("inheritsTransform"); if (!inheritPlug.isNull()) { if (util::getSampledType(inheritPlug) != 0) mInheritsPlug = inheritPlug; mSample.setInheritsXforms(inheritPlug.asBool()); } // everything is default, don't write anything if (mSample.getNumOps() == 0 && mSample.getInheritsXforms()) return; mSchema.set(mSample); }
MayaTransformWriter::MayaTransformWriter(Alembic::AbcGeom::OObject & iParent, MDagPath & iDag, Alembic::Util::uint32_t iTimeIndex, const JobArgs & iArgs) { mVerbose = iArgs.verbose; mFilterEulerRotations = iArgs.filterEulerRotations; mJointOrientOpIndex[0] = mJointOrientOpIndex[1] = mJointOrientOpIndex[2] = mRotateOpIndex[0] = mRotateOpIndex[1] = mRotateOpIndex[2] = mRotateAxisOpIndex[0] = mRotateAxisOpIndex[1] = mRotateAxisOpIndex[2] = ~size_t(0); if (iDag.hasFn(MFn::kJoint)) { MFnIkJoint joint(iDag); MString jointName = joint.name(); mName = util::stripNamespaces(jointName, iArgs.stripNamespace); Alembic::AbcGeom::OXform obj(iParent, mName.asChar(), iTimeIndex); mSchema = obj.getSchema(); Alembic::Abc::OCompoundProperty cp; Alembic::Abc::OCompoundProperty up; if (AttributesWriter::hasAnyAttr(joint, iArgs)) { cp = mSchema.getArbGeomParams(); up = mSchema.getUserProperties(); } mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, joint, iTimeIndex, iArgs)); if (!iArgs.worldSpace) { pushTransformStack(joint, iTimeIndex == 0); // need to look at inheritsTransform MFnDagNode dagNode(iDag); MPlug inheritPlug = dagNode.findPlug("inheritsTransform"); if (!inheritPlug.isNull()) { if (util::getSampledType(inheritPlug) != 0) mInheritsPlug = inheritPlug; mSample.setInheritsXforms(inheritPlug.asBool()); } // everything is default, don't write anything if (mSample.getNumOps() == 0 && mSample.getInheritsXforms()) return; mSchema.set(mSample); return; } } else { MFnTransform trans(iDag); MString transName = trans.name(); mName = util::stripNamespaces(transName, iArgs.stripNamespace); Alembic::AbcGeom::OXform obj(iParent, mName.asChar(), iTimeIndex); mSchema = obj.getSchema(); Alembic::Abc::OCompoundProperty cp; Alembic::Abc::OCompoundProperty up; if (AttributesWriter::hasAnyAttr(trans, iArgs)) { cp = mSchema.getArbGeomParams(); up = mSchema.getUserProperties(); } mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, trans, iTimeIndex, iArgs)); if (!iArgs.worldSpace) { pushTransformStack(trans, iTimeIndex == 0); // need to look at inheritsTransform MFnDagNode dagNode(iDag); MPlug inheritPlug = dagNode.findPlug("inheritsTransform"); if (!inheritPlug.isNull()) { if (util::getSampledType(inheritPlug) != 0) mInheritsPlug = inheritPlug; mSample.setInheritsXforms(inheritPlug.asBool()); } // everything is default, don't write anything if (mSample.getNumOps() == 0 && mSample.getInheritsXforms()) return; mSchema.set(mSample); return; } } // if we didn't bail early then we need to add all the transform // information at the current node and above // copy the dag path because we'll be popping from it MDagPath dag(iDag); int i; int numPaths = dag.length(); std::vector< MDagPath > dagList; for (i = numPaths - 1; i > -1; i--, dag.pop()) { dagList.push_back(dag); // inheritsTransform exists on both joints and transforms MFnDagNode dagNode(dag); MPlug inheritPlug = dagNode.findPlug("inheritsTransform"); // if inheritsTransform exists and is set to false, then we // don't need to worry about ancestor nodes above this one if (!inheritPlug.isNull() && !inheritPlug.asBool()) break; } std::vector< MDagPath >::iterator iStart = dagList.begin(); std::vector< MDagPath >::iterator iCur = dagList.end(); iCur--; // now loop backwards over our dagpath list so we push ancestor nodes // first, all the way down to the current node for (; iCur != iStart; iCur--) { // only add it to the stack don't write it yet! if (iCur->hasFn(MFn::kJoint)) { MFnIkJoint joint(*iCur); pushTransformStack(joint, iTimeIndex == 0); } else { MFnTransform trans(*iCur); pushTransformStack(trans, iTimeIndex == 0); } } // finally add any transform info on the final node and write it if (iCur->hasFn(MFn::kJoint)) { MFnIkJoint joint(*iCur); pushTransformStack(joint, iTimeIndex == 0); } else { MFnTransform trans(*iCur); pushTransformStack(trans, iTimeIndex == 0); } // need to look at inheritsTransform MFnDagNode dagNode(iDag); MPlug inheritPlug = dagNode.findPlug("inheritsTransform"); if (!inheritPlug.isNull()) { if (util::getSampledType(inheritPlug) != 0) mInheritsPlug = inheritPlug; mSample.setInheritsXforms(inheritPlug.asBool()); } // everything is default, don't write anything if (mSample.getNumOps() == 0 && mSample.getInheritsXforms()) return; mSchema.set(mSample); }
bool PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( const UsdTimeCode& usdTime, const UsdGeomPointInstancer& instancer) { MStatus status = MS::kSuccess; MFnDagNode dagNode(GetDagPath(), &status); CHECK_MSTATUS_AND_RETURN(status, false); // Note: In this function, we don't read instances using the provided // MFnInstancer API. One reason is that it breaks up prototypes into their // constituent shapes, and there's no way to figure out which hierarchy // they came from. Another reason is that it only provides computed matrices // and not separate position, rotation, scale attrs. const SdfPath prototypesGroupPath = instancer.GetPrim().GetPath().AppendChild(_tokens->Prototypes); // At the default time, setup all the prototype instances. if (usdTime.IsDefault()) { const MPlug inputHierarchy = dagNode.findPlug("inputHierarchy", true, &status); CHECK_MSTATUS_AND_RETURN(status, false); // Note that the "Prototypes" prim needs to be a model group to ensure // contiguous model hierarchy. const UsdPrim prototypesGroupPrim = GetUsdStage()->DefinePrim( prototypesGroupPath); UsdModelAPI(prototypesGroupPrim).SetKind(KindTokens->group); _modelPaths.push_back(prototypesGroupPath); UsdRelationship prototypesRel = instancer.CreatePrototypesRel(); const unsigned int numElements = inputHierarchy.numElements(); for (unsigned int i = 0; i < numElements; ++i) { const MPlug plug = inputHierarchy[i]; const MPlug source(UsdMayaUtil::GetConnected(plug)); if (source.isNull()) { TF_WARN("Cannot read prototype: the source plug %s was null", plug.name().asChar()); return false; } MFnDagNode sourceNode(source.node(), &status); CHECK_MSTATUS_AND_RETURN(status, false); MDagPath prototypeDagPath; sourceNode.getPath(prototypeDagPath); // Prototype names are guaranteed unique by virtue of having a // unique numerical suffix _# indicating the prototype index. const TfToken prototypeName( TfStringPrintf("%s_%d", sourceNode.name().asChar(), i)); const SdfPath prototypeUsdPath = prototypesGroupPrim.GetPath() .AppendChild(prototypeName); UsdPrim prototypePrim = GetUsdStage()->DefinePrim( prototypeUsdPath); _modelPaths.push_back(prototypeUsdPath); // Try to be conservative and only create an intermediary xformOp // with the instancerTranslate if we can ensure that we don't need // to compensate for the translation on the prototype root. // // XXX: instancerTranslate does not behave well when added to a // reference that has an existing transform on the far side of the // reference. However, its behavior at least matches the // behavior in UsdMayaTranslatorModelAssembly. If we fix the // behavior there, we need to make sure that this is also // fixed to match. bool instancerTranslateAnimated = false; if (_NeedsExtraInstancerTranslate( prototypeDagPath, &instancerTranslateAnimated)) { UsdGeomXformable xformable(prototypePrim); UsdGeomXformOp newOp = xformable.AddTranslateOp( UsdGeomXformOp::PrecisionDouble, _tokens->instancerTranslate); _instancerTranslateOps.push_back( {prototypeDagPath, newOp, instancerTranslateAnimated}); } // Two notes: // (1) We don't un-instance here, because it's OK for the prototype // to just be a reference to an instance master if the prototype // participates in Maya native instancing. // (2) The prototype root must be visible to match Maya's behavior, // which always vis'es the prototype root, even if it is marked // hidden. _writeJobCtx.CreatePrimWriterHierarchy( prototypeDagPath, prototypeUsdPath, /*forceUninstance*/ false, /*exportRootVisibility*/ false, &_prototypeWriters); prototypesRel.AddTarget(prototypeUsdPath); } _numPrototypes = numElements; } // If there aren't any prototypes, fail and don't export on subsequent // time-sampled exports. if (_numPrototypes == 0) { return false; } // Actual write of prototypes (@ both default time and animated time). for (UsdMayaPrimWriterSharedPtr& writer : _prototypeWriters) { writer->Write(usdTime); if (usdTime.IsDefault()) { // Prototype roots should have kind component or derived. // Calling Write() above may have populated kinds, so don't stomp // over existing component-derived kinds. // (Note that ModelKindWriter's fix-up stage might change this.) if (writer->GetUsdPath().GetParentPath() == prototypesGroupPath) { if (const UsdPrim writerPrim = writer->GetUsdPrim()) { UsdModelAPI primModelAPI(writerPrim); TfToken kind; primModelAPI.GetKind(&kind); if (!KindRegistry::IsA(kind, KindTokens->component)) { primModelAPI.SetKind(KindTokens->component); } } } } } // Write the instancerTranslate xformOp for all prims that need it. // (This should happen @ default time or animated time depending on whether // the xform is animated.) for (const _TranslateOpData& opData : _instancerTranslateOps) { if (opData.isAnimated != usdTime.IsDefault()) { GfVec3d origin; if (_GetTransformedOriginInLocalSpace(opData.mayaPath, &origin)) { UsdGeomXformOp translateOp = opData.op; _SetAttribute(translateOp.GetAttr(), -origin, usdTime); } } } // Grab the inputPoints data from the source plug. // (This attribute's value must come from a source plug; it isn't // directly writeable. Thus reading it directly may not give the right // value depending on Maya's execution behavior.) MPlug inputPointsDest = dagNode.findPlug("inputPoints", true, &status); CHECK_MSTATUS_AND_RETURN(status, false); MPlug inputPointsSrc = UsdMayaUtil::GetConnected(inputPointsDest); if (inputPointsSrc.isNull()) { TF_WARN("inputPoints not connected on instancer '%s'", GetDagPath().fullPathName().asChar()); return false; } auto holder = UsdMayaUtil::GetPlugDataHandle(inputPointsSrc); if (!holder) { TF_WARN("Unable to read inputPoints data handle for instancer '%s'", GetDagPath().fullPathName().asChar()); return false; } MFnArrayAttrsData inputPointsData(holder->GetDataHandle().data(), &status); CHECK_MSTATUS_AND_RETURN(status, false); if (!UsdMayaWriteUtil::WriteArrayAttrsToInstancer( inputPointsData, instancer, _numPrototypes, usdTime, _GetSparseValueWriter())) { return false; } // Load the completed point instancer to compute and set its extent. instancer.GetPrim().GetStage()->Load(instancer.GetPath()); VtArray<GfVec3f> extent(2); if (instancer.ComputeExtentAtTime(&extent, usdTime, usdTime)) { _SetAttribute(instancer.CreateExtentAttr(), &extent, usdTime); } return true; }
bool DX11ViewportRenderer::drawScene(const MRenderingInfo &renderInfo) // // Description: // Draw the Maya scene, using a custom traverser. // { bool useDrawTraversal = true; float groundPlaneColor[3] = { 0.8f, 0.8f, 0.8f }; if (useDrawTraversal) { const MDagPath &cameraPath = renderInfo.cameraPath(); if (cameraPath.isValid()) { // You can actually keep the traverser classes around // if desired. Here we just create temporary traversers // on the fly. // MDrawTraversal *trav = new MDrawTraversal; if (!trav) { MGlobal::displayWarning("DX11 renderer : failed to create a traversal class !\n"); return true; } trav->enableFiltering( false ); const MRenderTarget &renderTarget = renderInfo.renderTarget(); trav->setFrustum( cameraPath, renderTarget.width(), renderTarget.height() ); if (!trav->frustumValid()) { MGlobal::displayWarning("DX11 renderer : Frustum is invalid !\n"); return true; } trav->traverse(); unsigned int numItems = trav->numberOfItems(); unsigned int i; for (i=0; i<numItems; i++) { MDagPath path; trav->itemPath(i, path); if (path.isValid()) { bool drawIt = false; // Default traverer may have view manips showing up. // This is currently a known Maya bug. if ( path.hasFn( MFn::kViewManip )) continue; // // Draw surfaces (polys, nurbs, subdivs) // bool active = false; bool templated = false; if ( path.hasFn( MFn::kMesh) || path.hasFn( MFn::kNurbsSurface) || path.hasFn( MFn::kSubdiv) ) { drawIt = true; if (trav->itemHasStatus( i, MDrawTraversal::kActiveItem )) { active = true; } if (trav->itemHasStatus( i, MDrawTraversal::kTemplateItem )) { templated = true; } } // // Draw the ground plane // else if (path.hasFn( MFn::kSketchPlane ) || path.hasFn( MFn::kGroundPlane )) { MMatrix matrix = path.inclusiveMatrix(); MFnDagNode dagNode(path); MBoundingBox box = dagNode.boundingBox(); drawBounds( matrix, box, groundPlaneColor ); } if (drawIt) { drawSurface( path, active, templated ); } } } if (trav) delete trav; // Cleanup any unused resource items bool onlyInvalidItems = true; clearResources( onlyInvalidItems, false ); } } else { // Draw some poly bounding boxes // MItDag::TraversalType traversalType = MItDag::kDepthFirst; MFn::Type filter = MFn::kMesh; MStatus status; MItDag dagIterator( traversalType, filter, &status); for ( ; !dagIterator.isDone(); dagIterator.next() ) { MDagPath dagPath; status = dagIterator.getPath(dagPath); if ( !status ) { status.perror("MItDag::getPath"); continue; } MFnDagNode dagNode(dagPath, &status); if ( !status ) { status.perror("MFnDagNode constructor"); continue; } MMatrix matrix = dagPath.inclusiveMatrix(); MBoundingBox box = dagNode.boundingBox(); drawBounds( matrix, box, groundPlaneColor ); } } return true; }
void MayaObject::initialize() { this->isInstancerObject = false; this->instancerParticleId = -1; this->instanceNumber = 0; this->attributes = nullptr; this->origObject = nullptr; this->shortName = getObjectName(mobject); this->fullName = this->dagPath.fullPathName(); this->fullNiceName = makeGoodString(this->fullName); this->transformMatrices.push_back(this->dagPath.inclusiveMatrix()); this->instanceNumber = dagPath.instanceNumber(); MFnDependencyNode depFn(mobject); this->motionBlurred = true; this->geometryMotionblur = false; bool mb = true; if( getBool(MString("motionBlur"), depFn, mb) ) this->motionBlurred = mb; // cameras have motionBlur attribute but it is set to false by default and it is not accessible via UI // but we want to have a blurred camera by default. if( this->mobject.hasFn(MFn::kCamera)) this->motionBlurred = true; this->perObjectTransformSteps = 1; this->perObjectDeformSteps = 1; this->index = -1; this->shapeConnected = false; this->lightExcludeList = true; // In most cases only a few lights are ignored, so the list is shorter with excluded lights this->shadowExcludeList = true; // in most cases only a few objects ignore shadows, so the list is shorter with ignoring objects this->animated = this->isObjAnimated(); this->shapeConnected = this->isShapeConnected(); this->parent = nullptr; this->visible = true; this->hasInstancerConnection = false; MDagPath dp; dp = dagPath; MFnDagNode dagNode(this->mobject); if (!IsVisible(dagNode) || IsTemplated(dagNode) || !IsInRenderLayer(dp) || !IsPathVisible(dp) || !IsLayerVisible(this->dagPath)) this->visible = false; // get instancer connection MStatus stat; MPlug matrixPlug = depFn.findPlug(MString("matrix"), &stat); if( !stat) Logging::debug(MString("Could not find matrix plug")); else{ MPlugArray outputs; if( matrixPlug.isConnected()) { matrixPlug.connectedTo(outputs, false, true); for( uint i = 0; i < outputs.length(); i++) { MObject otherSide = outputs[i].node(); Logging::debug(MString("matrix is connected to ") + getObjectName(otherSide)); if( otherSide.hasFn(MFn::kInstancer)) { Logging::debug(MString("other side is instancer")); this->hasInstancerConnection = true; } } } } if( this->mobject.hasFn(MFn::kWorld)) { this->shortName = this->fullName = this->fullNiceName = "world"; } }
bool DX11ViewportRenderer::drawSurface( const MDagPath &dagPath, bool active, bool templated) { bool drewSurface = false; if ( !dagPath.hasFn( MFn::kMesh )) { MMatrix matrix = dagPath.inclusiveMatrix(); MFnDagNode dagNode(dagPath); MBoundingBox box = dagNode.boundingBox(); float color[3] = {0.6f, 0.3f, 0.0f}; if (active) { color[0] = 1.0f; color[1] = 1.0f; color[2] = 1.0f; } else if (templated) { color[0] = 1.0f; color[1] = 0.686f; color[2] = 0.686f; } drawBounds( matrix, box, color); return true; } if ( dagPath.hasFn( MFn::kMesh )) { MMatrix matrix = dagPath.inclusiveMatrix(); MFnDagNode dagNode(dagPath); // Look for any hardware shaders which can draw D3D first. // bool drewWithHwShader = false; { MFnMesh fnMesh(dagPath); MObjectArray sets; MObjectArray comps; unsigned int instanceNum = dagPath.instanceNumber(); if (!fnMesh.getConnectedSetsAndMembers(instanceNum, sets, comps, true)) MGlobal::displayError("ERROR : MFnMesh::getConnectedSetsAndMembers"); for ( unsigned i=0; i<sets.length(); i++ ) { MObject set = sets[i]; MObject comp = comps[i]; MStatus status; MFnSet fnSet( set, &status ); if (status == MS::kFailure) { MGlobal::displayError("ERROR: MFnSet::MFnSet"); continue; } MObject shaderNode = findShader(set); if (shaderNode != MObject::kNullObj) { MPxHardwareShader * hwShader = MPxHardwareShader::getHardwareShaderPtr( shaderNode ); if (hwShader) { const MRenderProfile & profile = hwShader->profile(); if (profile.hasRenderer( MRenderProfile::kMayaD3D)) { // Render a Maya D3D hw shader here.... //printf("Found a D3D hw shader\n"); //drewWithHwShader = true; } } } } } // Get the geometry buffers for this bad boy and render them D3DGeometry* Geometry = m_resourceManager.getGeometry( dagPath, m_pD3DDevice); if( Geometry) { // Transform from object to world space // XMMATRIX objectToWorld = XMMATRIX ( (float)matrix.matrix[0][0], (float)matrix.matrix[0][1], (float)matrix.matrix[0][2], (float)matrix.matrix[0][3], (float)matrix.matrix[1][0], (float)matrix.matrix[1][1], (float)matrix.matrix[1][2], (float)matrix.matrix[1][3], (float)matrix.matrix[2][0], (float)matrix.matrix[2][1], (float)matrix.matrix[2][2], (float)matrix.matrix[2][3], (float)matrix.matrix[3][0], (float)matrix.matrix[3][1], (float)matrix.matrix[3][2], (float)matrix.matrix[3][3] ); FixedFunctionConstants cb; if (!drewWithHwShader) { // Get material properties for shader associated with mesh // // 1. Try to draw with the sample internal programmable shader bool drewGeometryWithShader = false; // 2. Draw with fixed function shader if (!drewGeometryWithShader) { // Set up a default material, just in case there is none. // float diffuse[3]; if (active) { if (templated) { m_pD3DDeviceCtx->RSSetState( m_pWireframeRS ); diffuse[0] = 1.0f; diffuse[1] = 0.686f; diffuse[2] = 0.686f; } else { m_pD3DDeviceCtx->RSSetState( m_pNormalRS ); diffuse[0] = 0.6f; diffuse[1] = 0.6f; diffuse[2] = 0.6f; } } else { if (templated) { m_pD3DDeviceCtx->RSSetState( m_pWireframeRS ); diffuse[0] = 1.0f; diffuse[1] = 0.686f; diffuse[2] = 0.686f; } else { m_pD3DDeviceCtx->RSSetState( m_pNormalRS ); diffuse[0] = 0.5f; diffuse[1] = 0.5f; diffuse[2] = 0.5f; } } // Set constant buffer XMVECTOR det; cb.wvIT = XMMatrixInverse( &det, objectToWorld * m_currentViewMatrix ); cb.wvp = XMMatrixTranspose( objectToWorld * m_currentViewMatrix * m_currentProjectionMatrix ); cb.wv = XMMatrixTranspose( objectToWorld * m_currentViewMatrix ); cb.lightDir = XMFLOAT4( 0.0f, 0.0f, 1.0f, 0.0f ); cb.lightColor = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f ); cb.ambientLight = XMFLOAT4( 0.2f, 0.2f, 0.2f, 0.0f ); cb.diffuseMaterial = XMFLOAT4( diffuse[0], diffuse[1], diffuse[2], 0.0f ); cb.specularColor = XMFLOAT4( 0.2f, 0.2f, 0.2f, 0.0f ); cb.diffuseCoeff = 1.0f; cb.shininess = 16.0f; cb.transparency = 1.0f; m_pD3DDeviceCtx->UpdateSubresource( m_pFixedFunctionConstantBuffer, 0, NULL, &cb, 0, 0 ); // get shader SurfaceEffectItemList::const_iterator it = m_resourceManager.getSurfaceEffectItemList().find( "Maya_fixedFunction" ); if ( it == m_resourceManager.getSurfaceEffectItemList().end() ) return false; const SurfaceEffectItem* sei = it->second; // bind shaders m_pD3DDeviceCtx->VSSetShader( sei->fVertexShader, NULL, 0 ); m_pD3DDeviceCtx->VSSetConstantBuffers( 0, 1, &m_pFixedFunctionConstantBuffer ); m_pD3DDeviceCtx->IASetInputLayout( sei->fInputLayout ); m_pD3DDeviceCtx->PSSetShader( sei->fPixelShader, NULL, 0 ); m_pD3DDeviceCtx->PSSetConstantBuffers( 0, 1, &m_pFixedFunctionConstantBuffer ); Geometry->Render( m_pD3DDeviceCtx ); drewSurface = true; } } // Draw wireframe on top // if ( drewSurface && active ) { bool drawActiveWithBounds = false; if (drawActiveWithBounds) { MBoundingBox box = dagNode.boundingBox(); float color[3] = {1.0f, 1.0f, 1.0f}; drawBounds( matrix, box, color ); } else { cb.lightColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); cb.ambientLight = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f ); cb.diffuseMaterial = XMFLOAT4( 1.0f, 1.0f, 1.0f, 0.0f ); cb.specularColor = XMFLOAT4( 0.0f, 0.0f, 0.0f, 0.0f ); m_pD3DDeviceCtx->UpdateSubresource( m_pFixedFunctionConstantBuffer, 0, NULL, &cb, 0, 0 ); m_pD3DDeviceCtx->RSSetState( m_pWireframeRS ); Geometry->Render( m_pD3DDeviceCtx ); } } } // If Geometry } return drewSurface; }
bool CXRayObjectExport::initializeSetsAndLookupTables( bool exportAll ) // // Description : // Creates a list of all sets in Maya, a list of mesh objects, // and polygon/vertex lookup tables that will be used to // determine which sets are referenced by the poly components. // { int i=0,j=0, length; MStatus stat; // Initialize class data. // Note: we cannot do this in the constructor as it // only gets called upon registry of the plug-in. // numSets = 0; sets = NULL; lastSets = NULL; lastMaterials = NULL; objectId = 0; objectCount = 0; polygonTable = NULL; vertexTable = NULL; polygonTablePtr = NULL; vertexTablePtr = NULL; objectGroupsTablePtr = NULL; objectNodeNamesArray.clear(); transformNodeNameArray.clear(); ////////////////////////////////////////////////////////////////// // // Find all sets in Maya and store the ones we care about in // the 'sets' array. Also make note of the number of sets. // ////////////////////////////////////////////////////////////////// // Get all of the sets in maya and put them into // a selection list // MStringArray result; MGlobal::executeCommand( "ls -sets", result ); MSelectionList * setList = new MSelectionList(); length = result.length(); for ( i=0; i<length; i++ ) { setList->add( result[i] ); } // Extract each set as an MObject and add them to the // sets array. // We may be excluding groups, matierials, or ptGroups // in which case we can ignore those sets. // MObject mset; sets = new MObjectArray(); length = setList->length(); for ( i=0; i<length; i++ ) { setList->getDependNode( i, mset ); MFnSet fnSet( mset, &stat ); if ( stat ) { if ( MFnSet::kRenderableOnly == fnSet.restriction(&stat) ) { sets->append( mset ); } } } xr_delete(setList); numSets = sets->length(); ////////////////////////////////////////////////////////////////// // // Do a dag-iteration and for every mesh found, create facet and // vertex look-up tables. These tables will keep track of which // sets each component belongs to. // // If exportAll is false then iterate over the activeSelection // list instead of the entire DAG. // // These arrays have a corrisponding entry in the name // stringArray. // ////////////////////////////////////////////////////////////////// MIntArray vertexCounts; MIntArray polygonCounts; if ( exportAll ) { MItDag dagIterator( MItDag::kBreadthFirst, MFn::kInvalid, &stat); if ( MS::kSuccess != stat) { fprintf(stderr,"Failure in DAG iterator setup.\n"); return false; } objectNames = new MStringArray(); for ( ; !dagIterator.isDone(); dagIterator.next() ) { MDagPath dagPath; stat = dagIterator.getPath( dagPath ); if ( stat ) { // skip over intermediate objects // MFnDagNode dagNode( dagPath, &stat ); if (dagNode.isIntermediateObject()) { continue; } if (( dagPath.hasFn(MFn::kMesh)) && ( dagPath.hasFn(MFn::kTransform))) { // We want only the shape, // not the transform-extended-to-shape. continue; } else if ( dagPath.hasFn(MFn::kMesh)) { // We have a mesh so create a vertex and polygon table // for this object. // MFnMesh fnMesh( dagPath ); int vtxCount = fnMesh.numVertices(); int polygonCount = fnMesh.numPolygons(); // we do not need this call anymore, we have the shape. // dagPath.extendToShape(); MString name = dagPath.fullPathName(); objectNames->append( name ); objectNodeNamesArray.append( fnMesh.name() ); vertexCounts.append( vtxCount ); polygonCounts.append( polygonCount ); objectCount++; } } } }else{ MSelectionList slist; MGlobal::getActiveSelectionList( slist ); MItSelectionList iter( slist ); MStatus status; objectNames = new MStringArray(); // We will need to interate over a selected node's heirarchy // in the case where shapes are grouped, and the group is selected. MItDag dagIterator( MItDag::kDepthFirst, MFn::kInvalid, &status); for ( ; !iter.isDone(); iter.next() ){ MDagPath objectPath; stat = iter.getDagPath( objectPath ); // reset iterator's root node to be the selected node. status = dagIterator.reset (objectPath.node(), MItDag::kDepthFirst, MFn::kInvalid ); // DAG iteration beginning at at selected node for ( ; !dagIterator.isDone(); dagIterator.next() ){ MDagPath dagPath; MObject component = MObject::kNullObj; status = dagIterator.getPath(dagPath); if (!status){ fprintf(stderr,"Failure getting DAG path.\n"); freeLookupTables(); return false; } // skip over intermediate objects // MFnDagNode dagNode( dagPath, &stat ); if (dagNode.isIntermediateObject()) continue; if (( dagPath.hasFn(MFn::kMesh)) && ( dagPath.hasFn(MFn::kTransform))){ // We want only the shape, // not the transform-extended-to-shape. continue; }else if ( dagPath.hasFn(MFn::kMesh)){ // We have a mesh so create a vertex and polygon table // for this object. // MFnMesh fnMesh( dagPath ); int vtxCount = fnMesh.numVertices(); int polygonCount = fnMesh.numPolygons(); // we do not need this call anymore, we have the shape. // dagPath.extendToShape(); MString name = dagPath.fullPathName(); objectNames->append( name ); objectNodeNamesArray.append( fnMesh.name() ); vertexCounts.append( vtxCount ); polygonCounts.append( polygonCount ); objectCount++; } } } } // Now we know how many objects we are dealing with // and we have counts of the vertices/polygons for each // object so create the maya group look-up table. // if( objectCount > 0 ) { // To export Maya groups we traverse the hierarchy starting at // each objectNodeNamesArray[i] going towards the root collecting transform // nodes as we go. length = objectNodeNamesArray.length(); for( i=0; i<length; i++ ) { MIntArray transformNodeNameIndicesArray; recFindTransformDAGNodes( objectNodeNamesArray[i], transformNodeNameIndicesArray ); } if( transformNodeNameArray.length() > 0 ) { objectGroupsTablePtr = xr_alloc<bool*>(objectCount);// (bool**) malloc( sizeof(bool*)*objectCount ); length = transformNodeNameArray.length(); for ( i=0; i<objectCount; i++ ) { // objectGroupsTablePtr[i] = (bool*)calloc( length, sizeof(bool) ); objectGroupsTablePtr[i] = xr_alloc<bool>(length); ZeroMemory(objectGroupsTablePtr[i],length*sizeof(bool)); // XXX nitrocaster: remove this 'cause malloc failure shouldn't be handled there if ( objectGroupsTablePtr[i] == NULL ) { Log("! calloc returned NULL (objectGroupsTablePtr)"); return false; } } } // else{ // Log("! Can't find transform for node."); // return false; // } } // Create the vertex/polygon look-up tables. // if ( objectCount > 0 ) { vertexTablePtr = xr_alloc<bool*>(objectCount); //(bool**) malloc( sizeof(bool*)*objectCount ); polygonTablePtr = xr_alloc<bool*>(objectCount); //(bool**) malloc( sizeof(bool*)*objectCount ); for ( i=0; i<objectCount; i++ ) { // vertexTablePtr[i] = (bool*)calloc( vertexCounts[i]*numSets, sizeof(bool) ); vertexTablePtr[i] = xr_alloc<bool>(vertexCounts[i]*numSets); ZeroMemory(vertexTablePtr[i],vertexCounts[i]*numSets*sizeof(bool)); // XXX nitrocaster: remove this 'cause malloc failure shouldn't be handled there if ( vertexTablePtr[i] == NULL ) { Log("! calloc returned NULL (vertexTable)"); return false; } // polygonTablePtr[i] = (bool*)calloc( polygonCounts[i]*numSets, sizeof(bool) ); polygonTablePtr[i] = xr_alloc<bool>(polygonCounts[i]*numSets); ZeroMemory(polygonTablePtr[i],polygonCounts[i]*numSets*sizeof(bool)); // XXX nitrocaster: remove this 'cause malloc failure shouldn't be handled there if ( polygonTablePtr[i] == NULL ) { Log("! calloc returned NULL (polygonTable)"); return false; } } } // If we found no meshes then return // if ( objectCount == 0 ) { return false; } ////////////////////////////////////////////////////////////////// // // Go through all of the set members (flattened lists) and mark // in the lookup-tables, the sets that each mesh component belongs // to. // // ////////////////////////////////////////////////////////////////// bool flattenedList = true; MDagPath object; MObject component; MSelectionList memberList; for ( i=0; i<numSets; i++ ) { MFnSet fnSet( (*sets)[i] ); memberList.clear(); stat = fnSet.getMembers( memberList, flattenedList ); if (MS::kSuccess != stat) { fprintf(stderr,"Error in fnSet.getMembers()!\n"); } int m, numMembers; numMembers = memberList.length(); for ( m=0; m<numMembers; m++ ) { if ( memberList.getDagPath(m,object,component) ) { if ( (!component.isNull()) && (object.apiType() == MFn::kMesh) ) { if (component.apiType() == MFn::kMeshVertComponent) { MItMeshVertex viter( object, component ); for ( ; !viter.isDone(); viter.next() ) { int compIdx = viter.index(); MString name = object.fullPathName(); // Figure out which object vertexTable // to get. // int o, numObjectNames; numObjectNames = objectNames->length(); for ( o=0; o<numObjectNames; o++ ) { if ( (*objectNames)[o] == name ) { // Mark set i as true in the table // vertexTable = vertexTablePtr[o]; *(vertexTable + numSets*compIdx + i) = true; break; } } } } else if (component.apiType() == MFn::kMeshPolygonComponent) { MItMeshPolygon piter( object, component ); for ( ; !piter.isDone(); piter.next() ) { int compIdx = piter.index(); MString name = object.fullPathName(); // Figure out which object polygonTable // to get. // int o, numObjectNames; numObjectNames = objectNames->length(); for ( o=0; o<numObjectNames; o++ ) { if ( (*objectNames)[o] == name ) { // Mark set i as true in the table // // Check for bad components in the set // if ( compIdx >= polygonCounts[o] ) { Msg("! Bad polygon index '%d' found. Polygon skipped",compIdx); break; } polygonTable = polygonTablePtr[o]; *(polygonTable + numSets*compIdx + i) = true; break; } } } } } else { // There are no components, therefore we can mark // all polygons as members of the given set. // if (object.hasFn(MFn::kMesh)) { MFnMesh fnMesh( object, &stat ); if ( MS::kSuccess != stat) { fprintf(stderr,"Failure in MFnMesh initialization.\n"); return false; } // We are going to iterate over all the polygons. // MItMeshPolygon piter( object, MObject::kNullObj, &stat ); if ( MS::kSuccess != stat) { fprintf(stderr, "Failure in MItMeshPolygon initialization.\n"); return false; } for ( ; !piter.isDone(); piter.next() ) { int compIdx = piter.index(); MString name = object.fullPathName(); // Figure out which object polygonTable to get. // int o, numObjectNames; numObjectNames = objectNames->length(); for ( o=0; o<numObjectNames; o++ ) { if ( (*objectNames)[o] == name ) { // Check for bad components in the set // if ( compIdx >= polygonCounts[o] ) { Msg("! Bad polygon index '%d' found. Polygon skipped",compIdx); break; } // Mark set i as true in the table // polygonTable = polygonTablePtr[o]; *(polygonTable + numSets*compIdx + i) = true; break; } } } // end of piter.next() loop } // end of condition if (object.hasFn(MFn::kMesh)) } // end of else condifion if (!component.isNull()) } // end of memberList.getDagPath(m,object,component) } // end of memberList loop } // end of for-loop for sets // Go through all of the group members and mark in the // lookup-table, the group that each shape belongs to. length = objectNodeNamesArray.length(); if (objectGroupsTablePtr){ for( i=0; i<length; i++ ) { MIntArray groupTableIndicesArray; bool *objectGroupTable = objectGroupsTablePtr[i]; int length2; recFindTransformDAGNodes( objectNodeNamesArray[i], groupTableIndicesArray ); length2 = groupTableIndicesArray.length(); for( j=0; j<length2; j++ ) { int groupIdx = groupTableIndicesArray[j]; objectGroupTable[groupIdx] = true; } } } return true; }