void
UsdRiStatementsAPI::SetCoordinateSystem(const std::string &coordSysName)
{
    UsdAttribute attr = GetPrim().CreateAttribute(_tokens->coordsys, 
                                                  SdfValueTypeNames->String, 
                                                  /* custom = */ false);
    if (TF_VERIFY(attr)) {
        attr.Set(coordSysName);

        UsdPrim currPrim = GetPrim();
        while (currPrim && currPrim.GetPath() != SdfPath::AbsoluteRootPath()) {
            if (currPrim.IsModel() && !currPrim.IsGroup() &&
                currPrim.GetPath() != SdfPath::AbsoluteRootPath()) {
                UsdRelationship rel =
                    currPrim.CreateRelationship(_tokens->modelCoordsys,
                                                /* custom = */ false);
                if (TF_VERIFY(rel)) {
                    // Order should not matter, since these are a set,
                    // but historically we have appended these.
                    rel.AddTarget(GetPrim().GetPath());
                }
                break;
            }

            currPrim = currPrim.GetParent();
        }
    }
}
Example #2
0
/* static */
GfMatrix4d
GusdPrimWrapper::computeTransform( 
        const UsdPrim&              prim,
        UsdTimeCode                 time,
        const UT_Matrix4D&          houXform,
        const GusdSimpleXformCache& xformCache ) {

    // We need the transform into the prims space.
    // If the prim is in a hierarchy that we have written on this frame, 
    // its transform will be in the xformCache. Otherwise, we can read it 
    // from the global cache. 
    //
    // The transform cache is necessary because the gobal cache 
    // will only contain transform that we read from the stage and 
    // not anything that we have modified.

    UT_Matrix4D primXform;
    auto it = xformCache.find( prim.GetPath() );
    if( it != xformCache.end() ) {
        primXform = it->second;
    }
    else if( !GusdUSD_XformCache::GetInstance().GetLocalToWorldTransform( 
                        prim,
                        time,
                        primXform )) {
        TF_WARN( "Failed to get transform for %s.", prim.GetPath().GetText() );
        primXform.identity();
    }
    return GusdUT_Gf::Cast( houXform ) / GusdUT_Gf::Cast( primXform );
}
Example #3
0
void
GusdUSD_XformCache::XformInfo::ComputeFlags(const UsdPrim& prim,
                                            GusdUSD_XformCache& cache)
{
    if(query.TransformMightBeTimeVarying()) {
        _flags = FLAGS_LOCAL_MAYBE_TIMEVARYING|
                 FLAGS_WORLD_MAYBE_TIMEVARYING;
    } else {
        /* Local transform isn't time-varying, but maybe the parent is.*/
        if(!query.GetResetXformStack()) {
            UsdPrim parent = prim.GetParent();
            if(parent && parent.GetPath() != SdfPath::AbsoluteRootPath()) {
                auto info = cache.GetXformInfo(parent);
                if(info && info->WorldXformIsMaybeTimeVarying())
                    _flags = FLAGS_WORLD_MAYBE_TIMEVARYING;
            }
        }
    }
    
    if(!query.GetResetXformStack()) {
        UsdPrim parent = prim.GetParent();
        if(parent && parent.GetPath() != SdfPath::AbsoluteRootPath())
            _flags |= FLAGS_HAS_PARENT_XFORM;
    }
}
SdfPath
UsdImagingMaterialAdapter::Populate(UsdPrim const& prim,
                            UsdImagingIndexProxy* index,
                            UsdImagingInstancerContext const* instancerContext)
{
    // Since material are populated by reference, they need to take care not to
    // be populated multiple times.
    SdfPath cachePath = prim.GetPath();
    if (index->IsPopulated(cachePath)) {
        return cachePath;
    }

    index->InsertSprim(HdPrimTypeTokens->material,
                       cachePath,
                       prim, shared_from_this());
    HD_PERF_COUNTER_INCR(UsdImagingTokens->usdPopulatedPrimCount);

    // Also register this adapter on behalf of any descendent
    // UsdShadeShader prims, since they are consumed to
    // create the material network.
    for (UsdPrim const& child: prim.GetDescendants()) {
        if (child.IsA<UsdShadeShader>()) {
            index->AddPrimInfo(child.GetPath(), child, shared_from_this());
        }
    }

    return prim.GetPath();
}
SdfPath
UsdImagingSphereLightAdapter::Populate(UsdPrim const& prim, 
                            UsdImagingIndexProxy* index,
                            UsdImagingInstancerContext const* instancerContext)
{
    index->InsertSprim(HdPrimTypeTokens->sphereLight, prim.GetPath(), prim);
    HD_PERF_COUNTER_INCR(UsdImagingTokens->usdPopulatedPrimCount);

    return prim.GetPath();
}
Example #6
0
SdfPath
UsdImagingPointsAdapter::Populate(UsdPrim const& prim, 
                            UsdImagingIndexProxy* index,
                            UsdImagingInstancerContext const* instancerContext)
{
    index->InsertPoints(prim.GetPath(),
                        GetShaderBinding(prim),
                        instancerContext);
    HD_PERF_COUNTER_INCR(UsdImagingTokens->usdPopulatedPrimCount);

    return prim.GetPath();
}
Example #7
0
bool GusdXformWrapper::
initUsdPrim(const UsdStagePtr& stage,
            const SdfPath& path,
            bool asOverride)
{
    bool newPrim = true;
    if( asOverride ) {
        UsdPrim existing = stage->GetPrimAtPath( path );
        if( existing ) {
            // Note that we are creating a Xformable rather than a Xform. 
            // If we are writing an overlay and the ROP sees a geometry packed prim,
            // we want to write just the xform. In that case we can use a xform
            // wrapper to write the xform on any prim type.
            m_usdXformForWrite = UsdGeomXformable(stage->OverridePrim( path ));
            newPrim = false;
        }
        else {
            m_usdXformForWrite = UsdGeomXform::Define( stage, path );

            // Make sure our ancestors have proper types.
            UsdPrim p = m_usdXformForWrite.GetPrim().GetParent();
            while( p && p.GetTypeName().IsEmpty() ) {
                UsdGeomXform::Define( stage, p.GetPath() );
                p = p.GetParent();
            } 
        }
    }
    else {
        m_usdXformForWrite = UsdGeomXform::Define( stage, path );
    }
    if( !m_usdXformForWrite || !m_usdXformForWrite.GetPrim().IsValid() ) {
        TF_WARN( "Unable to create %s xform '%s'.", newPrim ? "new" : "override", path.GetText() );
    }
    return bool(m_usdXformForWrite);
}
void
UsdRiStatementsAPI::SetScopedCoordinateSystem(const std::string &coordSysName)
{
    UsdAttribute attr = GetPrim().CreateAttribute(_tokens->scopedCoordsys, 
                                                  SdfValueTypeNames->String,
                                                  /* custom = */ false);
    if (TF_VERIFY(attr)) {
        attr.Set(coordSysName);

        UsdPrim currPrim = GetPrim();
        while (currPrim) {
            if (currPrim.IsModel() && !currPrim.IsGroup() &&
                currPrim.GetPath() != SdfPath::AbsoluteRootPath()) {
                UsdRelationship rel =
                    currPrim.CreateRelationship(_tokens->modelScopedCoordsys,
                                                /* custom = */ false);
                if (TF_VERIFY(rel)) {
                    rel.AddTarget(GetPrim().GetPath());
                }
                break;
            }

            currPrim = currPrim.GetParent();
        }
    }
}
Example #9
0
File: mesh.cpp Project: mplanck/USD
// For now, this is only used by the mesh op.  If this logic needs to be
// accessed elsewhere, it should move down into usdKatana.
static void 
_CreateFaceSetsFromFaceSetAPI(
        const UsdPrim& prim,
        const PxrUsdKatanaUsdInPrivateData &data,
        FnKat::GeolibCookInterface& interface)
{
    UsdGeomFaceSetAPI faceSet = UsdShadeMaterial::GetMaterialFaceSet(prim);
    bool isPartition = faceSet.GetIsPartition();;
    if (!isPartition) {
        TF_WARN("Found face set on prim <%s> that is not a partition.", 
                prim.GetPath().GetText());
        // continue here?
    }

    const double currentTime = data.GetCurrentTime();

    VtIntArray faceCounts, faceIndices;
    faceSet.GetFaceCounts(&faceCounts, currentTime);
    faceSet.GetFaceIndices(&faceIndices, currentTime);

    SdfPathVector bindingTargets;
    faceSet.GetBindingTargets(&bindingTargets);

    size_t faceSetIdxStart = 0;
    for(size_t faceSetIdx = 0; faceSetIdx < faceCounts.size(); ++faceSetIdx) {
        size_t faceCount = faceCounts[faceSetIdx];

        FnKat::GroupBuilder faceSetAttrs;

        faceSetAttrs.set("type", FnKat::StringAttribute("faceset"));
        faceSetAttrs.set("materialAssign", FnKat::StringAttribute(
            PxrUsdKatanaUtils::ConvertUsdMaterialPathToKatLocation(
                bindingTargets[faceSetIdx], data)));

        FnKat::IntBuilder facesBuilder;
        {
            std::vector<int> faceIndicesVec(faceCount);
            for (size_t faceIndicesIdx = 0; faceIndicesIdx < faceCount; ++faceIndicesIdx)
            {
                faceIndicesVec[faceIndicesIdx] = 
                    faceIndices[faceSetIdxStart + faceIndicesIdx];
            }
            faceSetIdxStart += faceCount;
            facesBuilder.set(faceIndicesVec);
        }
        faceSetAttrs.set("geometry.faces", facesBuilder.build());

        std::string faceSetName = TfStringPrintf("faceset_%zu", faceSetIdx);

        FnKat::GroupBuilder staticSceneCreateAttrs;
        staticSceneCreateAttrs.set("a", faceSetAttrs.build());
        interface.createChild(
            faceSetName,
            "StaticSceneCreate",
            staticSceneCreateAttrs.build());
    }
}
Example #10
0
MObject
PxrUsdMayaShadingModeImportContext::AddCreatedObject(
        const UsdPrim& prim,
        const MObject& obj)
{
    if (prim) {
        return AddCreatedObject(prim.GetPath(), obj);
    }

    return obj;
}
Example #11
0
PXR_NAMESPACE_OPEN_SCOPE


// TODO: We should centralize this logic in a UsdImaging ShaderAdapter.

/*static*/
UsdPrim
UsdImaging_MaterialStrategy::GetTargetedShader(UsdPrim const& materialPrim,
                                        UsdRelationship const& materialRel)
{
    SdfPathVector targets;
    if (!materialRel.GetForwardedTargets(&targets))
        return UsdPrim();

    if (targets.size() != 1) {
        // XXX: This should really be a validation error once USD gets that
        // feature.
        TF_WARN("We expect only one target on relationship %s of prim <%s>, "
                "but got %zu.",
                materialRel.GetName().GetText(),
                materialPrim.GetPath().GetText(),
                targets.size());
        return UsdPrim();
    }

    if (!targets[0].IsPrimPath()) {
        // XXX: This should really be a validation error once USD gets that
        // feature.
        TF_WARN("We expect the target of the relationship %s of prim <%s> "
                "to be a prim, instead it is <%s>.",
                materialRel.GetName().GetText(),
                materialPrim.GetPath().GetText(),
                targets[0].GetText());
        return UsdPrim();
    }

    return materialPrim.GetStage()->GetPrimAtPath(targets[0]);
}
Example #12
0
SdfPath
UsdImagingCapsuleAdapter::Populate(UsdPrim const& prim, 
                            UsdImagingIndexProxy* index,
                            UsdImagingInstancerContext const* instancerContext)

{
    index->InsertRprim(HdPrimTypeTokens->mesh,
                       prim,
                       GetShaderBinding(prim),
                       instancerContext);
    HD_PERF_COUNTER_INCR(UsdImagingTokens->usdPopulatedPrimCount);

    return prim.GetPath();
}
Example #13
0
bool
PxrUsdMayaShadingModeImportContext::GetCreatedObject(
        const UsdPrim& prim,
        MObject* obj) const
{
    if (not prim) {
        return false;
    }

    MObject node = _context->GetMayaNode(prim.GetPath(), false);
    if (not node.isNull()) {
        *obj = node;
        return true;
    }
    return false;
}
void 
UsdImagingMaterialAdapter::_GetMaterialNetworkMap(UsdPrim const &usdPrim, 
    HdMaterialNetworkMap *materialNetworkMap) const
{
    UsdShadeMaterial material(usdPrim);
    if (!material) {
        TF_RUNTIME_ERROR("Expected material prim at <%s> to be of type "
                         "'UsdShadeMaterial', not type '%s'; ignoring",
                         usdPrim.GetPath().GetText(),
                         usdPrim.GetTypeName().GetText());
        return;
    }
    const TfToken context = _GetMaterialNetworkSelector();
    if (UsdShadeShader s = material.ComputeSurfaceSource(context)) {
        _WalkGraph(s, &materialNetworkMap->map[UsdImagingTokens->bxdf],
                  _GetShaderSourceTypes());
    }
    if (UsdShadeShader d = material.ComputeDisplacementSource(context)) {
        _WalkGraph(d, &materialNetworkMap->map[UsdImagingTokens->displacement],
                  _GetShaderSourceTypes());
    }
}
Example #15
0
UT_IntrusivePtr<UT_CappedItem> 
CreateEntryFn::operator()( 
    const UsdPrim &prim, 
    UsdTimeCode time, 
    GusdPurposeSet purposes,
    bool skipRoot ) const 
{ 

    // Build a cache entry for a USD Prim. A cache entry contains a GT_Primitive
    // that can be used to draw the usd prim. 
    //
    // Handle 3 different cases differently. 
    //
    // USD gprims (leaves in the hierarchy) are just converted to GT_Primitives. 
    //
    // For USD native instances, find the instance's master or the prim in
    // master corresponding to an instance proxy, and recurse on that. This way
    // each instance should share a cache with its master.
    //
    // Any other USD primitive represents a branch of the USD hierarchy. Find 
    // all the instances and leaves in this branch and build a GT_PrimCollect 
    // that represent the branch.
    //
    // The viewport doesn't seem to like nested collections very much. So we 
    // use a refiner to flatten the collections.
    
    Refiner refiner;

    // Tell the wrapper classes that we are refining for the viewport. In this case we just load the geometry and color. No
    // other primvars. Also load curves as polylines.
    GT_RefineParms refineParms;
    refineParms.setPackedViewportLOD( true );

    bool isInstance = prim.IsInstance();
    bool isInstanceProxy = prim.IsInstanceProxy();
    if( isInstance || isInstanceProxy)
    {
        DBG( cerr << "Create prim cache for instance " << prim.GetPath() << " at " << time << endl; )
Example #16
0
/* static */
bool
PxrUsdMayaTranslatorUtil::CreateNode(
        const UsdPrim& usdPrim,
        const MString& nodeTypeName,
        MObject& parentNode,
        PxrUsdMayaPrimReaderContext* context,
        MStatus* status,
        MObject* mayaNodeObj)
{
    if (not CreateNode(MString(usdPrim.GetName().GetText()),
                       nodeTypeName,
                       parentNode,
                       status,
                       mayaNodeObj)) {
        return false;
    }

    if (context) {
        context->RegisterNewMayaNode(usdPrim.GetPath().GetString(), *mayaNodeObj);
    }

    return true;
}
bool
GusdGU_PackedUSD::unpackGeometry(
    GU_Detail &destgdp,
    const char* primvarPattern
#if SYS_VERSION_FULL_INT >= 0x11000000
    , const UT_Matrix4D *transform
#endif
) const
{
    UsdPrim usdPrim = getUsdPrim();

    if( !usdPrim )
    {
        TF_WARN( "Invalid prim found" );
        return false;
    }

#if SYS_VERSION_FULL_INT < 0x11000000
    UT_Matrix4D xform(1);
    const GU_PrimPacked *prim = getPrim();
    if( prim ) {
        prim->getFullTransform4(xform);
    }
#endif

    GT_RefineParms      rparms;
    // Need to manually force polysoup to be turned off.
    rparms.setAllowPolySoup( false );

    if (primvarPattern) {
        rparms.set("usd:primvarPattern", primvarPattern);
    }

    GT_PrimitiveHandle gtPrim;

    DBG( cerr << "GusdGU_PackedUSD::unpackGeometry: " << usdPrim.GetTypeName() << ", " << usdPrim.GetPath() << endl; )
Example #18
0
TfToken usdWriteJob::writeVariants(const UsdPrim &usdRootPrim)
{
    // Init parameters for filtering and setting the active variant
    std::string defaultModelingVariant;

    // Get the usdVariantRootPrimPath (optionally filter by renderLayer prefix)
    MayaPrimWriterPtr firstPrimWriterPtr = *mMayaPrimWriterList.begin();
    std::string firstPrimWriterPathStr( firstPrimWriterPtr->getDagPath().fullPathName().asChar() );
    std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), '|', '/');
    std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), ':', '_'); // replace namespace ":" with "_"
    SdfPath usdVariantRootPrimPath(firstPrimWriterPathStr);
    usdVariantRootPrimPath = usdVariantRootPrimPath.GetPrefixes()[0];

    // Create a new usdVariantRootPrim and reference the Base Model UsdRootPrim
    //   This is done for reasons as described above under mArgs.usdModelRootOverridePath
    UsdPrim usdVariantRootPrim = mStage->DefinePrim(usdVariantRootPrimPath);
    TfToken defaultPrim = usdVariantRootPrim.GetName();
    usdVariantRootPrim.GetReferences().AppendInternalReference(usdRootPrim.GetPath());
    usdVariantRootPrim.SetActive(true);
    usdRootPrim.SetActive(false);

    // Loop over all the renderLayers
    for (unsigned int ir=0; ir < mRenderLayerObjs.length(); ++ir) {
        SdfPathTable<bool> tableOfActivePaths;
        MFnRenderLayer renderLayerFn( mRenderLayerObjs[ir] );
        MString renderLayerName = renderLayerFn.name();
        std::string variantName(renderLayerName.asChar());
        // Determine default variant. Currently unsupported
        //MPlug renderLayerDisplayOrderPlug = renderLayerFn.findPlug("displayOrder", true);
        //int renderLayerDisplayOrder = renderLayerDisplayOrderPlug.asShort();
                    
        // The Maya default RenderLayer is also the default modeling variant
        if (mRenderLayerObjs[ir] == MFnRenderLayer::defaultRenderLayer()) {
            defaultModelingVariant=variantName;
        }
        
        // Make the renderlayer being looped the current one
        MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+
                                        renderLayerName, false, false);

        // == ModelingVariants ==
        // Identify prims to activate
        // Put prims and parent prims in a SdfPathTable
        // Then use that membership to determine if a prim should be Active.
        // It has to be done this way since SetActive(false) disables access to all child prims.
        MObjectArray renderLayerMemberObjs;
        renderLayerFn.listMembers(renderLayerMemberObjs);
        std::vector< SdfPath > activePaths;
        for (unsigned int im=0; im < renderLayerMemberObjs.length(); ++im) {
            MFnDagNode dagFn(renderLayerMemberObjs[im]);
            MDagPath dagPath;
            dagFn.getPath(dagPath);
            dagPath.extendToShape();
            SdfPath usdPrimPath; 
            if (!TfMapLookup(mDagPathToUsdPathMap, dagPath, &usdPrimPath)) {
                continue;
            }
            usdPrimPath = usdPrimPath.ReplacePrefix(usdPrimPath.GetPrefixes()[0], usdVariantRootPrimPath); // Convert base to variant usdPrimPath
            tableOfActivePaths[usdPrimPath] = true;
            activePaths.push_back(usdPrimPath);
            //UsdPrim usdPrim = mStage->GetPrimAtPath(usdPrimPath);
            //usdPrim.SetActive(true);
        }
        if (!tableOfActivePaths.empty()) {
            { // == BEG: Scope for Variant EditContext
                // Create the variantSet and variant
                UsdVariantSet modelingVariantSet = usdVariantRootPrim.GetVariantSets().AppendVariantSet("modelingVariant");
                modelingVariantSet.AppendVariant(variantName);
                modelingVariantSet.SetVariantSelection(variantName);
                // Set the Edit Context
                UsdEditTarget editTarget = modelingVariantSet.GetVariantEditTarget();
                UsdEditContext editContext(mStage, editTarget);

                // == Activate/Deactivate UsdPrims
                UsdPrimRange it = UsdPrimRange::AllPrims(mStage->GetPseudoRoot());
                std::vector<UsdPrim> primsToDeactivate;
                for ( ; it; ++it) {
                    UsdPrim usdPrim = *it;
                    // For all xformable usdPrims...
                    if (usdPrim && usdPrim.IsA<UsdGeomXformable>()) {
                        bool isActive=false;
                        for (size_t j=0;j<activePaths.size();j++) {
                            //primPathD.HasPrefix(primPathA);
                            SdfPath activePath=activePaths[j];
                            if (usdPrim.GetPath().HasPrefix(activePath) || activePath.HasPrefix(usdPrim.GetPath())) {
                                isActive=true; break;
                            }
                        }
                        if (isActive==false) {
                            primsToDeactivate.push_back(usdPrim);
                            it.PruneChildren();
                        }
                    }
                }
                // Now deactivate the prims (done outside of the UsdPrimRange 
                // so not to modify the iterator while in the loop)
                for ( UsdPrim const& prim : primsToDeactivate ) {
                    prim.SetActive(false);
                }
            } // == END: Scope for Variant EditContext
        }
    } // END: RenderLayer iterations

    // Set the default modeling variant
    UsdVariantSet modelingVariantSet = usdVariantRootPrim.GetVariantSet("modelingVariant");
    if (modelingVariantSet.IsValid()) {
        modelingVariantSet.SetVariantSelection(defaultModelingVariant);
    }
    return defaultPrim;
}
Example #19
0
// This method inspects the JSON blob stored in the 'USD_UserExportedAttributesJson'
// attribute on the Maya node at dagPath and exports any attributes specified
// there onto usdPrim at time usdTime. The JSON should contain an object that
// maps Maya attribute names to other JSON objects that contain metadata about
// how to export the attribute into USD. For example:
//
//    {
//        "myMayaAttributeOne": {
//        },
//        "myMayaAttributeTwo": {
//            "usdAttrName": "my:namespace:attributeTwo"
//        },
//        "attributeAsPrimvar": {
//            "usdAttrType": "primvar"
//        },
//        "attributeAsVertexInterpPrimvar": {
//            "usdAttrType": "primvar",
//            "interpolation": "vertex"
//        },
//        "attributeAsRibAttribute": {
//            "usdAttrType": "usdRi"
//        },
//        "doubleAttributeAsFloatAttribute": {
//            "translateMayaDoubleToUsdSinglePrecision": true
//        }
//    }
//
// If the attribute metadata contains a value for "usdAttrName", the attribute
// will be given that name in USD. Otherwise, the Maya attribute name will be
// used for primvars and UsdRi attributes, or the Maya attribute name prepended
// with the "userProperties" namespace will be used for regular USD attributes.
// Maya attributes in the JSON will be processed in sorted order, and any
// USD attribute name collisions will be resolved by using the first attribute
// visited and warning about subsequent attribute tags.
//
bool
PxrUsdMayaWriteUtil::WriteUserExportedAttributes(
        const MDagPath& dagPath,
        const UsdPrim& usdPrim,
        const UsdTimeCode& usdTime)
{
    std::vector<PxrUsdMayaUserTaggedAttribute> exportedAttributes =
        PxrUsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode(dagPath);
    for (const PxrUsdMayaUserTaggedAttribute& attr : exportedAttributes) {
        const std::string& usdAttrName = attr.GetUsdName();
        const TfToken& usdAttrType = attr.GetUsdType();
        const TfToken& interpolation = attr.GetUsdInterpolation();
        const bool translateMayaDoubleToUsdSinglePrecision =
            attr.GetTranslateMayaDoubleToUsdSinglePrecision();
        const MPlug& attrPlug = attr.GetMayaPlug();
        UsdAttribute usdAttr;

        if (usdAttrType ==
                    PxrUsdMayaUserTaggedAttributeTokens->USDAttrTypePrimvar) {
            UsdGeomImageable imageable(usdPrim);
            if (!imageable) {
                MGlobal::displayError(
                    TfStringPrintf(
                        "Cannot create primvar for non-UsdGeomImageable USD prim: '%s'",
                        usdPrim.GetPath().GetText()).c_str());
                continue;
            }
            UsdGeomPrimvar primvar =
                PxrUsdMayaWriteUtil::GetOrCreatePrimvar(attrPlug,
                                                        imageable,
                                                        usdAttrName,
                                                        interpolation,
                                                        -1,
                                                        true,
                                                        translateMayaDoubleToUsdSinglePrecision);
            if (primvar) {
                usdAttr = primvar.GetAttr();
            }
        } else if (usdAttrType ==
                    PxrUsdMayaUserTaggedAttributeTokens->USDAttrTypeUsdRi) {
            usdAttr =
                PxrUsdMayaWriteUtil::GetOrCreateUsdRiAttribute(attrPlug,
                                                               usdPrim,
                                                               usdAttrName,
                                                               "user",
                                                               translateMayaDoubleToUsdSinglePrecision);
        } else {
            usdAttr = PxrUsdMayaWriteUtil::GetOrCreateUsdAttr(attrPlug,
                                                              usdPrim,
                                                              usdAttrName,
                                                              true,
                                                              translateMayaDoubleToUsdSinglePrecision);
        }

        if (usdAttr) {
            if (!PxrUsdMayaWriteUtil::SetUsdAttr(attrPlug,
                                                    usdAttr,
                                                    usdTime,
                                                    translateMayaDoubleToUsdSinglePrecision)) {
                MGlobal::displayError(
                    TfStringPrintf("Could not set value for attribute: '%s'",
                                   usdAttr.GetPath().GetText()).c_str());
                continue;
            }
        } else {
            MGlobal::displayError(
                TfStringPrintf("Could not create attribute '%s' for USD prim: '%s'",
                               usdAttrName.c_str(),
                               usdPrim.GetPath().GetText()).c_str());
                continue;
        }
    }

    return true;
}
Example #20
0
void
PxrUsdKatanaReadLightFilter(
        const UsdLuxLightFilter& lightFilter,
        const PxrUsdKatanaUsdInPrivateData& data,
        PxrUsdKatanaAttrMap& attrs)
{
    const UsdPrim filterPrim = lightFilter.GetPrim();
    const SdfPath primPath = filterPrim.GetPath();
    const double currentTime = data.GetCurrentTime();

    GroupBuilder materialBuilder;
    GroupBuilder filterBuilder;
    _UsdBuilder usdBuilder = {filterBuilder, currentTime};
    
    if (UsdRiLightFilterAPI f = UsdRiLightFilterAPI(filterPrim)) {
        usdBuilder
            .Set("density", f.GetRiDensityAttr())
            .Set("intensity", f.GetRiIntensityAttr())
            .Set("exposure", f.GetRiExposureAttr())
            .Set("invert", f.GetRiInvertAttr())
            .Set("diffuse", f.GetRiDiffuseAttr())
            .Set("specular", f.GetRiSpecularAttr())
            ;

        // combineMode
        {
            VtValue val;
            UsdAttribute attr = f.GetRiCombineModeAttr();
            if (attr.IsValid() && attr.HasAuthoredValueOpinion()
                && attr.Get(&val, currentTime) && val.IsHolding<TfToken>()) {
                TfToken t = val.Get<TfToken>();
                if (t == UsdRiTokens->multiply) {
                    filterBuilder.set("combineMode",
                                      FnKat::StringAttribute("mult"));
                } else if (t == UsdRiTokens->max) {
                    filterBuilder.set("combineMode",
                                      FnKat::StringAttribute("max"));
                } else if (t == UsdRiTokens->min) {
                    filterBuilder.set("combineMode",
                                      FnKat::StringAttribute("min"));
                } else if (t == UsdRiTokens->screen) {
                    filterBuilder.set("combineMode",
                                      FnKat::StringAttribute("screen"));
                }
            }
        }
    }
    if (UsdRiPxrIntMultLightFilter f = UsdRiPxrIntMultLightFilter(filterPrim)) {
        materialBuilder.set("prmanLightfilterShader",
                            FnKat::StringAttribute("PxrIntMultLightFilter"));
    }
    if (UsdRiPxrBarnLightFilter f = UsdRiPxrBarnLightFilter(filterPrim)) {
        materialBuilder.set("prmanLightfilterShader",
                            FnKat::StringAttribute("PxrBarnLightFilter"));
        usdBuilder
            .Set("directional", f.GetAnalyticDirectionalAttr())
            .Set("shearX", f.GetAnalyticShearXAttr())
            .Set("shearY", f.GetAnalyticShearYAttr())
            .Set("apex", f.GetAnalyticApexAttr())
            .Set("useLightDirection", f.GetAnalyticDirectionalAttr())
            .Set("width", f.GetWidthAttr())
            .Set("height", f.GetHeightAttr())
            .Set("radius", f.GetRadiusAttr())
            .Set("edge", f.GetEdgeThicknessAttr())
            .Set("scaleWidth", f.GetScaleWidthAttr())
            .Set("scaleHeight", f.GetScaleHeightAttr())
            .Set("left", f.GetRefineLeftAttr())
            .Set("right", f.GetRefineRightAttr())
            .Set("top", f.GetRefineTopAttr())
            .Set("bottom", f.GetRefineBottomAttr())
            .Set("leftEdge", f.GetEdgeLeftAttr())
            .Set("rightEdge", f.GetEdgeRightAttr())
            .Set("topEdge", f.GetEdgeTopAttr())
            .Set("bottomEdge", f.GetEdgeBottomAttr())
            .Set("densityNear", f.GetAnalyticDensityNearDistanceAttr())
            .Set("densityNearVal", f.GetAnalyticDensityNearValueAttr())
            .Set("densityFar", f.GetAnalyticDensityFarDistanceAttr())
            .Set("densityFarVal", f.GetAnalyticDensityFarValueAttr())
            .Set("densityPow", f.GetAnalyticDensityExponentAttr())
            ;

        // barnMode 
        {
            VtValue val;
            UsdAttribute attr = f.GetBarnModeAttr();
            if (attr.IsValid() && attr.HasAuthoredValueOpinion()
                && attr.Get(&val, currentTime) && val.IsHolding<TfToken>()) {
                TfToken t = val.Get<TfToken>();
                if (t == UsdRiTokens->analytic) {
                    filterBuilder.set("barnMode", FnKat::IntAttribute(1));
                } else if (t == UsdRiTokens->physical) {
                    filterBuilder.set("barnMode", FnKat::IntAttribute(0));
                }
            }
        }
        // preBarn
        {
            VtValue val;
            UsdAttribute attr = f.GetPreBarnEffectAttr();
            if (attr.IsValid() && attr.HasAuthoredValueOpinion()
                && attr.Get(&val, currentTime) && val.IsHolding<TfToken>()) {
                TfToken t = val.Get<TfToken>();
                if (t == UsdRiTokens->noEffect) {
                    filterBuilder.set("preBarn", FnKat::IntAttribute(0));
                } else if (t == UsdRiTokens->cone) {
                    filterBuilder.set("preBarn", FnKat::IntAttribute(1));
                } else if (t == UsdRiTokens->noLight) {
                    filterBuilder.set("preBarn", FnKat::IntAttribute(2));
                }
            }
        }
    }
    if (UsdRiPxrCookieLightFilter f = UsdRiPxrCookieLightFilter(filterPrim)) {
        materialBuilder.set("prmanLightfilterShader",
                            FnKat::StringAttribute("PxrCookieLightFilter"));
        // cookieMode 
        {
            VtValue val;
            UsdAttribute attr = f.GetCookieModeAttr();
            if (attr.IsValid() && attr.HasAuthoredValueOpinion()
                && attr.Get(&val, currentTime) && val.IsHolding<TfToken>()) {
                TfToken t = val.Get<TfToken>();
                if (t == UsdRiTokens->analytic) {
                    filterBuilder.set("cookieMode", FnKat::IntAttribute(1));
                } else if (t == UsdRiTokens->physical) {
                    filterBuilder.set("cookieMode", FnKat::IntAttribute(0));
                }
            }
        }
        // tileMode
        {
            VtValue val;
            UsdAttribute attr = f.GetTextureWrapModeAttr();
            if (attr.IsValid() && attr.HasAuthoredValueOpinion()
                && attr.Get(&val, currentTime) && val.IsHolding<TfToken>()) {
                TfToken t = val.Get<TfToken>();
                if (t == UsdRiTokens->off) {
                    filterBuilder.set("tileMode", FnKat::IntAttribute(0));
                } else if (t == UsdRiTokens->repeat) {
                    filterBuilder.set("tileMode", FnKat::IntAttribute(2));
                } else if (t == UsdRiTokens->clamp) {
                    filterBuilder.set("tileMode", FnKat::IntAttribute(1));
                }
            }
        }
        usdBuilder
            .Set("map", f.GetTextureMapAttr())
            .Set("fillColor", f.GetTextureFillColorAttr())
            .Set("width", f.GetWidthAttr())
            .Set("height", f.GetHeightAttr())
            .Set("directional", f.GetAnalyticDirectionalAttr())
            .Set("shearX", f.GetAnalyticShearXAttr())
            .Set("shearY", f.GetAnalyticShearYAttr())
            .Set("apex", f.GetAnalyticApexAttr())
            .Set("useLightDirection", f.GetAnalyticDirectionalAttr())
            .Set("invertU", f.GetTextureInvertUAttr())
            .Set("invertV", f.GetTextureInvertVAttr())
            .Set("scaleU", f.GetTextureScaleUAttr())
            .Set("scaleV", f.GetTextureScaleVAttr())
            .Set("offsetU", f.GetTextureOffsetUAttr())
            .Set("offsetV", f.GetTextureOffsetVAttr())
            .Set("blur", f.GetAnalyticBlurAmountAttr())
            .Set("sBlurMult", f.GetAnalyticBlurSMultAttr())
            .Set("tBlurMult", f.GetAnalyticBlurTMultAttr())
            .Set("blurNearDist", f.GetAnalyticBlurNearDistanceAttr())
            .Set("blurNearVal", f.GetAnalyticBlurNearValueAttr())
            .Set("blurFarDist", f.GetAnalyticBlurFarDistanceAttr())
            .Set("blurFarVal", f.GetAnalyticBlurFarValueAttr())
            .Set("blurMidpoint", f.GetAnalyticBlurMidpointAttr())
            .Set("blurMidVal", f.GetAnalyticBlurMidValueAttr())
            .Set("blurPow", f.GetAnalyticBlurExponentAttr())
            .Set("densityNearDist", f.GetAnalyticDensityNearDistanceAttr())
            .Set("densityNearVal", f.GetAnalyticDensityNearValueAttr())
            .Set("densityFarDist", f.GetAnalyticDensityFarDistanceAttr())
            .Set("densityFarVal", f.GetAnalyticDensityFarValueAttr())
            .Set("densityMidpoint", f.GetAnalyticDensityMidpointAttr())
            .Set("densityMidVal", f.GetAnalyticDensityMidValueAttr())
            .Set("densityPow", f.GetAnalyticDensityExponentAttr())
            .Set("saturation", f.GetColorSaturationAttr())
            .Set("midpoint", f.GetColorMidpointAttr())
            .Set("contrast", f.GetColorContrastAttr())
            .Set("whitepoint", f.GetColorWhitepointAttr())
            .Set("tint", f.GetColorTintAttr())
            ;
    }
    if (UsdRiPxrRampLightFilter f = UsdRiPxrRampLightFilter(filterPrim)) {
        materialBuilder.set("prmanLightfilterShader",
                            FnKat::StringAttribute("PxrRampLightFilter"));
        usdBuilder
            .Set("beginDist", f.GetFalloffRampBeginDistanceAttr())
            .Set("endDist", f.GetFalloffRampEndDistanceAttr())
            .SetSpline("colorRamp", "_Colors", f.GetColorRampAPI())
            .SetSpline("ramp", "_Floats", f.GetFalloffRampAPI())
            ;
        // rampMode
        {
            VtValue val;
            UsdAttribute attr = f.GetRampModeAttr();
            if (attr.IsValid() && attr.HasAuthoredValueOpinion()
                && attr.Get(&val, currentTime) && val.IsHolding<TfToken>()) {
                TfToken t = val.Get<TfToken>();
                if (t == UsdRiTokens->distanceToLight) {
                    filterBuilder.set("rampMode", FnKat::IntAttribute(0));
                } else if (t == UsdRiTokens->linear) {
                    filterBuilder.set("rampMode", FnKat::IntAttribute(1));
                } else if (t == UsdRiTokens->spherical) {
                    filterBuilder.set("rampMode", FnKat::IntAttribute(2));
                } else if (t == UsdRiTokens->radial) {
                    filterBuilder.set("rampMode", FnKat::IntAttribute(3));
                }
            }
        }
    }
    if (UsdRiPxrRodLightFilter f = UsdRiPxrRodLightFilter(filterPrim)) {
        materialBuilder.set("prmanLightfilterShader",
                            FnKat::StringAttribute("PxrRodLightFilter"));
        usdBuilder
            .Set("width", f.GetWidthAttr())
            .Set("height", f.GetHeightAttr())
            .Set("depth", f.GetDepthAttr())
            .Set("radius", f.GetRadiusAttr())
            .Set("edge", f.GetEdgeThicknessAttr())
            .Set("scaleWidth", f.GetScaleWidthAttr())
            .Set("scaleHeight", f.GetScaleHeightAttr())
            .Set("scaleDepth", f.GetScaleDepthAttr())
            .Set("left", f.GetRefineLeftAttr())
            .Set("right", f.GetRefineRightAttr())
            .Set("top", f.GetRefineTopAttr())
            .Set("bottom", f.GetRefineBottomAttr())
            .Set("front", f.GetRefineFrontAttr())
            .Set("back", f.GetRefineBackAttr())
            .Set("leftEdge", f.GetEdgeLeftAttr())
            .Set("rightEdge", f.GetEdgeRightAttr())
            .Set("topEdge", f.GetEdgeTopAttr())
            .Set("bottomEdge", f.GetEdgeBottomAttr())
            .Set("frontEdge", f.GetEdgeFrontAttr())
            .Set("backEdge", f.GetEdgeBackAttr())
            .Set("saturation", f.GetColorSaturationAttr())
            .SetSpline("colorRamp", "_Colors", f.GetColorRampAPI())
            .SetSpline("falloff", "_Floats", f.GetFalloffRampAPI())
            ;
    }

    // Gather prman statements
    FnKat::GroupBuilder prmanBuilder;
    PxrUsdKatanaReadPrimPrmanStatements(filterPrim, currentTime, prmanBuilder);
    attrs.set("prmanStatements", prmanBuilder.build());
    materialBuilder.set("prmanLightfilterParams", filterBuilder.build());
    attrs.set("material", materialBuilder.build());
    PxrUsdKatanaReadXformable(lightFilter, data, attrs);
    attrs.set("type", FnKat::StringAttribute("light filter"));
}
Example #21
0
static
bool 
_SetOrMergeOverOp(std::vector<int64_t> const &items, SdfListOpType op,
                  UsdPrim const &prim)
{
    SdfInt64ListOp  proposed, current;
    UsdStagePtr stage = prim.GetStage();
    UsdEditTarget editTarget = stage->GetEditTarget();
    SdfPrimSpecHandle  primSpec = 
        editTarget.GetPrimSpecForScenePath(prim.GetPath());
    
    if (primSpec){
        VtValue  existingOp = primSpec->GetInfo(UsdGeomTokens->inactiveIds);
        if (existingOp.IsHolding<SdfInt64ListOp>()){
            current = existingOp.UncheckedGet<SdfInt64ListOp>();
        }
    }

    proposed.SetItems(items, op);
    if (current.IsExplicit()){
        std::vector<int64_t> explicitItems = current.GetExplicitItems();
        proposed.ApplyOperations(&explicitItems);
        current.SetExplicitItems(explicitItems);
    }
    else {
        // We can't use ApplyOperations on an extant, non-explicit listOp
        // because the result is always flat and explicit.
        current.ComposeOperations(proposed, op);
        // ComposeOperations() is too narrow in functionality - it does not
        // consider that if we "remove over" an existing set of added items,
        // we need to additionally ensure the removed items get removed
        // from the added in current, since when applying ops, we first
        // remove, then add.  Bug #139215 filed to track; when it gets fixed
        // we can remove this code!
        if (op == SdfListOpTypeDeleted){
            std::vector<int64_t> addedItems = current.GetAddedItems();
            if (!addedItems.empty()){
                std::set<int64_t> toRemove(items.begin(), items.end());
                std::vector<int64_t> newAdded;
                newAdded.reserve(addedItems.size());
                for (auto elt : addedItems){
                    if (!toRemove.count(elt))
                        newAdded.push_back(elt);
                }
                if (newAdded.size() != addedItems.size())
                    current.SetAddedItems(newAdded);
            }
        }
        else if (op == SdfListOpTypeAdded){
            std::vector<int64_t> deletedItems = current.GetDeletedItems();
            if (!deletedItems.empty()){
                std::set<int64_t> toAdd(items.begin(), items.end());
                std::vector<int64_t> newDeleted;
                newDeleted.reserve(deletedItems.size());
                for (auto elt : deletedItems){
                    if (!toAdd.count(elt))
                        newDeleted.push_back(elt);
                }
                if (newDeleted.size() != deletedItems.size())
                    current.SetDeletedItems(newDeleted);
            }
        }
    }
    return prim.SetMetadata(UsdGeomTokens->inactiveIds, current);
}
Example #22
0
static FnKat::Attribute
_GetMaterialAssignAttr(
        const UsdPrim& prim,
        const PxrUsdKatanaUsdInPrivateData& data)
{
    if (not prim or prim.GetPath() == SdfPath::AbsoluteRootPath()) {
        // Special-case to pre-empt coding errors.
        return FnKat::Attribute();
    }

    UsdRelationship usdRel = UsdShadeLook::GetBindingRel(prim);
    if (usdRel) {
        // USD shading binding
        SdfPathVector targetPaths;
        usdRel.GetForwardedTargets(&targetPaths);
        if (targetPaths.size() > 0) {
            if (not targetPaths[0].IsPrimPath()) {
                FnLogWarn("Target path " << prim.GetPath().GetString() <<
                          " is not a prim");
                return FnKat::Attribute();
            }

            // This is a copy as it could be modified below.
            SdfPath targetPath = targetPaths[0];
            UsdPrim targetPrim = data.GetUsdInArgs()->GetStage()->GetPrimAtPath(targetPath);
            // If the target is inside a master, then it needs to be re-targeted 
            // to the instance.
            // 
            // XXX remove this special awareness once GetMasterWithContext is
            //     is available as the provided prim will automatically
            //     retarget (or provide enough context to retarget without
            //     tracking manually).
            if (targetPrim and targetPrim.IsInMaster()) {
                if (not data.GetInstancePath().IsEmpty() and 
                        not data.GetMasterPath().IsEmpty()) {

                    // Check if the source and the target of the relationship 
                    // belong to the same master.
                    // If they do, we have the context necessary to do the 
                    // re-mapping.
                    if (data.GetMasterPath().GetCommonPrefix(targetPath).
                            GetPathElementCount() > 0) {
                        targetPath = data.GetInstancePath().AppendPath(
                            targetPath.ReplacePrefix(targetPath.GetPrefixes()[0],
                                SdfPath::ReflexiveRelativePath()));
                    } else {
                        // Warn saying the target of relationship isn't within 
                        // the same master as the source.
                        FnLogWarn("Target path " << prim.GetPath().GetString() 
                            << " isn't within the master " << data.GetMasterPath());
                        return FnKat::Attribute();
                    }
                } else {
                    // XXX
                    // When loading beneath a master via an isolatePath
                    // opArg, we can encounter targets which are within masters
                    // but not within the context of a material.
                    // While that would be an error according to the below
                    // warning, it produces the expected results.
                    // This case can occur when expanding pointinstancers as
                    // the sources are made via execution of PxrUsdIn again
                    // at the sub-trees.
                    
                    
                    // Warn saying target of relationship is in a master, 
                    // but the associated instance path is unknown!
                    // FnLogWarn("Target path " << prim.GetPath().GetString() 
                    //         << " is within a master, but the associated "
                    //         "instancePath is unknown.");
                    // return FnKat::Attribute();
                }
            }

            // Convert the target path to the equivalent katana location.
            // XXX: Looks may have an atypical USD->Katana 
            // path mapping
            std::string location =
                PxrUsdKatanaUtils::ConvertUsdLookPathToKatLocation(targetPath, data);
                
            // XXX Looks containing only display terminals are causing issues
            //     with katana material manipulation workflows.
            //     For now: exclude any material assign which doesn't include
            //     /Looks/ in the path
            if (location.find(UsdKatanaTokens->katanaLooksScopePathSubstring)
                    == std::string::npos)
            {
                return FnKat::Attribute();
            }
                
                
            // location = TfStringReplace(location, "/Looks/", "/Materials/");
            // XXX handle multiple assignments
            return FnKat::StringAttribute(location);
        }
    }

    return FnKat::Attribute();
}
Example #23
0
PXR_NAMESPACE_OPEN_SCOPE


PxrUsdKatanaUsdInPrivateData::PxrUsdKatanaUsdInPrivateData(
        const UsdPrim& prim,
        PxrUsdKatanaUsdInArgsRefPtr usdInArgs,
        const PxrUsdKatanaUsdInPrivateData* parentData)
    : _prim(prim), _usdInArgs(usdInArgs), _extGb(0)
{
    // XXX: manually track instance and master path for possible
    //      relationship re-retargeting. This approach does not yet
    //      support nested instances -- which is expected to be handled
    //      via the forthcoming GetMasterWithContext.
    //
    if (prim.IsInstance())
    {
        if (prim.IsInMaster() && parentData)
        {
            SdfPath descendentPrimPath = 
                prim.GetPath().ReplacePrefix(
                    prim.GetPath().GetPrefixes()[0], 
                    SdfPath::ReflexiveRelativePath());

            _instancePath = parentData->GetInstancePath().AppendPath(
                descendentPrimPath);
        }
        else
        {
            _instancePath = prim.GetPath();
        }

        const UsdPrim& masterPrim = prim.GetMaster();            
        if (masterPrim)
        {
            _masterPath = masterPrim.GetPath();
        }
    }
    else if (parentData)
    {
        // Pass along instance and master paths to children.
        //
        if (!parentData->GetInstancePath().IsEmpty())
        {
            _instancePath = parentData->GetInstancePath();
        }

        if (!parentData->GetMasterPath().IsEmpty())
        {
            _masterPath = parentData->GetMasterPath();
        }
    }

    //
    // Apply session overrides for motion.
    //

    const std::string primPath = prim.GetPrimPath().GetString();
    const std::string isolatePath = usdInArgs->GetIsolatePath();
    const std::string sessionPath = usdInArgs->GetSessionLocationPath();
    FnKat::GroupAttribute sessionAttr = usdInArgs->GetSessionAttr();

    // XXX: If an isolatePath has been specified, it means the PxrUsdIn is
    // probably loading USD contents below the USD root. This can prevent
    // overrides from trickling down the hierarchy, e.g. the overrides for /A/B
    // won't get applied to children if the isolatePath is /A/B/C/D.
    //
    // So, if the usdInArgs suggest that an isolatePath has been specified and
    // we don't have any parentData, we'll need to check if there are overrides
    // for the prim and any of its parents.
    //
    std::vector<std::string> pathsToCheck;
    if (!parentData and !isolatePath.empty() and
        pystring::startswith(primPath, isolatePath+"/"))
    {
        std::vector<std::string> parentLocs;
        Foundry::Katana::Util::Path::GetLocationStack(parentLocs, primPath);
        std::reverse(std::begin(parentLocs), std::end(parentLocs));
        for (size_t i = 0; i < parentLocs.size(); ++i)
        {
            pathsToCheck.push_back(FnKat::DelimiterEncode(
                    sessionPath + parentLocs[i]));
        }
    }
    else
    {
        pathsToCheck.push_back(FnKat::DelimiterEncode(sessionPath + primPath));
    }

    //
    // If a session override is specified, use its value. If no override exists,
    // try asking the parent data for its value. Otherwise, fall back on the
    // usdInArgs value.
    //

    bool overrideFound;

    // Current time.
    //
    overrideFound = false;
    for (size_t i = 0; i < pathsToCheck.size(); ++i)
    {
        FnKat::FloatAttribute currentTimeAttr =
            sessionAttr.getChildByName(
                "overrides."+pathsToCheck[i]+".currentTime");
        if (currentTimeAttr.isValid())
        {
            _currentTime = currentTimeAttr.getValue();
            overrideFound = true;
            break;
        }
    }
    if (!overrideFound)
    {
        if (parentData)
        {
            _currentTime = parentData->GetCurrentTime();
        }
        else
        {
            _currentTime = usdInArgs->GetCurrentTime();
        }
    }

    // Shutter open.
    //
    overrideFound = false;
    for (size_t i = 0; i < pathsToCheck.size(); ++i)
    {
        FnKat::FloatAttribute shutterOpenAttr =
                sessionAttr.getChildByName(
                    "overrides."+pathsToCheck[i]+".shutterOpen");
        if (shutterOpenAttr.isValid())
        {
            _shutterOpen = shutterOpenAttr.getValue();
            overrideFound = true;
            break;
        }
    }
    if (!overrideFound)
    {
        if (parentData)
        {
            _shutterOpen = parentData->GetShutterOpen();
        }
        else
        {
            _shutterOpen = usdInArgs->GetShutterOpen();
        }
    }

    // Shutter close.
    //
    overrideFound = false;
    for (size_t i = 0; i < pathsToCheck.size(); ++i)
    {
        FnKat::FloatAttribute shutterCloseAttr =
                sessionAttr.getChildByName(
                    "overrides."+pathsToCheck[i]+".shutterClose");
        if (shutterCloseAttr.isValid())
        {
            _shutterClose = shutterCloseAttr.getValue();
            overrideFound = true;
            break;
        }
    }
    if (!overrideFound)
    {
        if (parentData)
        {
            _shutterClose = parentData->GetShutterClose();
        }
        else
        {
            _shutterClose = usdInArgs->GetShutterClose();
        }
    }

    // Motion sample times.
    //
    // Fallback logic is a little more complicated for motion sample times, as
    // they can vary per attribute, so store both the overridden and the
    // fallback motion sample times for use inside GetMotionSampleTimes.
    //
    for (size_t i = 0; i < pathsToCheck.size(); ++i)
    {
        FnKat::Attribute motionSampleTimesAttr =
                sessionAttr.getChildByName(
                    "overrides."+pathsToCheck[i]+".motionSampleTimes");
        if (motionSampleTimesAttr.isValid())
        {
            // Interpret an IntAttribute as "use usdInArgs defaults"
            //
            if (motionSampleTimesAttr.getType() == kFnKatAttributeTypeInt)
            {
                _motionSampleTimesOverride = usdInArgs->GetMotionSampleTimes();
                break;
            }
            // Interpret a FloatAttribute as an explicit value override
            //
            if (motionSampleTimesAttr.getType() == kFnKatAttributeTypeFloat)
            {
                const auto& sampleTimes = FnKat::FloatAttribute(
                        motionSampleTimesAttr).getNearestSample(0);
                if (!sampleTimes.empty())
                {
                    for (float sampleTime : sampleTimes)
                        _motionSampleTimesOverride.push_back(
                            (double)sampleTime);
                    break;
                }
            }
        }
    }
    if (parentData)
    {
        _motionSampleTimesFallback = parentData->GetMotionSampleTimes();
    }
    else
    {
        _motionSampleTimesFallback = usdInArgs->GetMotionSampleTimes();
    }
}
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;
}
Example #25
0
void
UsdSkel_CacheImpl::ReadScope::_RecursivePopulate(const UsdPrim& prim,
                                                 SkinningQueryKey key,
                                                 UsdSkelAnimQuery animQuery,
                                                 size_t depth)
{
    if(!prim.IsA<UsdGeomImageable>()) {
        TF_DEBUG(USDSKEL_CACHE).Msg(
            "[UsdSkelCache]: %sPruning traversal at <%s> "
            "(prim types is not a UsdGeomImageable)\n",
            _MakeIndent(depth).c_str(), prim.GetPath().GetText());
        return;
    }
        
    TF_DEBUG(USDSKEL_CACHE).Msg("[UsdSkelCache]: %sVisiting <%s>\n",
                                _MakeIndent(depth).c_str(), 
                                prim.GetPath().GetText());

    UsdSkelBindingAPI binding(prim);

    if(UsdRelationship rel = binding.GetAnimationSourceRel()) {
        SdfPathVector targets;
        if(rel.GetForwardedTargets(&targets)) {
            animQuery = FindOrCreateAnimQuery(_GetFirstTarget(rel, targets));
        }
    }

    if(UsdRelationship rel = binding.GetSkeletonRel()) {
        SdfPathVector targets;
        if(rel.GetForwardedTargets(&targets)) {
            _PrimToSkelQueryMap::accessor a;
            if(_cache->_skelQueryCache.insert(a, prim)) {
                a->second = _FindOrCreateSkelQuery(
                    _GetFirstTarget(rel, targets), animQuery);
            }
            key.skelQuery = a->second;

            TF_DEBUG(USDSKEL_CACHE).Msg(
                "[UsdSkelCache]: %sNew skeleton bound at <%s>: %s\n",
                _MakeIndent(depth).c_str(), prim.GetPath().GetText(),
                key.skelQuery.GetDescription().c_str());
        }
    }

    if(UsdAttribute attr = binding.GetJointIndicesAttr())
        key.jointIndicesAttr = attr;

    if(UsdAttribute attr = binding.GetJointWeightsAttr())
        key.jointWeightsAttr = attr;

    if(UsdAttribute attr = binding.GetGeomBindTransformAttr())
        key.geomBindTransformAttr = attr;

    if(UsdAttribute attr = binding.GetJointsAttr()) {
        VtTokenArray jointOrder;
        if(attr.Get(&jointOrder)) {
            key.jointOrder = jointOrder;
        }
    }

    if(prim.IsA<UsdGeomBoundable>() &&
       (key.jointIndicesAttr && key.jointWeightsAttr)) {

        _PrimToSkinningQueryMap::accessor a;
        if(_cache->_primSkinningQueryCache.insert(a, prim)) {
            a->second = _FindOrCreateSkinningQuery(prim, key);
        }

        TF_DEBUG(USDSKEL_CACHE).Msg(
            "[UsdSkelCache]: %sFound skinnable prim <%s> (valid? %d)\n",
            _MakeIndent(depth).c_str(), prim.GetPath().GetText(),
            a->second.IsValid());

        // Skinnable prims cannot be nested.
        return;
    }

    UsdPrim traversalPrim = !prim.IsInstance() ? prim : prim.GetMaster();
    for(const auto& child : prim.GetChildren()) {
        _RecursivePopulate(child, key, animQuery, depth+1);
    }
}
Example #26
0
bool
UsdRelationship::GetTargets(SdfPathVector* targets) const
{
    TRACE_FUNCTION();

    UsdStage *stage = _GetStage();
    PcpErrorVector pcpErrors;
    std::vector<std::string> otherErrors;
    PcpTargetIndex targetIndex;
    {
        // Our intention is that the following code requires read-only
        // access to the PcpCache, so use a const-ref.
        const PcpCache& pcpCache(*stage->_GetPcpCache());
        // In USD mode, Pcp does not cache property indexes, so we
        // compute one here ourselves and use that.  First, we need
        // to get the prim index of the owning prim.
        const PcpPrimIndex &primIndex = _Prim()->GetPrimIndex();
        // PERFORMANCE: Here we can't avoid constructing the full property path
        // without changing the Pcp API.  We're about to do serious
        // composition/indexing, though, so the added expense may be neglible.
        const PcpSite propSite(pcpCache.GetLayerStackIdentifier(), GetPath());
        PcpPropertyIndex propIndex;
        PcpBuildPrimPropertyIndex(propSite.path, pcpCache, primIndex,
                                  &propIndex, &pcpErrors);
        PcpBuildTargetIndex(propSite, propIndex, SdfSpecTypeRelationship,
                            &targetIndex, &pcpErrors);
    }

    targets->swap(targetIndex.paths);
    if (!targets->empty() && _Prim()->IsInMaster()) {
        Usd_PrimDataConstPtr master = get_pointer(_Prim());
        while (!master->IsMaster()) { 
            master = master->GetParent();  
        }
        
        // Paths that point to an object under the master's source prim index
        // are internal to the master and need to be translated to either
        // the master or instance we're currently looking at.
        const SdfPath& masterSourcePrimIndexPath = 
            master->GetSourcePrimIndex().GetPath();

        if (GetPrim().IsInMaster()) {
            // Translate any paths that point to an object at or under the
            // source prim index to our master.
            for (SdfPath& target : *targets) {
                target = target.ReplacePrefix(
                    masterSourcePrimIndexPath, master->GetPath());
            }
        }
        else if (GetPrim().IsInstanceProxy()) {
            // Translate any paths that point to an object at or under the
            // source prim index to our instance.
            UsdPrim instance = GetPrim();
            while (!instance.IsInstance()) { 
                instance = instance.GetParent(); 
            }

            for (SdfPath& target : *targets) {
                target = target.ReplacePrefix(
                    masterSourcePrimIndexPath, instance.GetPath());
            }
        }
    }

    // TODO: handle errors
    const bool hasErrors = !(pcpErrors.empty() && otherErrors.empty());
    if (hasErrors) {
        stage->_ReportErrors(
            pcpErrors, otherErrors,
            TfStringPrintf("Getting targets for relationship <%s>",
                           GetPath().GetText()));
    }

    return !hasErrors;
}