Beispiel #1
0
        /// <summary>
        /// Check if the selected material supports "tint".
        /// </summary>
        /// <returns>True if the selected material supports "tint" or not.</returns>
        private bool SupportTintColor()
        {
            if (this.m_currentAppearanceAssetElementId == ElementId.InvalidElementId)
            {
                return(false);
            }

            AppearanceAssetElement assetElem = m_document.GetElement(this.m_currentAppearanceAssetElementId) as AppearanceAssetElement;

            if (assetElem == null)
            {
                return(false);
            }

            Asset asset = assetElem.GetRenderingAsset();
            AssetPropertyDoubleArray4d tintColorProp = asset["common_Tint_color"] as AssetPropertyDoubleArray4d;

            if (tintColorProp == null)
            {
                return(false);
            }

            // If the material supports tint but it is not enabled, it will be enabled first with a value (255 255 255)
            AssetPropertyBoolean tintToggleProp = asset["common_Tint_toggle"] as AssetPropertyBoolean;

            if ((tintToggleProp != null) && !(tintToggleProp.Value))
            {
                EnableTintColor();
            }

            return(true);
        }
Beispiel #2
0
 /// <summary>
 /// 得到材质的Asset集合
 /// </summary>
 /// <param name="node"></param>
 private void ReadBitMap(MaterialNode node)
 {
     if (node.MaterialId != ElementId.InvalidElementId)
     {
         Asset theAsset = node.GetAppearance();
         if (node.HasOverriddenAppearance)
         {
             theAsset = node.GetAppearanceOverride();
         }
         if (theAsset == null)
         {
             Material  material     = _doc.GetElement(node.MaterialId) as Material;
             ElementId appearanceId = material.AppearanceAssetId;
             AppearanceAssetElement appearanceElem = _doc.GetElement(appearanceId) as AppearanceAssetElement;
             theAsset = appearanceElem.GetRenderingAsset();
         }
         if (theAsset.Size == 0)
         {
             //Asset大小为0,则为欧特克材质
             foreach (Asset objCurrentAsset in _objlibraryAsset)
             {
                 if (objCurrentAsset.Name == theAsset.Name && objCurrentAsset.LibraryName == theAsset.LibraryName)
                 {
                     ReadAsset(objCurrentAsset, ttrgb);
                 }
             }
         }
         else
         {
             ReadAsset(theAsset, ttrgb);
         }
     }
 }
Beispiel #3
0
        public void ShowMaterialInfo(Document doc)
        {
            // Find material
            FilteredElementCollector fec = new FilteredElementCollector(doc);

            fec.OfClass(typeof(Material));

            String materialName = "Checker"; // "Copper";//"Prism - Glass - Textured"; // "Parking Stripe"; // "Copper";
                                             // "Carpet (1)";// "Prism - Glass - Textured";// "Parking Stripe"; // "Prism 1";// "Brick, Common" ;// "Acoustic Ceiling Tile 24 x 48";  // "Aluminum"
            Material mat = fec.Cast <Material>().First <Material>(m => m.Name == materialName);



            ElementId appearanceAssetId = mat.AppearanceAssetId;

            AppearanceAssetElement appearanceAsset = doc.GetElement(appearanceAssetId) as AppearanceAssetElement;

            Asset renderingAsset = appearanceAsset.GetRenderingAsset();



            RenderAppearanceDescriptor rad
                = new RenderAppearanceDescriptor(renderingAsset);


            PropertyDescriptorCollection collection = rad.GetProperties();

            TaskDialog.Show("Total properties", "Properties found: " + collection.Count);
            //

            string s = ": Material Asset Properties";

            TaskDialog dlg = new TaskDialog(s);

            dlg.MainInstruction = mat.Name + s;

            s = string.Empty;

            List <PropertyDescriptor> orderableCollection = new List <PropertyDescriptor>(collection.Count);

            foreach (PropertyDescriptor descr in collection)
            {
                orderableCollection.Add(descr);
            }



            foreach (AssetPropertyPropertyDescriptor descr in
                     orderableCollection.OrderBy <PropertyDescriptor, String>(pd => pd.Name).Cast <AssetPropertyPropertyDescriptor>())
            {
                object value = descr.GetValue(rad);

                s += "\nname: " + descr.Name
                     + " | type: " + descr.PropertyType.Name
                     + " | value: " + value;
            }
            dlg.MainContent = s;
            dlg.Show();
        }
 // 定义获取贴图名称的方法
 public void GetMapname(Document doc, Material mat)
 {
     if (Convert.ToString(mat.AppearanceAssetId) != "-1")
     {
         AppearanceAssetElement appearanceAssetElement = doc.GetElement(mat.AppearanceAssetId) as AppearanceAssetElement;
         Asset  asset  = appearanceAssetElement.GetRenderingAsset();
         Asset  asset2 = asset.FindByName("generic_diffuse").GetSingleConnectedAsset();
         string name   = asset2.FindByName("unifiedbitmap_Bitmap").ToString();
     }
 }
Beispiel #5
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //获取当前文档
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;
            Document   doc   = commandData.Application.ActiveUIDocument.Document;
            //指定输出信息的文件
            FileStream   fs = new FileStream(@"C:\Users\11265\Desktop\0.txt", FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            //指定存放贴图路径的列表
            List <string> oldPathList           = new List <string>();
            List <string> newPathList           = new List <string>();
            List <string> fileNameList          = new List <string>();
            Dictionary <string, string> dicPath = new Dictionary <string, string>();



            // 获取元素
            IList <Reference> referList = uiDoc.Selection.PickObjects(ObjectType.Element, "请框选需要的构件");
            Element           elem      = doc.GetElement(referList.First().ElementId);
            //获取元素的材质
            ICollection <ElementId> ids = elem.GetMaterialIds(false);
            Material material           = doc.GetElement(ids.First()) as Material;
            AppearanceAssetElement appearanceAssetElement = doc.GetElement(material.AppearanceAssetId) as AppearanceAssetElement;
            Asset asset = appearanceAssetElement.GetRenderingAsset();

            for (int i = 0; i < asset.Size; i++)
            {
                AssetProperty prop = asset[i];
                ReadAssetProperty(prop, sw, oldPathList);
            }
            sw.Flush();
            sw.Close();
            TaskDialog.Show("demo", "转换完成");
            foreach (var item in oldPathList)
            {
                TaskDialog.Show("result", item);
            }

            //复制文件更改材质路径



            return(Result.Succeeded);
        }
Beispiel #6
0
        /// <summary>
        /// Check if the button Darker is enabled.
        /// </summary>
        /// <returns>True if the material can be made darker or not.</returns>
        internal bool IsDarkerEnabled()
        {
            if (!SupportTintColor())
            {
                return(false);
            }

            AppearanceAssetElement assetElem = m_document.GetElement(this.m_currentAppearanceAssetElementId) as AppearanceAssetElement;

            if (assetElem == null)
            {
                return(false);
            }

            Asset asset = assetElem.GetRenderingAsset();
            AssetPropertyDoubleArray4d tintColorProp = asset["common_Tint_color"] as AssetPropertyDoubleArray4d;
            Color tintColor = tintColorProp.GetValueAsColor();
            Color black     = new Color(0, 0, 0);

            return(!ColorsEqual(tintColor, black));
        }
Beispiel #7
0
        /// <summary>
        /// Check if the button Lighter is enabled.
        /// </summary>
        /// <returns>True if the material can be made lighter or not.</returns>
        internal bool IsLighterEnabled()
        {
            if (!SupportTintColor())
            {
                return(false);
            }

            AppearanceAssetElement assetElem = m_document.GetElement(m_currentAppearanceAssetElementId) as AppearanceAssetElement;

            if (assetElem == null)
            {
                return(false);
            }

            Asset asset = assetElem.GetRenderingAsset();
            AssetPropertyDoubleArray4d tintColorProp = asset.FindByName("common_Tint_color") as AssetPropertyDoubleArray4d;
            Color tintColor = tintColorProp.GetValueAsColor();
            Color white     = new Color(255, 255, 255);

            return(!ColorsEqual(tintColor, white));
        }
        void FindTextureBitmapPaths(Document doc)
        {
            // Find materials
            FilteredElementCollector fec
                = new FilteredElementCollector(doc);

            fec.OfClass(typeof(Material));

            IEnumerable <Material> targetMaterials
                = fec.Cast <Material>().Where <Material>(mtl =>
                                                         targetMaterialNames.Contains(mtl.Name));

            foreach (Material material in targetMaterials)
            {
                // Get appearance asset for read
                ElementId appearanceAssetId = material
                                              .AppearanceAssetId;

                AppearanceAssetElement appearanceAssetElem
                    = doc.GetElement(appearanceAssetId)
                      as AppearanceAssetElement;

                Asset asset = appearanceAssetElem
                              .GetRenderingAsset();

                // Walk through all first level assets to find
                // connected Bitmap properties.  Note: it is
                // possible to have multilevel connected
                // properties with Bitmaps in the leaf nodes.
                // So this would need to be recursive.

                int size = asset.Size;
                for (int assetIdx = 0; assetIdx < size; assetIdx++)
                {
                    //AssetProperty aProperty = asset[assetIdx]; // 2018
                    AssetProperty aProperty = asset.Get(assetIdx); // 2019

                    if (aProperty.NumberOfConnectedProperties < 1)
                    {
                        continue;
                    }

                    // Find first connected property.
                    // Should work for all current (2018) schemas.
                    // Safer code would loop through all connected
                    // properties based on the number provided.

                    Asset connectedAsset = aProperty
                                           .GetConnectedProperty(0) as Asset;

                    // We are only checking for bitmap connected assets.

                    if (connectedAsset.Name == "UnifiedBitmapSchema")
                    {
                        // This line is 2018.1 & up because of the
                        // property reference to UnifiedBitmap
                        // .UnifiedbitmapBitmap.  In earlier versions,
                        // you can still reference the string name
                        // instead: "unifiedbitmap_Bitmap"

                        //AssetPropertyString path = connectedAsset[ // 2018
                        //  UnifiedBitmap.UnifiedbitmapBitmap]
                        //    as AssetPropertyString;

                        AssetPropertyString path = connectedAsset // 2019
                                                   .FindByName(UnifiedBitmap.UnifiedbitmapBitmap)
                                                   as AssetPropertyString;

                        // This will be a relative path to the
                        // built -in materials folder, addiitonal
                        // render appearance folder, or an
                        // absolute path.

                        TaskDialog.Show("Connected bitmap",
                                        String.Format("{0} from {2}: {1}",
                                                      aProperty.Name, path.Value,
                                                      connectedAsset.LibraryName));
                    }
                }
            }
        }
        void GetElementMaterialInfo(Document doc)
        {
            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .WhereElementIsNotElementType()
                  .OfClass(typeof(Material));

            try
            {
                foreach (Material material in collector)
                {
                    if (material.Name.Equals("Air"))
                    {
                        AppearanceAssetElement appearanceElement
                            = doc.GetElement(material.AppearanceAssetId)
                              as AppearanceAssetElement;

                        Asset appearanceAsset = appearanceElement
                                                .GetRenderingAsset();

                        List <AssetProperty> assetProperties
                            = new List <AssetProperty>();

                        PropertySetElement physicalPropSet
                            = doc.GetElement(material.StructuralAssetId)
                              as PropertySetElement;

                        PropertySetElement thermalPropSet
                            = doc.GetElement(material.ThermalAssetId)
                              as PropertySetElement;

                        ThermalAsset thermalAsset = thermalPropSet
                                                    .GetThermalAsset();

                        StructuralAsset physicalAsset = physicalPropSet
                                                        .GetStructuralAsset();

                        ICollection <Parameter> physicalParameters
                            = physicalPropSet.GetOrderedParameters();

                        ICollection <Parameter> thermalParameters
                            = thermalPropSet.GetOrderedParameters();

                        // Appearance Asset

                        for (int i = 0; i < appearanceAsset.Size; i++)
                        {
                            AssetProperty property = appearanceAsset[i];
                            assetProperties.Add(property);
                        }
                        foreach (AssetProperty assetProp in assetProperties)
                        {
                            Type   type           = assetProp.GetType();
                            object assetPropValue = null;
                            var    prop           = type.GetProperty("Value");
                            if (prop != null &&
                                prop.GetIndexParameters().Length == 0)
                            {
                                assetPropValue = prop.GetValue(assetProp);
                            }
                        }

                        // Physical (Structural) Asset

                        foreach (Parameter p in physicalParameters)
                        {
                            // Work with parameters here
                            // The only parameter not in the orderedParameters
                            // that is needed is the Asset name, which you
                            // can get by 'physicalAsset.Name'.
                        }

                        // Thermal Asset

                        foreach (Parameter p in thermalParameters)
                        {
                            //Work with parameters here
                            //The only parameter not in the orderedParameters
                            // that is needed is the Asset name, shich you
                            // can get by 'thermalAsset.Name'.
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        public static List <TextureBundle> GetTextureBundles(Document doc, out List <string> paths)
        {
            if (_bundleCache.ContainsKey(doc.PathName))
            {
                paths = _texturePathCache[doc.PathName];
                return(_bundleCache[doc.PathName]);
            }
            _texturePathCache.Add(doc.PathName, new List <string>());

            // Find materials
            FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(Material));

            // Convert materials to bundles
            List <TextureBundle> bundles = new List <TextureBundle>();

            foreach (var m in fec.Cast <Material>())
            {
                try
                {
                    var bundle = new TextureBundle(m);

                    ElementId appearanceAssetId = m.AppearanceAssetId;
                    AppearanceAssetElement appearanceAssetElem
                        = doc.GetElement(appearanceAssetId)
                          as AppearanceAssetElement;

                    if (appearanceAssetElem == null)
                    {
                        continue;
                    }

                    Asset asset = appearanceAssetElem
                                  .GetRenderingAsset();

                    if (asset == null)
                    {
                        continue;
                    }

                    for (int assetIdx = 0; assetIdx < asset.Size; assetIdx++)
                    {
                        AssetProperty aProperty = asset[assetIdx];
                        if (aProperty.NumberOfConnectedProperties < 1)
                        {
                            continue;
                        }

                        Asset connectedAsset = aProperty
                                               .GetConnectedProperty(0) as Asset;

                        // See if there is a path associated.
#if REVIT2018 || REVIT2019 || REVIT2020
                        // This line is 2018.1 & up because of the
                        // property reference to UnifiedBitmap
                        // .UnifiedbitmapBitmap.  In earlier versions,
                        // you can still reference the string name
                        // instead: "unifiedbitmap_Bitmap"
                        AssetPropertyString path = connectedAsset[
                            UnifiedBitmap.UnifiedbitmapBitmap]
                                                   as AssetPropertyString;
#else
                        AssetPropertyString path =
                            connectedAsset["unifiedbitmap_Bitmap"] as AssetPropertyString;
#endif
                        // If there is no asset path, nothing to pursue (Empty field)
                        if (path == null || String.IsNullOrEmpty(path.Value))
                        {
                            continue;
                        }

                        // See what kind of texture it is.
                        if (TryGetTextureTypeFromAssetName(connectedAsset.Name, out var t))
                        {
                            // This will be a relative path to the
                            // built -in materials folder, addiitonal
                            // render appearance folder, or an
                            // absolute path.
                            string assetName = Path.GetFileNameWithoutExtension(path.Value);

                            // Ensure that we have a valid texture path.
                            if (RevitTextures.ContainsKey(assetName))
                            {
                                bundle.TexturePaths.Add(t, new SafenedFilename(RevitTextures[assetName]));
                            }
                            else
                            {
                                //Logger.LogError(
                                //    $"Found asset outisde of Revit material lib: {path.Value}. Could not add to export"
                                //    );
                            }
                        }
                    }

                    // Return the bundle we created.
                    bundles.Add(bundle);
                }
                catch (Exception e)
                {
                    //Logger.LogException("Error in bundle creation: ", e);
                }
            }

            var bundleList = bundles.Where(b => b != null).ToList();
            _bundleCache.Add(doc.PathName, bundleList);
            paths = _texturePathCache[doc.PathName];

            return(bundleList);
        }
Beispiel #11
0
 public void OnMaterial(MaterialNode node)
 {
     matid = node.MaterialId.IntegerValue;
     if (!matLink.ContainsKey(matid))
     {
         StringBuilder log = new StringBuilder();
         XMaterial     mat = new XMaterial();
         Element       e   = Documents.Peek().GetElement(node.MaterialId);
         if (e is Material)
         {
             Material m = e as Material;
             mat.Name = m.Name;
             if (m.UseRenderAppearanceForShading)
             {
                 mat.Color = new XColor(1.0f, 1.0f, 1.0f, 1 - (float)node.Transparency);
             }
             else
             {
                 mat.Color = new XColor(m.Color.Red / 255f, m.Color.Green / 255f, m.Color.Blue / 255f, 1 - (float)node.Transparency);
             }
             mat.Specular  = XColor.white * (m.Smoothness / 100f);
             mat.Shininess = m.Shininess / 100f;
             Element _e = Documents.Peek().GetElement(m.AppearanceAssetId);
             if (EnableLog)
             {
                 log.Append("Material:" + m.Name + "\n");
                 log.Append("AppearanceAssetElement:" + (_e is AppearanceAssetElement).ToString() + "\n");
             }
             if (_e is AppearanceAssetElement)
             {
                 AppearanceAssetElement aae = _e as AppearanceAssetElement;
                 Asset a = aae.GetRenderingAsset();
                 if (EnableLog)
                 {
                     log.Append("Asset.Size:" + a.Size.ToString() + "\n");
                 }
                 if (a.Size > 0)
                 {
                     for (int i = 0; i < a.Size; i++)
                     {
                         if (EnableLog)
                         {
                             LogMaterial(a[i], log);
                         }
                         XMapping t = ReadTexture(a[i]);
                         if (t != null)
                         {
                             mat.Maps.Add(t);
                         }
                     }
                 }
             }
         }
         else
         {
             mat.Name      = node.NodeName;
             mat.Color     = new XColor(node.Color.Red / 255f, node.Color.Green / 255f, node.Color.Blue / 255f, 1 - (float)node.Transparency);
             mat.Specular  = new XColor(0, 0, 0, 1);
             mat.Shininess = 0f;
         }
         matLog.Add(log.ToString());
         matLink.Add(matid, XData.Materials.Count);
         XData.Materials.Add(mat);
     }
 }
Beispiel #12
0
        public void OnMaterial(MaterialNode node)
        {
            currentTransparencyDouble = node.Transparency;
            currentColor           = node.Color;
            currentShiniess        = node.Glossiness;
            currentTransparencyint = Convert.ToInt32(node.Transparency);


            if (node.MaterialId != ElementId.InvalidElementId)
            {
                Asset theAsset = node.GetAppearance();
                if (node.HasOverriddenAppearance)
                {
                    theAsset = node.GetAppearanceOverride();
                }
                if (theAsset == null)
                {
                    //Element m = _doc.GetElement(node.MaterialId);
                    Material  material     = _doc.GetElement(node.MaterialId) as Material;
                    ElementId appearanceId = material.AppearanceAssetId;
                    AppearanceAssetElement appearanceElem = _doc.GetElement(appearanceId) as AppearanceAssetElement;
                    theAsset = appearanceElem.GetRenderingAsset();
                }


                if (theAsset.Size == 0)
                {
                    //TaskDialog.Show("revit","欧特克材质");
                    foreach (Asset objCurrentAsset in _objlibraryAsset)
                    {
                        if (objCurrentAsset.Name == theAsset.Name && objCurrentAsset.LibraryName == theAsset.LibraryName)
                        {
                            //var theValue = objCurrentAsset.Type.ToString();
                            ReadAsset(objCurrentAsset);
                            //TaskDialog.Show("欧特克材质", theValue);
                        }
                    }
                }
                else
                {
                    ReadAsset(theAsset);
                }



                //AssetProperty aProperty = theAsset[assetIdx];
                //if (aProperty.NumberOfConnectedProperties < 1)
                //    continue;
                //// Find first connected property.
                //// Should work for all current (2018) schemas.
                //// Safer code would loop through all connected
                //// properties based on the number provided.
                //Asset connectedAsset = aProperty.GetConnectedProperty(0) as Asset;
                //// We are only checking for bitmap connected assets.
                //if (connectedAsset.Name == "UnifiedBitmapSchema")
                //{
                //    // This line is 2018.1 & up because of the
                //    // property reference to UnifiedBitmap
                //    // .UnifiedbitmapBitmap. In earlier versions,
                //    // you can still reference the string name
                //    // instead: "unifiedbitmap_Bitmap"
                //    AssetPropertyString path = connectedAsset["unifiedbitmap_Bitmap"] as AssetPropertyString;
                //    // This will be a relative path to the
                //    // built -in materials folder, addiitonal
                //    // render appearance folder, or an
                //    // absolute path.
                //    TaskDialog.Show("Connected bitmap", String.Format("{0} from {2}: {1}", aProperty.Name, path.Value, connectedAsset.LibraryName));
            }

            if (currentMterialId != node.MaterialId)
            {
                var trgb = Util.ColorTransparencyToInt(currentColor, currentTransparencyint);
                face.Add(-1);
                face.Add(trgb);
                face.Add(currentTransparencyint);
                face.Add(-2);
                face.Add(-2);
                face.Add(-2);
                face.Add(-2);
                face.Add(-2);
                face.Add(-2);
                currentMterialId = node.MaterialId;


                var ttrgb = Util.ColorTransparencyString(currentColor, currentTransparencyint);

                if (!transparencys.ContainsKey(ttrgb))
                {
                    transparencys.Add(ttrgb, 1.0 - currentTransparencyDouble);
                }

                if (!colors.ContainsKey(ttrgb))
                {
                    colors.Add(ttrgb, currentColor);
                }
            }
            else
            {
                if (materialIndex == 0)
                {
                    var trgb = Util.ColorTransparencyToInt(currentColor, currentTransparencyint);
                    face.Add(-1);
                    face.Add(trgb);
                    face.Add(currentTransparencyint);
                    face.Add(-2);
                    face.Add(-2);
                    face.Add(-2);
                    face.Add(-2);
                    face.Add(-2);
                    face.Add(-2);
                    currentMterialId = node.MaterialId;
                    var ttrgb = Util.ColorTransparencyString(currentColor, currentTransparencyint);
                    colors.Add(ttrgb, currentColor);
                    transparencys.Add(ttrgb, currentTransparencyint);
                }
            }
            materialIndex++;
        }
Beispiel #13
0
        public Message Execute(Document doc, Message msg)
        {
            JObject msgData   = JObject.Parse(msg.Data);
            string  elementId = msgData["Id"].ToString();

            Material mat = doc.GetElement(new ElementId(Int32.Parse(elementId))) as Material;

            try
            {
                System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
                s.Start();

                LMAStudio.StreamVR.Common.Models.Material dto = _converter.ConvertToDTO(mat).ToObject <LMAStudio.StreamVR.Common.Models.Material>();

                AppearanceAssetElement assetElement = doc.GetElement(mat.AppearanceAssetId) as AppearanceAssetElement;
                Asset asset = assetElement?.GetRenderingAsset();

                if (asset == null)
                {
                    return(new Message
                    {
                        Type = "EMPTY",
                        Data = $"No material asset found for: {mat.Name} ({mat.Id})"
                    });
                }

                string bmpPathFull = "";

                for (int i = 0; i < asset.Size; i++)
                {
                    AssetProperty prop = asset.Get(i);
                    if (textureProperties.Contains(prop.Name) && prop.NumberOfConnectedProperties > 0)
                    {
                        Asset connectedAsset = prop.GetSingleConnectedAsset();
                        for (int j = 0; j < connectedAsset.Size; j++)
                        {
                            AssetProperty prop2 = connectedAsset.Get(j);
                            if (prop2.Name == "unifiedbitmap_Bitmap")
                            {
                                bmpPathFull = (prop2 as AssetPropertyString).Value;
                            }
                        }
                    }
                }

                if (string.IsNullOrEmpty(bmpPathFull))
                {
                    return(new Message
                    {
                        Type = "EMPTY",
                        Data = $"No exportable material found for: {mat.Name} ({mat.Id})"
                    });
                }

                string texturesDirectory = "C:\\Program Files (x86)\\Common Files\\Autodesk Shared\\Materials\\Textures";
                string bmpPath           = bmpPathFull.Split('|').LastOrDefault();

                string fullPath         = texturesDirectory + "\\" + bmpPath;
                string materialFileName = new FileInfo(fullPath).Name;

                byte[] materialAlbedo = File.ReadAllBytes(fullPath);

                UploadOBJ(dto, materialAlbedo, materialFileName);

                _log($"Export/Upload time for {1} materials: {s.ElapsedMilliseconds}ms");
                s.Stop();

                return(new Message
                {
                    Type = "MAT",
                    Data = mat.Id.ToString()
                });
            }
            catch (Exception e)
            {
                return(new Message
                {
                    Type = "ERROR",
                    Data = $"Error: {mat.Name} ({mat.Id}) {e.ToString()}"
                });
            }
        }
Beispiel #14
0
        IList <string> GetAssetPropValueFromMaterial(AppearanceAssetElement currentAppearance, IList <string> targetList)
        {
            IList <string> valuesToReturn = new List <string>();

            if (currentAppearance != null)
            {
                Asset thisAsset = currentAppearance.GetRenderingAsset();
                if (thisAsset != null)
                {
                    for (int i = 0; i < thisAsset.Size; i++)
                    {
                        AssetProperty currentProp = thisAsset[i];

                        if (currentProp != null)
                        {
                            AssetPropertyString currentPropString = currentProp as AssetPropertyString;
                            if (currentPropString != null)
                            {
                                if (currentPropString.Value != null && currentPropString.Value != "")
                                {
                                    CheckStringAValidTexturePathCorrectItAndAddToList(currentPropString.Value, targetList);
                                }
                            }
                        }

                        IList <AssetProperty> allProp = currentProp.GetAllConnectedProperties();

                        if (allProp != null && allProp.Count > 0)
                        {
                            foreach (AssetProperty currentConnectedProp in allProp)
                            {
#if R2016 || R2017
                                if (currentConnectedProp.Type == AssetPropertyType.APT_Asset)
                                {
                                    Asset currentConnectedAsset = currentConnectedProp as Asset;
                                    if (currentConnectedAsset != null)
                                    {
                                        for (int j = 0; j < currentConnectedAsset.Size; j++)
                                        {
                                            AssetProperty currentConnectedAssetProp = currentConnectedAsset[j];
                                            if (currentConnectedAssetProp != null)
                                            {
                                                AssetPropertyString currentConnectedAssetPropString = currentConnectedAssetProp as AssetPropertyString;
                                                if (currentConnectedAssetPropString != null)
                                                {
                                                    if (currentConnectedAssetPropString.Value != null && currentConnectedAssetPropString.Value != "")
                                                    {
                                                        CheckStringAValidTexturePathCorrectItAndAddToList(currentConnectedAssetPropString.Value, targetList);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
#else
                                if (currentConnectedProp.Type == AssetPropertyType.Asset)
                                {
                                    Asset currentConnectedAsset = currentConnectedProp as Asset;
                                    if (currentConnectedAsset != null)
                                    {
                                        for (int j = 0; j < currentConnectedAsset.Size; j++)
                                        {
                                            AssetProperty currentConnectedAssetProp = currentConnectedAsset[j];
                                            if (currentConnectedAssetProp != null)
                                            {
                                                AssetPropertyString currentConnectedAssetPropString = currentConnectedAssetProp as AssetPropertyString;
                                                if (currentConnectedAssetPropString != null)
                                                {
                                                    if (currentConnectedAssetPropString.Value != null && currentConnectedAssetPropString.Value != "")
                                                    {
                                                        CheckStringAValidTexturePathCorrectItAndAddToList(currentConnectedAssetPropString.Value, targetList);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
#endif
                            }
                        }
                    }
                }
            }
            return(valuesToReturn);
        }
        public static Assimp.Material ConvertToAssimpMaterial(TextureBundle bundle, Document doc)
        {
            // Create new material with base props
            // from the Revit material
            var newmat = new Assimp.Material()
            {
                Opacity      = bundle.Material.GetOpacity(),
                Reflectivity = 0f,
                Name         = bundle.Material.Name,
                ColorDiffuse = bundle.Material.ToColor4D()
            };

            // Extract base properties from revit material
            ElementId appearanceAssetId            = bundle.Material.AppearanceAssetId;
            AppearanceAssetElement appearanceAsset = doc.GetElement(appearanceAssetId) as AppearanceAssetElement;
            Asset renderingAsset = appearanceAsset.GetRenderingAsset();
            RenderAppearanceDescriptor rad
                = new RenderAppearanceDescriptor(renderingAsset);
            PropertyDescriptorCollection collection          = rad.GetProperties();
            List <PropertyDescriptor>    orderableCollection = new List <PropertyDescriptor>(collection.Count);

            List <string> allPropNames = orderableCollection.Select(f => f.Name).ToList();

            foreach (PropertyDescriptor descr in collection)
            {
                orderableCollection.Add(descr);
                switch (descr.Name)
                {
                    #region Notes

                    // The commented out properties aren't in use yet,
                    // but do work with revit materials as expected.

                    //case "texture_UScale":
                    //    var uScale = renderingAsset["texture_UScale"] as AssetPropertyDouble;
                    //    break;
                    //case "texture_VScale":
                    //    break;
                    //case "texture_UOffset":
                    //    break;
                    //case "texture_VOffset":
                    //    break;
                    //case "texture_RealWorldScaleX":
                    //    var xScale = renderingAsset["texture_RealWorldScaleX"] as AssetPropertyDistance;
                    //    break;
                    //case "texture_RealWorldScaleY":
                    //    break;

                    #endregion

                case "generic_diffuse":
                    var prop = renderingAsset.GetAssetProperty <AssetPropertyDoubleArray4d>("generic_diffuse");
                    newmat.ColorDiffuse = ColorFromAssetDoubleArray4d(prop);
                    break;

                case "glazing_reflectance":
                    // This is glass, so we should reduce the transparency.
                    var refl = renderingAsset.GetAssetProperty <AssetPropertyDouble>("glazing_reflectance");
                    if (refl == null)
                    {
                        var reflFloat = renderingAsset.GetAssetProperty <AssetPropertyFloat>("glazing_reflectance");
                        newmat.Reflectivity = reflFloat?.Value ?? 0f;
                    }
                    else
                    {
                        newmat.Reflectivity = (float)refl.Value;
                    }
                    newmat.Opacity = Math.Abs(0f - newmat.Reflectivity);
                    break;

                case "common_Tint_color":
                    // Tint shouldn't be used if generic diffuse is set
                    if (
                        renderingAsset.GetAssetProperty <AssetPropertyDoubleArray4d>("generic_diffuse") != null
                        )
                    {
                        continue;
                    }
                    var tintProp = renderingAsset.GetAssetProperty <AssetPropertyDoubleArray4d>("common_Tint_color");
                    newmat.ColorDiffuse = ColorFromAssetDoubleArray4d(tintProp);
                    break;

                default:
                    break;
                }
            }

            // Set textures
            foreach (var tx in bundle.TexturePaths)
            {
                // Get the filename
                var txFileName = tx.Value.SafeFileName;
                if (tx.Key == RevitTextureType.Color)
                {
                    newmat.TextureDiffuse = new TextureSlot(
                        $"Textures/{txFileName}",
                        TextureType.Diffuse,
                        0,    // Texture index in the material
                        TextureMapping.Box,
                        0,    //
                        0.5f, // Blend mode
                        TextureOperation.Add,
                        TextureWrapMode.Clamp,
                        TextureWrapMode.Clamp,
                        0 // Flags,
                        );
                }
                else if (tx.Key == RevitTextureType.Bump)
                {
                    newmat.TextureHeight = new TextureSlot(
                        $"Textures/{txFileName}",
                        TextureType.Diffuse,
                        0,    // Texture index in the material
                        TextureMapping.Box,
                        0,    //
                        0.5f, // Blend mode
                        TextureOperation.Add,
                        TextureWrapMode.Clamp,
                        TextureWrapMode.Clamp,
                        0 // Flags,
                        );
                }
            }
            return(newmat);
        }
Beispiel #16
0
 public static AppearanceAssetElement Duplicate(this AppearanceAssetElement element, string name)
 {
     return(AppearanceAssetElement.Create(element.Document, name, element.GetRenderingAsset()));
 }
    public List <BIM_Service.Material> Get(string elementID)
    {
        try
        {
            Document doc;
            if (ModelService.Service.IsActive)
            {
                doc = ModelService.Service.RvtDoc;
            }
            else if (TCPServer.Server.IsActive)
            {
                doc = TCPServer.Server.RvtDoc;
            }
            else
            {
                throw new Exception("Server not running...");
            }


            Element element = doc.GetElement(new ElementId(Convert.ToInt32(elementID)));

            List <BIM_Service.Material> materialsList = new List <BIM_Service.Material>();

            ICollection <ElementId> mats = element.GetMaterialIds(false);

            foreach (ElementId el in mats)
            {
                Material mat = (Material)doc.GetElement(el);

                AppearanceAssetElement appearance = (AppearanceAssetElement)doc.GetElement(mat.AppearanceAssetId);

                Asset theAsset = appearance.GetRenderingAsset();
                BIM_Service.Material elementMat = new BIM_Service.Material();

                //TODO: Use Appearance/Graphics properties

                //if (!mat.UseRenderAppearanceForShading)
                //{
                elementMat.name  = mat.Name;
                elementMat.id    = mat.Id.IntegerValue;
                elementMat.color = "[" +
                                   mat.Color.Red.ToString() + "," +
                                   mat.Color.Green.ToString() + "," +
                                   mat.Color.Blue.ToString() + "," +
                                   mat.Transparency.ToString() + "]";

                elementMat.shininess = mat.Shininess.ToString();
                elementMat.smothness = mat.Smoothness.ToString();
                //}
                //else
                //{
                //    elementMat.name = theAsset.Name;

                //    elementMat.id = theAsset.Id.IntegerValue;
                //    elementMat.color = "[" +
                //        theAsset.Color.Red.ToString() + "," +
                //        theAsset.Color.Green.ToString() + "," +
                //        theAsset.Color.Blue.ToString() + "," +
                //        theAsset.Transparency.ToString() + "]";

                //    elementMat.shininess = theAsset.Shininess.ToString();
                //    elementMat.smothness = theAsset.Smoothness.ToString();
                //}



                materialsList.Add(elementMat);
            }

            return(materialsList);
        }
        catch (Exception e)
        {
            TaskDialog.Show("Error", e.Message);
        }
        return(null);
    }