예제 #1
0
파일: readNurbsPatch.cpp 프로젝트: MWDD/USD
/*
 * Return a FloatAttribute for points. There are 4 floats per
 * point, where the first 3 floats are the point's position,
 * and the 4th float is the weight of the point.
 */
static FnKat::FloatAttribute
_GetPwAttr(
    const UsdGeomNurbsPatch &nurbsPatch,
    double currentTime,
    const std::vector<double>& motionSampleTimes,
    const bool isMotionBackward)
{
    UsdAttribute weightsAttr = nurbsPatch.GetPointWeightsAttr();
    UsdAttribute pointsAttr = nurbsPatch.GetPointsAttr();

    if (!pointsAttr)
    {
        return FnKat::FloatAttribute();
    }

    FnKat::FloatBuilder pwBuilder(/* tupleSize = */ 4);
    TF_FOR_ALL(iter, motionSampleTimes)
    {
        double relSampleTime = *iter;
        double time = currentTime + relSampleTime;

        // Eval points at this motion sample time
        VtVec3fArray ptArray;
        pointsAttr.Get(&ptArray, time);
        // Eval Weights at this motion sample time
        VtDoubleArray wtArray;
        weightsAttr.Get(&wtArray, currentTime);
        
        bool hasWeights = false;
        if (ptArray.size() == wtArray.size())
        {
            hasWeights = true;
        }
        else if (wtArray.size() > 0)
        {
            FnLogWarn("Nurbs Patch " 
                    << nurbsPatch.GetPath().GetText()
                    << " has mismatched weights array. Skipping.");
            return FnKat::FloatAttribute();
        }

        // set the points data in katana at the give motion sample time
        std::vector<float> &ptVec = pwBuilder.get(isMotionBackward ?
            PxrUsdKatanaUtils::ReverseTimeSample(relSampleTime) : relSampleTime);

        ptVec.resize(ptArray.size() * 4);

        size_t count = 0;
        for (size_t i = 0; i != ptArray.size(); ++i)
        {
            float weight = hasWeights ? wtArray[i] : 1.0f;
            ptVec[count++] = ptArray[i][0]*weight;
            ptVec[count++] = ptArray[i][1]*weight;
            ptVec[count++] = ptArray[i][2]*weight;
            // the 4th float is the weight of the point
            ptVec[count++] = weight ;
        }
    }
예제 #2
0
파일: schemaBase.cpp 프로젝트: MWDD/USD
UsdAttribute
UsdSchemaBase::_CreateAttr(TfToken const &attrName,
                           SdfValueTypeName const & typeName,
                           bool custom, SdfVariability variability,
                           VtValue const &defaultValue, 
                           bool writeSparsely) const
{
    UsdPrim prim(GetPrim());
    
    if (writeSparsely && !custom){
        // We are a builtin, and we're trying to be parsimonious.
        // We only need to even CREATE a propertySpec if we are
        // authoring a non-fallback default value
        UsdAttribute attr = prim.GetAttribute(attrName);
        VtValue  fallback;
        if (defaultValue.IsEmpty() ||
            (!attr.HasAuthoredValueOpinion()
             && attr.Get(&fallback)
             && fallback == defaultValue)){
            return attr;
        }
    }
    
    UsdAttribute attr(prim.CreateAttribute(attrName, typeName,
                                           custom, variability));
    if (attr && !defaultValue.IsEmpty()) {
        attr.Set(defaultValue);
    }

    return attr;
}
예제 #3
0
static
bool
_TranslateUsdAttributeToPlug(
        const UsdAttribute& usdAttr,
        const MFnCamera& cameraFn,
        TfToken plugName,
        const PxrUsdMayaPrimReaderArgs& args,
        PxrUsdMayaPrimReaderContext* context,
        bool millimetersToInches=false)
{
    MStatus status;

    MPlug plug = cameraFn.findPlug(plugName.GetText(), true, &status);
    CHECK_MSTATUS_AND_RETURN(status, false);

    // First check for and translate animation if there is any.
    if (!_TranslateAnimatedUsdAttributeToPlug(usdAttr,
                                                 plug,
                                                 args,
                                                 context,
                                                 millimetersToInches)) {
        // If that fails, then try just setting a static value.
        UsdTimeCode timeCode = UsdTimeCode::EarliestTime();
        float attrValue;
        usdAttr.Get(&attrValue, timeCode);
        if (millimetersToInches) {
            attrValue = PxrUsdMayaUtil::ConvertMMToInches(attrValue);
        }
        status = plug.setFloat(attrValue);
        CHECK_MSTATUS_AND_RETURN(status, false);
    }

    return true;
}
예제 #4
0
파일: collectionAPI.cpp 프로젝트: JT-a/USD
bool 
UsdGeomCollectionAPI::GetTargetFaceIndices(
    VtIntArray *targetFaceIndices, 
    const UsdTimeCode &time /* =UsdTimeCode::Default() */) const
{
    UsdAttribute attr = _GetTargetFaceIndicesAttr();
    return attr.Get(targetFaceIndices, time);
}
예제 #5
0
파일: readPrim.cpp 프로젝트: 400dama/USD
static bool
_GatherRibAttributes(
        const UsdPrim &prim, 
        double currentTime,
        FnKat::GroupBuilder& attrsBuilder)
{
    bool hasAttrs = false;

    // USD SHADING STYLE ATTRIBUTES
    UsdRiStatements riStatements(prim);
    if (riStatements) {
        const std::vector<UsdProperty> props = 
            riStatements.GetRiAttributes();
        std::string attrName;
        TF_FOR_ALL(propItr, props) {
            UsdProperty prop = *propItr;
            if (!prop) continue;

            std::string nameSpace = 
                riStatements.GetRiAttributeNameSpace(prop).GetString();
            nameSpace = TfStringReplace(nameSpace, ":", ".") + ".";

            attrName = nameSpace +
                riStatements.GetRiAttributeName(prop).GetString();

            VtValue vtValue;
            UsdAttribute usdAttr = prim.GetAttribute(prop.GetName());
            if (usdAttr) {
                if (not usdAttr.Get(&vtValue, currentTime)) 
                    continue;

                // XXX asShaderParam really means:
                // "For arrays, as a single attr vs a type/value pair group"
                // The type/value pair group is meaningful for attrs who don't
                // have a formal type definition -- like a "user" RiAttribute.
                // 
                // However, other array values (such as two-element shadingrate)
                // are not expecting the type/value pair form and will not
                // generate rib correctly. As such, we'll handle the "user"
                // attribute as a special case.
                bool asShaderParam = true;
                
                if (nameSpace == "user.")
                {
                    asShaderParam = false;
                }

                attrsBuilder.set(attrName, PxrUsdKatanaUtils::ConvertVtValueToKatAttr(vtValue,
                    asShaderParam) );
            }
            else {
                UsdRelationship usdRel = prim.GetRelationship(prop.GetName());
                attrsBuilder.set(attrName, PxrUsdKatanaUtils::ConvertRelTargetsToKatAttr(usdRel,
                    /* asShaderParam */ false) );
            }
            hasAttrs = true;
        }
    }
예제 #6
0
void
UsdImagingGprimAdapter::_DiscoverPrimvars(UsdGeomGprim const& gprim,
                                          SdfPath const& cachePath, 
                                          UsdShadeShader const& shader,
                                          UsdTimeCode time,
                                          UsdImagingValueCache* valueCache)
{
    // TODO: It might be convenient to implicitly wire up PtexFaceOffset and
    // PtexFaceIndex primvars.
    
    TF_DEBUG(USDIMAGING_SHADERS).Msg("\t Looking for <%s> primvars at <%s>\n",
                            gprim.GetPrim().GetPath().GetText(),
                            shader.GetPrim().GetPath().GetText());
    for (UsdShadeParameter const& param : shader.GetParameters()) {
        UsdShadeShader source;
        TfToken outputName;
        if (param.GetConnectedSource(&source, &outputName)) {
            UsdAttribute attr = source.GetIdAttr();
            TfToken id;
            if (not attr or not attr.Get(&id)) {
                continue;
            }
            TF_DEBUG(USDIMAGING_SHADERS).Msg("\t\t Param <%s> connected <%s>(%s)\n",
                            param.GetAttr().GetName().GetText(),
                            source.GetPath().GetText(),
                            id.GetText());
            if (id == UsdHydraTokens->HwPrimvar_1) {
                TfToken t;
                VtValue v;
                UsdGeomPrimvar primvarAttr;
                if (UsdHydraPrimvar(source).GetVarnameAttr().Get(&t, 
                                            UsdTimeCode::Default())) {
                    primvarAttr = gprim.GetPrimvar(t);
                    if (primvarAttr.ComputeFlattened(&v, time)) {
                        TF_DEBUG(USDIMAGING_SHADERS).Msg("Found primvar %s\n",
                            t.GetText());

                        UsdImagingValueCache::PrimvarInfo primvar;
                        primvar.name = t;
                        primvar.interpolation = primvarAttr.GetInterpolation();
                        valueCache->GetPrimvar(cachePath, t) = v;
                        _MergePrimvar(primvar, &valueCache->GetPrimvars(cachePath));
                    } else {
                        TF_DEBUG(USDIMAGING_SHADERS).Msg(
                            "\t\t No primvar on <%s> named %s\n",
                            gprim.GetPath().GetText(),
                            t.GetText());

                    }
                }
            } else {
                // Recursively look for more primvars
                _DiscoverPrimvars(gprim, cachePath, source, time, valueCache);
            }
        }
    }
}
예제 #7
0
bool
UsdRiStatementsAPI::HasScopedCoordinateSystem() const
{
    std::string result;
    UsdAttribute attr = GetPrim().GetAttribute(_tokens->scopedCoordsys);
    if (attr) {
        return attr.Get(&result);
    }
    return false;
}
예제 #8
0
파일: primvar.cpp 프로젝트: JT-a/USD
bool 
UsdGeomPrimvar::GetIndices(VtIntArray *indices,
                           UsdTimeCode time) const
{
    UsdAttribute indicesAttr = _GetIndicesAttr(/*create*/ false);
    if (indicesAttr)
        return indicesAttr.Get(indices, time);

    return false;
}
예제 #9
0
std::string
UsdRiStatementsAPI::GetCoordinateSystem() const
{
    std::string result;
    UsdAttribute attr = GetPrim().GetAttribute(_tokens->coordsys);
    if (attr) {
        attr.Get(&result);
    }
    return result;
}
예제 #10
0
PXR_NAMESPACE_OPEN_SCOPE

bool
UsdGeomModelAPI::GetExtentsHint(VtVec3fArray *extents, 
                             const UsdTimeCode &time) const
{
    UsdAttribute extentsHintAttr = 
        GetPrim().GetAttribute(UsdGeomTokens->extentsHint);
    
    if (!extentsHintAttr)
        return false;

    return extentsHintAttr.Get(extents, time);
}
예제 #11
0
 _UsdBuilder& SetSpline(std::string kat_prefix, std::string valueSuffix,
                        UsdRiSplineAPI spline) {
     // Knot count
     {
         UsdAttribute posAttr = spline.GetPositionsAttr();
         VtFloatArray posVec;
         posAttr.Get(&posVec);
         _builder.set(kat_prefix, FnKat::IntAttribute(posVec.size()));
     }
     // Knot positions
     Set( kat_prefix + "_Knots", spline.GetPositionsAttr() );
     // Knot values
     Set( kat_prefix + valueSuffix, spline.GetValuesAttr() );
     // Interpolation
     {
         VtValue val;
         UsdAttribute attr = spline.GetInterpolationAttr();
         if (attr.IsValid() && attr.HasAuthoredValueOpinion()
             && attr.Get(&val, _time) && val.IsHolding<TfToken>()) {
             TfToken t = val.Get<TfToken>();
             std::string interp = "unknown";
             if (t == UsdRiTokens->linear) {
                 interp = "linear";
             } else if (t == UsdRiTokens->catmullRom) {
                 interp = "catmull-rom";
             } else if (t == UsdRiTokens->bspline) {
                 interp = "bspline";
             } else if (t == UsdRiTokens->constant) {
                 interp = "constant";
             }
             _builder.set(kat_prefix + "_Interpolation",
                          FnKat::StringAttribute(interp));
         }
     }
     return *this;
 }
예제 #12
0
bool
UsdGeomXformable::_GetXformOpOrderValue(
    VtTokenArray *xformOpOrder,
    bool *hasAuthoredValue) const
{
    UsdAttribute xformOpOrderAttr = GetXformOpOrderAttr();
    if (not xformOpOrderAttr)
        return false;

    if (hasAuthoredValue)
        *hasAuthoredValue = xformOpOrderAttr.HasAuthoredValueOpinion();

    xformOpOrderAttr.Get(xformOpOrder, UsdTimeCode::Default());
    return true;
}
예제 #13
0
static
bool
_GetTimeAndValueArrayForUsdAttribute(
        const UsdAttribute& usdAttr,
        const GfInterval& timeInterval,
        MTimeArray* timeArray,
        MDoubleArray* valueArray,
        const MDistance::Unit convertToUnit = MDistance::kMillimeters)
{
    static const TfType& floatType = TfType::Find<float>();
    std::vector<double> timeSamples;

    if (!_CheckUsdTypeAndResizeArrays(usdAttr,
                                      floatType,
                                      timeInterval,
                                      &timeSamples,
                                      timeArray,
                                      valueArray)) {
        return false;
    }

    size_t numTimeSamples = timeSamples.size();

    for (size_t i = 0; i < numTimeSamples; ++i) {
        const double timeSample = timeSamples[i];
        float attrValue;
        if (!usdAttr.Get(&attrValue, timeSample)) {
            return false;
        }

        switch (convertToUnit) {
            case MDistance::kInches:
                attrValue = UsdMayaUtil::ConvertMMToInches(attrValue);
                break;
            case MDistance::kCentimeters:
                attrValue = UsdMayaUtil::ConvertMMToCM(attrValue);
                break;
            default:
                // The input is expected to be in millimeters.
                break;
        }

        timeArray->set(MTime(timeSample), i);
        valueArray->set(attrValue, i);
    }

    return true;
}
예제 #14
0
static
bool
_TranslateUsdAttributeToPlug(
        const UsdAttribute& usdAttr,
        const MFnCamera& cameraFn,
        const TfToken& plugName,
        const UsdMayaPrimReaderArgs& args,
        UsdMayaPrimReaderContext* context,
        const MDistance::Unit convertToUnit = MDistance::kMillimeters)
{
    MStatus status;

    MPlug plug = cameraFn.findPlug(plugName.GetText(), true, &status);
    CHECK_MSTATUS_AND_RETURN(status, false);

    // First check for and translate animation if there is any.
    if (!_TranslateAnimatedUsdAttributeToPlug(usdAttr,
                                              plug,
                                              args,
                                              context,
                                              convertToUnit)) {
        // If that fails, then try just setting a static value.
        UsdTimeCode timeCode = UsdTimeCode::EarliestTime();
        float attrValue;
        usdAttr.Get(&attrValue, timeCode);

        switch (convertToUnit) {
            case MDistance::kInches:
                attrValue = UsdMayaUtil::ConvertMMToInches(attrValue);
                break;
            case MDistance::kCentimeters:
                attrValue = UsdMayaUtil::ConvertMMToCM(attrValue);
                break;
            default:
                // The input is expected to be in millimeters.
                break;
        }

        status = plug.setFloat(attrValue);
        CHECK_MSTATUS_AND_RETURN(status, false);
    }

    return true;
}
예제 #15
0
파일: primWrapper.cpp 프로젝트: mplanck/USD
void
GusdPrimWrapper::setVisibility(const TfToken& visibility, UsdTimeCode time)
{
    if( visibility == UsdGeomTokens->invisible ) {
        m_visible = false;
    } else {
        m_visible = true;
    }

    UsdAttribute visAttr = getUsdPrimForWrite().GetVisibilityAttr();
    if( visAttr.IsValid() ) {
        TfToken oldVal;
        if( !visAttr.Get( &oldVal, 
                          UsdTimeCode::Default() ) || oldVal != UsdGeomTokens->invisible ) {
            visAttr.Set(UsdGeomTokens->invisible, UsdTimeCode::Default()); 
        }
        visAttr.Set(visibility, time); 
    }
}
예제 #16
0
void
PxrUsdKatanaReadBlindData(
        const UsdKatanaBlindDataObject& kbd,
        PxrUsdKatanaAttrMap& attrs)
{
    std::vector<UsdProperty> blindProps = kbd.GetKbdAttributes();
    TF_FOR_ALL(blindPropIter, blindProps) {
        UsdProperty blindProp = *blindPropIter;
        if (blindProp.Is<UsdAttribute>()) {
            UsdAttribute blindAttr = blindProp.As<UsdAttribute>();
            VtValue vtValue;
            if (not blindAttr.Get(&vtValue)) {
                continue;
            }

            std::string attrName = 
                UsdKatanaBlindDataObject::GetKbdAttributeNameSpace(blindProp).GetString();

            // If the attribute has no namespace, then it should be a
            // top-level attribute and the name is simply the property 
            // 'base name'. Otherwise, attrName is the group attribute 
            // name, and we need to append onto it the group builder key.
            //
            if (attrName.empty())
            {
                attrName = blindProp.GetBaseName();
            }
            else
            {
                attrName += ".";
                attrName += UsdKatanaBlindDataObject::GetGroupBuilderKeyForProperty(blindProp);
            }

            // we set asShaderParam=true because we want the attribute to be
            // generated "as is", we *do not* want the prmanStatement style
            // "type"/"value" declaration to be created.
            attrs.set(attrName, 
                PxrUsdKatanaUtils::ConvertVtValueToKatAttr(
                    vtValue, 
                    /* asShaderParam */ true));
        }
    }
예제 #17
0
bool
UsdGeomModelAPI::SetExtentsHint(VtVec3fArray const &extents, 
                             const UsdTimeCode &time)
{
    if (!TF_VERIFY(extents.size() >= 2 &&
                      extents.size() <= (2 *
                      UsdGeomImageable::GetOrderedPurposeTokens().size())))
        return false;

    UsdAttribute extentsHintAttr = 
        GetPrim().CreateAttribute(UsdGeomTokens->extentsHint, 
                                  SdfValueTypeNames->Float3Array,
                                  /* custom = */ false);

    if (!extentsHintAttr)
        return false;

    VtVec3fArray currentExtentsHint;
    extentsHintAttr.Get(&currentExtentsHint, time);
   
    return extentsHintAttr.Set(extents, time);
}
예제 #18
0
static
bool
_GetTimeAndValueArrayForUsdAttribute(
        const UsdAttribute& usdAttr,
        const PxrUsdMayaPrimReaderArgs& args,
        MTimeArray* timeArray,
        MDoubleArray* valueArray,
        bool millimetersToInches=false)
{
    static const TfType& floatType = TfType::Find<float>();
    std::vector<double> timeSamples;

    if (!_CheckUsdTypeAndResizeArrays(usdAttr,
                                         floatType,
                                         args,
                                         &timeSamples,
                                         timeArray,
                                         valueArray)) {
        return false;
    }

    size_t numTimeSamples = timeSamples.size();

    for (size_t i = 0; i < numTimeSamples; ++i) {
        const double timeSample = timeSamples[i];
        float attrValue;
        if (!usdAttr.Get(&attrValue, timeSample)) {
            return false;
        }
        if (millimetersToInches) {
            attrValue = PxrUsdMayaUtil::ConvertMMToInches(attrValue);
        }
        timeArray->set(MTime(timeSample), i);
        valueArray->set(attrValue, i);
    }

    return true;
}
예제 #19
0
// This is primarily intended for use in translating the clippingRange
// USD attribute which is stored in USD as a single GfVec2f value but
// in Maya as separate nearClipPlane and farClipPlane attributes.
static
bool
_GetTimeAndValueArraysForUsdAttribute(
        const UsdAttribute& usdAttr,
        const GfInterval& timeInterval,
        MTimeArray* timeArray,
        MDoubleArray* valueArray1,
        MDoubleArray* valueArray2)
{
    static const TfType& vec2fType = TfType::Find<GfVec2f>();
    std::vector<double> timeSamples;

    if (!_CheckUsdTypeAndResizeArrays(usdAttr,
                                      vec2fType,
                                      timeInterval,
                                      &timeSamples,
                                      timeArray,
                                      valueArray1)) {
        return false;
    }

    size_t numTimeSamples = timeSamples.size();
    valueArray2->setLength(numTimeSamples);

    for (size_t i = 0; i < numTimeSamples; ++i) {
        const double timeSample = timeSamples[i];
        GfVec2f attrValue;
        if (!usdAttr.Get(&attrValue, timeSample)) {
            return false;
        }
        timeArray->set(MTime(timeSample), i);
        valueArray1->set(attrValue[0], i);
        valueArray2->set(attrValue[1], i);
    }

    return true;
}
예제 #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"));
}
예제 #21
0
HdTextureResourceSharedPtr
UsdImagingGL_GetTextureResource(UsdPrim const& usdPrim,
                                SdfPath const& usdPath,
                                UsdTimeCode time)
{
    if (!TF_VERIFY(usdPrim))
        return HdTextureResourceSharedPtr();
    if (!TF_VERIFY(usdPath != SdfPath()))
        return HdTextureResourceSharedPtr();

    UsdAttribute attr = _GetTextureResourceAttr(usdPrim, usdPath);
    SdfAssetPath asset;
    if (!TF_VERIFY(attr) || !TF_VERIFY(attr.Get(&asset, time))) {
        return HdTextureResourceSharedPtr();
    }

    HdTextureType textureType = HdTextureType::Uv;

    TfToken filePath = TfToken(asset.GetResolvedPath());
    // If the path can't be resolved, it's either an UDIM texture
    // or the texture doesn't exists and we can to exit early.
    if (filePath.IsEmpty()) {
        filePath = TfToken(asset.GetAssetPath());
        if (GlfIsSupportedUdimTexture(filePath)) {
            textureType = HdTextureType::Udim;
        } else {
            TF_DEBUG(USDIMAGING_TEXTURES).Msg(
                "File does not exist, returning nullptr");
            TF_WARN("Unable to find Texture '%s' with path '%s'.",
                    filePath.GetText(), usdPath.GetText());
            return {};
        }
    } else {
        if (GlfIsSupportedPtexTexture(filePath)) {
            textureType = HdTextureType::Ptex;
        }
    }

    GlfImage::ImageOriginLocation origin =
            UsdImagingGL_ComputeTextureOrigin(usdPrim);

    HdWrap wrapS = _GetWrapS(usdPrim, textureType);
    HdWrap wrapT = _GetWrapT(usdPrim, textureType);
    HdMinFilter minFilter = _GetMinFilter(usdPrim);
    HdMagFilter magFilter = _GetMagFilter(usdPrim);
    float memoryLimit = _GetMemoryLimit(usdPrim);

    TF_DEBUG(USDIMAGING_TEXTURES).Msg(
            "Loading texture: id(%s), type(%s)\n",
            usdPath.GetText(),
            textureType == HdTextureType::Uv ? "Uv" :
            textureType == HdTextureType::Ptex ? "Ptex" : "Udim");
 
    HdTextureResourceSharedPtr texResource;
    TfStopwatch timer;
    timer.Start();
    // Udim's can't be loaded through like other textures, because
    // we can't select the right factory based on the file type.
    // We also need to pass the layer context to the factory,
    // so each file gets resolved properly.
    GlfTextureHandleRefPtr texture;
    if (textureType == HdTextureType::Udim) {
        UdimTextureFactory factory(_FindLayerHandle(attr, time));
        texture = GlfTextureRegistry::GetInstance().GetTextureHandle(
            filePath, origin, &factory);
    } else {
        texture = GlfTextureRegistry::GetInstance().GetTextureHandle(
            filePath, origin);
    }

    texResource = HdTextureResourceSharedPtr(
        new HdStSimpleTextureResource(texture, textureType, wrapS, wrapT,
                                      minFilter, magFilter, memoryLimit));
    timer.Stop();

    TF_DEBUG(USDIMAGING_TEXTURES).Msg("    Load time: %.3f s\n", 
                                     timer.GetSeconds());

    return texResource;
}
PXR_NAMESPACE_USING_DIRECTIVE

void
TestTemplates()
{
    // --------------------------------------------------------------------- //
    // This test operates on /RootPrim.foo
    // and /RootPrim.foo:hidden
    // --------------------------------------------------------------------- //
    SdfPath primPath("/RootPrim");
    TfToken prop("foo");
    TfToken metaField("hidden");
    std::string propPath(primPath.GetString() + "." + prop.GetString());

    // --------------------------------------------------------------------- //
    // Author scene and compose the Stage 
    // --------------------------------------------------------------------- //
    SdfLayerRefPtr layer = SdfLayer::CreateAnonymous();
    UsdStageRefPtr stage = UsdStage::Open(layer->GetIdentifier());

    TF_VERIFY(stage->OverridePrim(primPath),
              "Failed to create prim at %s",
              primPath.GetText());

    UsdPrim prim(stage->GetPrimAtPath(primPath));
    TF_VERIFY(prim, "Failed to get Prim from %s", primPath.GetText());

    // Grab the attribute we will be testing with.
    UsdAttribute attr =
        prim.CreateAttribute(prop, SdfValueTypeNames->Double3Array);
    TF_VERIFY(attr, "Failed to create property at %s", propPath.c_str());

    // --------------------------------------------------------------------- //
    // Setup some test data 
    // --------------------------------------------------------------------- //
    VtVec3dArray vtVecOut(1);
    VtVec3dArray vtVecIn;
    std::string tmp;

    VtValue value;

    // ===================================================================== //
    // TEST READING METADATA
    // ===================================================================== //

    // --------------------------------------------------------------------- //
    // GetMetadata & SetMetadata the value as a VtValue
    // --------------------------------------------------------------------- //
    TF_VERIFY(attr.SetMetadata(metaField, VtValue(true)),
              "VtValue: Failed to set hidden metadata at %s",
              propPath.c_str());

    // Print the layer for debugging.
    layer->ExportToString(&tmp);
    std::cout << "-----------------------------------------" << std::endl;
    std::cout << "Metadata -- VtValue:" << std::endl;
    std::cout << tmp << std::endl;

    // Verify the result.
    TF_VERIFY(attr.GetMetadata(metaField, &value),
              "Metadata -- VtValue: Failed to get property value at %s",
              propPath.c_str());
    TF_VERIFY(value.IsHolding<bool>(),
              "Metadata -- VtValue: not holding bool%s",
              propPath.c_str());
   TF_VERIFY(value.Get<bool>(),
              "Metadata -- VtValue: value was not true %s",
              propPath.c_str());

    // --------------------------------------------------------------------- //
    // GetMetadata & SetMetadata the value as bool 
    // --------------------------------------------------------------------- //
    bool valueIn = false;
    TF_VERIFY(attr.SetMetadata(metaField, true),
              "Metadata -- bool: Failed to set property at %s",
              propPath.c_str());

    // Print the layer for debugging.
    tmp = "";
    layer->ExportToString(&tmp);
    std::cout << "-----------------------------------------" << std::endl;
    std::cout << "Metadata -- bool:" << std::endl;
    std::cout << tmp << std::endl;

    // Verify Result.
    TF_VERIFY(attr.GetMetadata(metaField, &valueIn),
              "Metadata -- bool: Failed to get property value at %s",
              propPath.c_str());
    TF_VERIFY(valueIn,
              "Metadata -- bool: value was not true %s",
              propPath.c_str());

    
    // ===================================================================== //
    // TEST READING VALUES
    // ===================================================================== //
    
    // --------------------------------------------------------------------- //
    // Get & Set the value as a VtValue
    // --------------------------------------------------------------------- //
    vtVecOut[0] = GfVec3d(9,8,7);
    TF_VERIFY(attr.Set(VtValue(vtVecOut)),
              "VtValue: Failed to set property at %s",
              propPath.c_str());

    // Print the layer for debugging.
    layer->ExportToString(&tmp);
    std::cout << "-----------------------------------------" << std::endl;
    std::cout << "VtValue:" << std::endl;
    std::cout << tmp << std::endl;

    // Verify the result.
    TF_VERIFY(attr.Get(&value),
              "VtValue: Failed to get property value at %s",
              propPath.c_str());
    TF_VERIFY(value.IsHolding<VtVec3dArray>(),
              "VtValue: not holding VtVec3dArray %s",
              propPath.c_str());
   TF_VERIFY(value.Get<VtVec3dArray>()[0] == vtVecOut[0],
              "VtValue: VtVec3d[0] does not match %s",
              propPath.c_str());

    // --------------------------------------------------------------------- //
    // Get & Set the value as a VtArray 
    // --------------------------------------------------------------------- //
    vtVecOut[0] = GfVec3d(6,5,4);
    TF_VERIFY(attr.Set(vtVecOut),
              "Failed to set property at %s",
              propPath.c_str());

    // Print the layer for debugging.
    tmp = "";
    layer->ExportToString(&tmp);
    std::cout << "-----------------------------------------" << std::endl;
    std::cout << "VtArray:" << std::endl;
    std::cout << tmp << std::endl;

    // Verify Result.
    TF_VERIFY(attr.Get(&vtVecIn),
              "VtArray: Failed to get property value at %s",
              propPath.c_str());
    TF_VERIFY(vtVecIn[0] == vtVecOut[0],
              "VtArray: VtVec3d[0] does not match %s",
              propPath.c_str());

    // --------------------------------------------------------------------- //
    // Get & Set the value as a VtDictionary (Dictionary composition semantics
    // are exercised in testUsdMetadata).
    // --------------------------------------------------------------------- //
    VtDictionary inDict;
    inDict["$Side"] = "R";
    TF_VERIFY(!prim.HasAuthoredMetadata(SdfFieldKeys->PrefixSubstitutions));
    TF_VERIFY(prim.SetMetadata(SdfFieldKeys->PrefixSubstitutions, inDict));
    VtDictionary outDict;
    TF_VERIFY(prim.HasAuthoredMetadata(SdfFieldKeys->PrefixSubstitutions));
    // Verify bug 97783 - GetMetadata should return true if Usd was able to
    // retrieve/compose a VtDictionary.
    TF_VERIFY(prim.GetMetadata(SdfFieldKeys->PrefixSubstitutions,&outDict));
    TF_VERIFY(inDict == outDict);
    std::cout << "-----------------------------------------" << std::endl;
    std::cout << "VtDictionary:" << std::endl;
    tmp = "";
    layer->ExportToString(&tmp);
    std::cout << tmp << std::endl;
    
}
예제 #23
0
파일: translatorMesh.cpp 프로젝트: JT-a/USD
PXR_NAMESPACE_OPEN_SCOPE



/* static */
bool 
PxrUsdMayaTranslatorMesh::Create(
        const UsdGeomMesh& mesh,
        MObject parentNode,
        const PxrUsdMayaPrimReaderArgs& args,
        PxrUsdMayaPrimReaderContext* context)
{
    if (!mesh) {
        return false;
    }

    const UsdPrim& prim = mesh.GetPrim();

    MStatus status;

    // Create node (transform)
    MObject mayaNodeTransformObj;
    if (!PxrUsdMayaTranslatorUtil::CreateTransformNode(prim,
                                                          parentNode,
                                                          args,
                                                          context,
                                                          &status,
                                                          &mayaNodeTransformObj)) {
        return false;
    }

    VtArray<GfVec3f> points;
    VtArray<GfVec3f> normals;
    VtArray<int>     faceVertexCounts;
    VtArray<int>     faceVertexIndices;
    
    UsdAttribute fvc = mesh.GetFaceVertexCountsAttr();
    if (fvc.ValueMightBeTimeVarying()){
        // at some point, it would be great, instead of failing, to create a usd/hydra proxy node
        // for the mesh, perhaps?  For now, better to give a more specific error
        MGlobal::displayError(
            TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexCounts). Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false;
    } else {
        // for any non-topo-varying mesh, sampling at zero will get us the right answer
        fvc.Get(&faceVertexCounts, 0);
    }

    UsdAttribute fvi = mesh.GetFaceVertexIndicesAttr();
    if (fvi.ValueMightBeTimeVarying()){
        // at some point, it would be great, instead of failing, to create a usd/hydra proxy node
        // for the mesh, perhaps?  For now, better to give a more specific error
        MGlobal::displayError(
            TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexIndices). Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false;
    } else {
        // for any non-topo-varying mesh, sampling at zero will get us the right answer
        fvi.Get(&faceVertexIndices, 0);
    }
        
    // Sanity Checks. If the vertex arrays are empty, skip this mesh
    if (faceVertexCounts.size() == 0 || faceVertexIndices.size() == 0) {
        MGlobal::displayError(
            TfStringPrintf("FaceVertex arrays are empty [Count:%zu Indices:%zu] on Mesh <%s>. Skipping...", 
                faceVertexCounts.size(), faceVertexIndices.size(), 
                prim.GetPath().GetText()).c_str());
        return false; // invalid mesh, so exit
    }

    // Gather points and normals
    // If args.GetReadAnimData() is TRUE,
    // pick the first avaiable sample or default
    UsdTimeCode pointsTimeSample=UsdTimeCode::EarliestTime();
    UsdTimeCode normalsTimeSample=UsdTimeCode::EarliestTime();
    std::vector<double> pointsTimeSamples;
    size_t pointsNumTimeSamples = 0;
    if (args.GetReadAnimData()) {
        PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetPointsAttr(), args,
                &pointsTimeSamples);
        pointsNumTimeSamples = pointsTimeSamples.size();
        if (pointsNumTimeSamples>0) {
            pointsTimeSample = pointsTimeSamples[0];
        }
    	std::vector<double> normalsTimeSamples;
        PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetNormalsAttr(), args,
                &normalsTimeSamples);
        if (normalsTimeSamples.size()) {
            normalsTimeSample = normalsTimeSamples[0];
        }
    }
    mesh.GetPointsAttr().Get(&points, pointsTimeSample);
    mesh.GetNormalsAttr().Get(&normals, normalsTimeSample);
    
    if (points.size() == 0) {
        MGlobal::displayError(
            TfStringPrintf("Points arrays is empty on Mesh <%s>. Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false; // invalid mesh, so exit
    }


    // == Convert data
    size_t mayaNumVertices = points.size();
    MPointArray mayaPoints(mayaNumVertices);
    for (size_t i=0; i < mayaNumVertices; i++) {
        mayaPoints.set( i, points[i][0], points[i][1], points[i][2] );
    }

    MIntArray polygonCounts( faceVertexCounts.cdata(),  faceVertexCounts.size() );
    MIntArray polygonConnects( faceVertexIndices.cdata(), faceVertexIndices.size() );

    // == Create Mesh Shape Node
    MFnMesh meshFn;
    MObject meshObj = meshFn.create(mayaPoints.length(), 
                           polygonCounts.length(), 
                           mayaPoints, 
                           polygonCounts, 
                           polygonConnects,
                           mayaNodeTransformObj,
                           &status
                           );
                           
    if (status != MS::kSuccess) {
        return false;
    }

    // Since we are "decollapsing", we will create a xform and a shape node for each USD prim
    std::string usdPrimName(prim.GetName().GetText());
    std::string shapeName(usdPrimName); shapeName += "Shape";
    // Set mesh name and register
    meshFn.setName(MString(shapeName.c_str()), false, &status);
    if (context) {
        std::string usdPrimPath(prim.GetPath().GetText());
        std::string shapePath(usdPrimPath);
        shapePath += "/";
        shapePath += shapeName;
        context->RegisterNewMayaNode( shapePath, meshObj ); // used for undo/redo
    }

    // If a material is bound, create (or reuse if already present) and assign it
    // If no binding is present, assign the mesh to the default shader    
    const TfToken& shadingMode = args.GetShadingMode();
    PxrUsdMayaTranslatorMaterial::AssignMaterial(shadingMode, mesh, meshObj,
            context);
    
    // Mesh is a shape, so read Gprim properties
    PxrUsdMayaTranslatorGprim::Read(mesh, meshObj, context);

    // Set normals if supplied
    MIntArray normalsFaceIds;
    if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) {

        for (size_t i=0; i < polygonCounts.length(); i++) {
            for (int j=0; j < polygonCounts[i]; j++) {
                normalsFaceIds.append(i);
            }
        }
        if (normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) {
            MVectorArray mayaNormals(normals.size());
            for (size_t i=0; i < normals.size(); i++) {
                mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i);
            }
            if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) {
            }
        }
     }

    // Determine if PolyMesh or SubdivMesh
    TfToken subdScheme = PxrUsdMayaMeshUtil::setSubdivScheme(mesh, meshFn, args.GetDefaultMeshScheme());

    // If we are dealing with polys, check if there are normals
    // If we are dealing with SubdivMesh, read additional attributes and SubdivMesh properties
    if (subdScheme == UsdGeomTokens->none) {
        if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) {
            PxrUsdMayaMeshUtil::setEmitNormals(mesh, meshFn, UsdGeomTokens->none);
        }
    } else {
        PxrUsdMayaMeshUtil::setSubdivInterpBoundary(mesh, meshFn, UsdGeomTokens->edgeAndCorner);
        PxrUsdMayaMeshUtil::setSubdivFVLinearInterpolation(mesh, meshFn);
        _AssignSubDivTagsToMesh(mesh, meshObj, meshFn);
    }
 
    // Set Holes
    VtArray<int> holeIndices;
    mesh.GetHoleIndicesAttr().Get(&holeIndices);   // not animatable
    if ( holeIndices.size() != 0 ) {
        MUintArray mayaHoleIndices;
        mayaHoleIndices.setLength( holeIndices.size() );
        for (size_t i=0; i < holeIndices.size(); i++) {
            mayaHoleIndices[i] = holeIndices[i];
        }
        if (meshFn.setInvisibleFaces(mayaHoleIndices) == MS::kFailure) {
            MGlobal::displayError(TfStringPrintf("Unable to set Invisible Faces on <%s>", 
                            meshFn.fullPathName().asChar()).c_str());
        }
    }

    // GETTING PRIMVARS
    std::vector<UsdGeomPrimvar> primvars = mesh.GetPrimvars();
    TF_FOR_ALL(iter, primvars) {
        const UsdGeomPrimvar& primvar = *iter;
        const TfToken& name = primvar.GetBaseName();
        const SdfValueTypeName& typeName = primvar.GetTypeName();

        // If the primvar is called either displayColor or displayOpacity check
        // if it was really authored from the user.  It may not have been
        // authored by the user, for example if it was generated by shader
        // values and not an authored colorset/entity.
        // If it was not really authored, we skip the primvar.
        if (name == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName || 
                name == PxrUsdMayaMeshColorSetTokens->DisplayOpacityColorSetName) {
            if (!PxrUsdMayaRoundTripUtil::IsAttributeUserAuthored(primvar)) {
                continue;
            }
        }

        // XXX: Maya stores UVs in MFloatArrays and color set data in MColors
        // which store floats, so we currently only import primvars holding
        // float-typed arrays. Should we still consider other precisions
        // (double, half, ...) and/or numeric types (int)?
        if (typeName == SdfValueTypeNames->Float2Array) {
            // We assume that Float2Array primvars are UV sets.
            if (!_AssignUVSetPrimvarToMesh(primvar, meshFn)) {
                MGlobal::displayWarning(
                    TfStringPrintf("Unable to retrieve and assign data for UV set <%s> on mesh <%s>", 
                                   name.GetText(),
                                   mesh.GetPrim().GetPath().GetText()).c_str());
            }
        } else if (typeName == SdfValueTypeNames->FloatArray   || 
                   typeName == SdfValueTypeNames->Float3Array  || 
                   typeName == SdfValueTypeNames->Color3fArray ||
                   typeName == SdfValueTypeNames->Float4Array  || 
                   typeName == SdfValueTypeNames->Color4fArray) {
            if (!_AssignColorSetPrimvarToMesh(mesh, primvar, meshFn)) {
                MGlobal::displayWarning(
                    TfStringPrintf("Unable to retrieve and assign data for color set <%s> on mesh <%s>",
                                   name.GetText(),
                                   mesh.GetPrim().GetPath().GetText()).c_str());
            }
        }
    }

    // We only vizualize the colorset by default if it is "displayColor".  
    MStringArray colorSetNames;
    if (meshFn.getColorSetNames(colorSetNames)==MS::kSuccess) {
        for (unsigned int i=0; i < colorSetNames.length(); i++) {
            const MString colorSetName = colorSetNames[i];
            if (std::string(colorSetName.asChar()) 
                    == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName.GetString()) {
                MFnMesh::MColorRepresentation csRep=
                    meshFn.getColorRepresentation(colorSetName);
                if (csRep==MFnMesh::kRGB || csRep==MFnMesh::kRGBA) {

                    // both of these are needed to show the colorset.
                    MPlug plg=meshFn.findPlug("displayColors");
                    if ( !plg.isNull() ) {
                        plg.setBool(true);
                    }
                    meshFn.setCurrentColorSetName(colorSetName);
                }
                break;
            }
        }
    }
    
    // == Animate points ==
    //   Use blendShapeDeformer so that all the points for a frame are contained in a single node
    //
    if (pointsNumTimeSamples > 0) {
        MPointArray mayaPoints(mayaNumVertices);
        MObject meshAnimObj;

        MFnBlendShapeDeformer blendFn;
        MObject blendObj = blendFn.create(meshObj);
        if (context) {
            context->RegisterNewMayaNode( blendFn.name().asChar(), blendObj ); // used for undo/redo
        }

        for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
             mesh.GetPointsAttr().Get(&points, pointsTimeSamples[ti]);

            for (unsigned int i=0; i < mayaNumVertices; i++) {
                mayaPoints.set( i, points[i][0], points[i][1], points[i][2] );
            }

            // == Create Mesh Shape Node
            MFnMesh meshFn;
            if ( meshAnimObj.isNull() ) {
                meshAnimObj = meshFn.create(mayaPoints.length(), 
                                       polygonCounts.length(), 
                                       mayaPoints, 
                                       polygonCounts, 
                                       polygonConnects,
                                       mayaNodeTransformObj,
                                       &status
                                       );
                if (status != MS::kSuccess) {
                    continue;
                }
            }
            else {
                // Reuse the already created mesh by copying it and then setting the points
                meshAnimObj = meshFn.copy(meshAnimObj, mayaNodeTransformObj, &status);
                meshFn.setPoints(mayaPoints);
            }

            // Set normals if supplied
            //
            // NOTE: This normal information is not propagated through the blendShapes, only the controlPoints.
            //
             mesh.GetNormalsAttr().Get(&normals, pointsTimeSamples[ti]);
             if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices()) &&
                normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) {

                MVectorArray mayaNormals(normals.size());
                for (size_t i=0; i < normals.size(); i++) {
                    mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i);
                }
                if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) {
                }
             }

            // Add as target and set as an intermediate object
            blendFn.addTarget(meshObj, ti, meshAnimObj, 1.0);
            meshFn.setIntermediateObject(true);
            if (context) {
                context->RegisterNewMayaNode( meshFn.fullPathName().asChar(), meshAnimObj ); // used for undo/redo
            }
        }

        // Animate the weights so that mesh0 has a weight of 1 at frame 0, etc.
        MFnAnimCurve animFn;

        // Construct the time array to be used for all the keys
        MTimeArray timeArray;
        timeArray.setLength(pointsNumTimeSamples);
        for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
            timeArray.set( MTime(pointsTimeSamples[ti]), ti);
        }

        // Key/Animate the weights
        MPlug plgAry = blendFn.findPlug( "weight" );
        if ( !plgAry.isNull() && plgAry.isArray() ) {
            for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
                MPlug plg = plgAry.elementByLogicalIndex(ti, &status);
                MDoubleArray valueArray(pointsNumTimeSamples, 0.0);
                valueArray[ti] = 1.0; // Set the time value where this mesh's weight should be 1.0
                MObject animObj = animFn.create(plg, NULL, &status);
                animFn.addKeys(&timeArray, &valueArray);
                if (context) {
                    context->RegisterNewMayaNode(animFn.name().asChar(), animObj ); // used for undo/redo
                }
            }
        }
    }

    return true;
}
예제 #24
0
HdTextureResource::ID
UsdImagingGL_GetTextureResourceID(UsdPrim const& usdPrim,
                                  SdfPath const& usdPath,
                                  UsdTimeCode time,
                                  size_t salt)
{
    if (!TF_VERIFY(usdPrim)) {
        return HdTextureResource::ID(-1);
    }
    if (!TF_VERIFY(usdPath != SdfPath())) {
        return HdTextureResource::ID(-1);
    }

    // If the texture name attribute doesn't exist, it might be badly specified
    // in scene data.
    UsdAttribute attr = _GetTextureResourceAttr(usdPrim, usdPath);

    SdfAssetPath asset;
    if (!attr || !attr.Get(&asset, time)) {
        TF_WARN("Unable to find texture attribute <%s> in scene data",
                usdPath.GetText());
        return HdTextureResource::ID(-1);
    }

    HdTextureType textureType = HdTextureType::Uv;
    TfToken filePath = TfToken(asset.GetResolvedPath());

    if (!filePath.IsEmpty()) {
        // If the resolved path contains a correct path, then we are 
        // dealing with a ptex or uv textures.
        if (GlfIsSupportedPtexTexture(filePath)) {
            textureType = HdTextureType::Ptex;
        } else {
            textureType = HdTextureType::Uv;
        }
    } else {
        // If the path couldn't be resolved, then it might be a Udim as they 
        // contain special characters in the path to identify them <Udim>.
        // Another option is that the path is just wrong and it can not be
        // resolved.
        filePath = TfToken(asset.GetAssetPath());
        if (GlfIsSupportedUdimTexture(filePath)) {
            const GlfContextCaps& caps = GlfContextCaps::GetInstance();
            if (!UsdImaging_UdimTilesExist(filePath, caps.maxArrayTextureLayers,
                _FindLayerHandle(attr, time))) {
                TF_WARN("Unable to find Texture '%s' with path '%s'. Fallback "
                        "textures are not supported for udim",
                        filePath.GetText(), usdPath.GetText());
                return HdTextureResource::ID(-1);
            }
            if (!caps.arrayTexturesEnabled) {
                TF_WARN("OpenGL context does not support array textures, "
                        "skipping UDIM Texture %s with path %s.",
                        filePath.GetText(), usdPath.GetText());
                return HdTextureResource::ID(-1);
            }
            textureType = HdTextureType::Udim;
        } else if (GlfIsSupportedPtexTexture(filePath)) {
            TF_WARN("Unable to find Texture '%s' with path '%s'. Fallback "
                    "textures are not supported for ptex",
                    filePath.GetText(), usdPath.GetText());
            return HdTextureResource::ID(-1);
        } else {
            TF_WARN("Unable to find Texture '%s' with path '%s'. A black "
                    "texture will be substituted in its place.",
                    filePath.GetText(), usdPath.GetText());
            return HdTextureResource::ID(-1);
        }
    }

    GlfImage::ImageOriginLocation origin =
            UsdImagingGL_ComputeTextureOrigin(usdPrim);

    // Hash on the texture filename.
    size_t hash = asset.GetHash();

    // Hash in wrapping and filtering metadata.
    HdWrap wrapS = _GetWrapS(usdPrim, textureType);
    HdWrap wrapT = _GetWrapT(usdPrim, textureType);
    HdMinFilter minFilter = _GetMinFilter(usdPrim);
    HdMagFilter magFilter = _GetMagFilter(usdPrim);
    float memoryLimit = _GetMemoryLimit(usdPrim);

    boost::hash_combine(hash, origin);
    boost::hash_combine(hash, wrapS);
    boost::hash_combine(hash, wrapT);
    boost::hash_combine(hash, minFilter);
    boost::hash_combine(hash, magFilter);
    boost::hash_combine(hash, memoryLimit);

    // Salt the result to prevent collisions in non-shared imaging.
    // Note that the salt is ignored for fallback texture hashes above.
    boost::hash_combine(hash, salt);

    return HdTextureResource::ID(hash);
}