예제 #1
0
파일: Profile.cs 프로젝트: AMEE/revit
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="elem">Selected element</param>
        /// <param name="commandData">ExternalCommandData</param>
        public Profile(Autodesk.Revit.DB.Element elem, ExternalCommandData commandData)
        {
            m_dataProfile = elem;
            m_commandData = commandData;
            m_appCreator = m_commandData.Application.Application.Create;
            m_docCreator = m_commandData.Application.ActiveUIDocument.Document.Create;

            List<List<Edge>> faces = GetFaces(m_dataProfile);
            m_face = GetNeedFace(faces);
        }
예제 #2
0
파일: ParameterUtil.cs 프로젝트: AMEE/revit
        /// <summary>
        /// set certain parameter of given element to int value
        /// </summary>
        /// <param name="elem">given element</param>
        /// <param name="paraIndex">BuiltInParameter</param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SetParaInt(Element elem, BuiltInParameter paraIndex, int value)
        {
            Parameter para = elem.get_Parameter(paraIndex);
            if (null == para)
            {
                return false;
            }

            para.Set(value);
            return true;
        }
예제 #3
0
 //class constructor (takes Revit Element as argument)
 public Revit_Geometry_Worker(Autodesk.Revit.DB.Element objElement, String sSceneFilepath,Document cDoc)
 {
     try
     {
         vRevitElement = objElement;
         vOutputFilePath = sSceneFilepath;
         vDoc = cDoc;
     }
     catch (Exception)
     {
         System.Windows.Forms.MessageBox.Show("Error in module Revit_Geometry_Worker (Class Constructor)");
         throw;
     }
 }
예제 #4
0
        private static IEnumerable <Autodesk.Revit.DB.View> FindAllViewsWhereElementIsVisible(
            Autodesk.Revit.DB.Element element)
        {
            Document           doc = element.Document;
            IEnumerable <View> relevantViewList = FindAllViewsThatCanDisplayElements(doc);

            ElementId idToCheck = element.Id;

            return(
                from v in relevantViewList
                let idList
                    = new FilteredElementCollector(doc, v.Id)
                      .WhereElementIsNotElementType()
                      .ToElementIds()
                      where idList.Contains(idToCheck)
                      select v);
        }
예제 #5
0
        /// <summary>
        /// Determines if the selected element meets extra criteria for export.
        /// </summary>
        /// <param name="exporterIFC">The exporter class.</param>
        /// <param name="element">The current element to export.</param>
        /// <param name="allowSeparateOpeningExport">True if IfcOpeningElement is allowed to be exported.</param>
        /// <returns>True if the element should be exported, false otherwise.</returns>
        public static bool CanExportElement(ExporterIFC exporterIFC, Autodesk.Revit.DB.Element element, bool allowSeparateOpeningExport)
        {
            if (!ElementFilteringUtil.ShouldElementBeExported(exporterIFC, element, allowSeparateOpeningExport))
            {
                return(false);
            }

            // if we allow exporting parts as independent building elements, then prevent also exporting the host elements containing the parts.
            bool checkIfExportingPart = ExporterCacheManager.ExportOptionsCache.ExportPartsAsBuildingElements || element is Part;

            if (checkIfExportingPart && PartExporter.CanExportParts(element))
            {
                return(false);
            }

            return(true);
        }
예제 #6
0
        public static Autodesk.Revit.DB.GeometryElement GetGeometry(this Autodesk.Revit.DB.Element element, ViewDetailLevel viewDetailLevel, out Options options)
        {
            options = new Options {
                ComputeReferences = true, DetailLevel = viewDetailLevel
            };
            var geometry = element.get_Geometry(options);

            if (!(geometry?.Any() ?? false) && element is GenericForm form && !form.Combinations.IsEmpty)
            {
                geometry.Dispose();

                options.IncludeNonVisibleObjects = true;
                return(element.get_Geometry(options));
            }

            return(geometry);
        }
예제 #7
0
        private List <Rhino.Geometry.Brep> GetCompoundStructureLayerGeom(DB.Element element)
        {
            var layerGeoms = new List <Rhino.Geometry.Brep>();
            var elementIds = new List <DB.ElementId>()
            {
                element.Id
            };

            if (DB.PartUtils.AreElementsValidForCreateParts(element.Document, elementIds))
            {
                try
                {
                    // start a dry transaction that will be rolled back automatically
                    // when execution goes out of next using statment
                    using (var transaction = new DB.Transaction(element.Document, nameof(GetCompoundStructureLayerGeom)))
                    {
                        transaction.Start();

                        // explode the element into parts
                        DB.PartUtils.CreateParts(element.Document, elementIds);
                        element.Document.Regenerate();

                        // get the exploded parts
                        foreach (DB.ElementId partId in DB.PartUtils.GetAssociatedParts(element.Document, element.Id, includePartsWithAssociatedParts: true, includeAllChildren: true))
                        {
                            if (element.Document.GetElement(partId) is DB.Element part)
                            {
                                using (var options = new DB.Options())
                                {
                                    // extract geometry for each part
                                    if (part.get_Geometry(options) is DB.GeometryElement partGeom)
                                    {
                                        foreach (DB.GeometryObject geom in partGeom)
                                        {
                                            layerGeoms.AddRange(geom.ToGeometryBaseMany().Cast <Rhino.Geometry.Brep>());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch {}
            }
            return(layerGeoms);
        }
예제 #8
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DB.Element element = null;
            if (!DA.GetData("Element", ref element))
            {
                return;
            }

            var inverted = false;

            if (!DA.GetData("Inverted", ref inverted))
            {
                return;
            }

            DA.SetData("Filter", new DB.ElementIntersectsElementFilter(element, inverted));
        }
예제 #9
0
        /// <summary>
        /// Retrieve the ViewPlan corresponding to the door's level.
        /// </summary>
        /// <param name="door">
        /// one door whose level is corresponding to the retrieved ViewPlan.
        /// </param>
        /// <returns>One ViewPlan</returns>
        static private ViewPlan GetPlanform2DView(Autodesk.Revit.DB.Element door)
        {
            IEnumerable <ViewPlan> viewPlans = from elem in
                                               new FilteredElementCollector(door.Document).OfClass(typeof(ViewPlan)).ToElements()
                                               let viewPlan = elem as ViewPlan
                                                              where viewPlan != null && !viewPlan.IsTemplate && viewPlan.GenLevel.Id.IntegerValue == door.LevelId.IntegerValue
                                                              select viewPlan;

            if (viewPlans.Count() > 0)
            {
                return(viewPlans.First());
            }
            else
            {
                return(null);
            }
        }
예제 #10
0
        void ReconstructBuildingPadByOutline
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            IList <Rhino.Geometry.Curve> boundaries,
            Optional <Autodesk.Revit.DB.BuildingPadType> type,
            Optional <Autodesk.Revit.DB.Level> level
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            boundaries = boundaries.Select(x => x.ChangeUnits(scaleFactor)).ToArray();

            var boundaryBBox = Rhino.Geometry.BoundingBox.Empty;

            foreach (var boundary in boundaries)
            {
                boundaryBBox.Union(boundary.GetBoundingBox(true));
            }

            SolveOptionalType(ref type, doc, ElementTypeGroup.BuildingPadType, (document, param) => BuildingPadType.CreateDefault(document), nameof(type));

            SolveOptionalLevel(ref level, doc, boundaryBBox.Min.Z, nameof(level));

            var curveLoops = boundaries.Select(region => CurveLoop.Create(region.ToHostMultiple().SelectMany(x => x.ToBoundedCurves()).ToList()));

            // Type
            ChangeElementTypeId(ref element, type.Value.Id);

            if (element is BuildingPad buildingPad)
            {
                buildingPad.SetBoundary(curveLoops.ToList());
            }
            else
            {
                ReplaceElement(ref element, BuildingPad.Create(doc, type.Value.Id, level.Value.Id, curveLoops.ToList()));
            }

            if (element != null)
            {
                element.get_Parameter(BuiltInParameter.TYPE_WALL_CLOSURE).Set(level.Value.Id);
                element.get_Parameter(BuiltInParameter.LEVEL_PARAM).Set(level.Value.Id);
                element.get_Parameter(BuiltInParameter.BUILDINGPAD_HEIGHTABOVELEVEL_PARAM).Set(boundaryBBox.Min.Z - level.Value.Elevation);
            }
        }
예제 #11
0
        // TBD: as of 04/10/07 - only works on App startup, not dynamically from another command (jma)

        /*public void
         * AddMenu()
         * {
         *  MenuItem rootMenu = m_revitApp.CreateTopMenu("RevitLookup Test Menu Item");
         *
         *  bool success = rootMenu.AddToExternalTools();
         *  if (success) {
         *      MenuItem subItem = rootMenu.Append(MenuItem.MenuType.BasicMenu, "Pick me to call back into RevitLookup", "RevitLookup.dll", "CmdSampleMenuItemCallback");
         *      System.Windows.Forms.MessageBox.Show("Successfully added new menu to the External Tools menu.  Pick the item to demonstrate callback.");
         *  }
         *  else
         *      System.Windows.Forms.MessageBox.Show("Could not add new menu!");
         * }
         *
         * public void
         * AddToolbar()
         * {
         *  Toolbar toolBar = m_revitApp.CreateToolbar();
         *  toolBar.Name = "Jimbo";
         *
         *  if (toolBar != null) {
         *      ToolbarItem tbItem = toolBar.AddItem("RevitLookup.dll", "CmdSampleMenuItemCallback");
         *      System.Windows.Forms.MessageBox.Show("Successfully added new toolbar.  Pick the item to demonstrate callback.");
         *  }
         *  else
         *      System.Windows.Forms.MessageBox.Show("Could not add new toolbar!");
         * }*/

        public void SelectElement()
        {
            Autodesk.Revit.UI.Selection.Selection selSet = m_revitApp.ActiveUIDocument.Selection;

            try
            {
                Autodesk.Revit.DB.Element    elem    = m_revitApp.ActiveUIDocument.Document.GetElement(selSet.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element).ElementId);
                Autodesk.Revit.DB.ElementSet elemSet = m_revitApp.Application.Create.NewElementSet();
                elemSet.Insert(elem);
                Snoop.Forms.Objects form = new Snoop.Forms.Objects(elemSet);
                form.ShowDialog();
            }
            catch (System.Exception)
            {
                System.Windows.Forms.MessageBox.Show("Didn't pick one!");
            }
        }
예제 #12
0
        protected void PipeHostParameter <T>(IGH_DataAccess DA, DB.Element srcElement, DB.BuiltInParameter srcParam, string paramName) where T : Types.GH_Enumerate, new()
        {
            if (srcElement is null)
            {
                DA.SetData(paramName, null);
                return;
            }

            var param = srcElement.get_Parameter(srcParam);

            if (param != null && param.StorageType == DB.StorageType.Integer)
            {
                var enumType = new T();
                enumType.Value = param.AsInteger();
                DA.SetData(paramName, enumType);
            }
        }
예제 #13
0
        /// <summary>
        /// constructor
        /// </summary>
        public ObjectViewer()
        {
            UIDocument doc       = Command.CommandData.Application.ActiveUIDocument;
            ElementSet selection = doc.Selection.Elements;

            // only one element should be selected
            if (0 == selection.Size)
            {
                throw new ErrorMessageException("Please select an element.");
            }

            if (1 < selection.Size)
            {
                throw new ErrorMessageException("Please select only one element.");
            }
            // get selected element
            foreach (Element e in selection)
            {
                m_selected = e;
            }
            // get current view and all views
            m_currentView = doc.Document.ActiveView;
            FilteredElementIterator itor = (new FilteredElementCollector(doc.Document)).OfClass(typeof(View)).GetElementIterator();

            itor.Reset();
            while (itor.MoveNext())
            {
                View view = itor.Current as View;
                // Skip view templates because they're invisible in project browser, invalid for geometry elements
                if (null != view && !view.IsTemplate)
                {
                    m_allViews.Add(view);
                }
            }

            // create a instance of Sketch3D
            GeometryData geomFactory = new GeometryData(m_selected, m_currentView);

            m_currentSketch3D = new Sketch3D(geomFactory.Data3D, Graphics2DData.Empty);

            //get a instance of ParametersFactory and then use it to create Parameters
            ParasFactory parasFactory = new ParasFactory(m_selected);

            m_paras = parasFactory.CreateParas();
        }
예제 #14
0
        void ReconstructBeamByCurve
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            Rhino.Geometry.Curve curve,
            Optional <Autodesk.Revit.DB.FamilySymbol> type,
            Optional <Autodesk.Revit.DB.Level> level
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            if
            (
                scaleFactor != 1.0 ? !curve.Scale(scaleFactor) : true &&
                curve.IsShort(Revit.ShortCurveTolerance) ||
                curve.IsClosed ||
                !curve.TryGetPlane(out var axisPlane, Revit.VertexTolerance) ||
                curve.GetNextDiscontinuity(Rhino.Geometry.Continuity.C1_continuous, curve.Domain.Min, curve.Domain.Max, out double discontinuity)
            )
            {
                ThrowArgumentException(nameof(curve), "Curve must be a C1 continuous planar non closed curve.");
            }

            SolveOptionalType(ref type, doc, BuiltInCategory.OST_StructuralFraming, nameof(type));

            if (!type.Value.IsActive)
            {
                type.Value.Activate();
            }

            SolveOptionalLevel(ref level, doc, curve, nameof(level));

            var curves = curve.ToHost().ToList();

            Debug.Assert(curves.Count == 1);
            var centerLine = curves[0];

            // Type
            ChangeElementTypeId(ref element, type.Value.Id);

            if (element is FamilyInstance && element.Location is LocationCurve locationCurve && centerLine.IsSameKindAs(locationCurve.Curve))
            {
                locationCurve.Curve = centerLine;
            }
예제 #15
0
        public static object Create(global::Revit.Elements.Views.Sheet sheet, global::Revit.Elements.Element view, Autodesk.DesignScript.Geometry.Point location)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //obtain the element id from the sheet
            ElementId sheetId = new ElementId(sheet.Id);

            Autodesk.Revit.DB.Element result = null;
            //change the dynamo point to a revit point
            var revitPoint = location.ToRevitType(true);
            //obtain the element id from the view
            ElementId viewId = new ElementId(view.Id);



            try
            {
                //start the transaction to place views
                TransactionManager.Instance.EnsureInTransaction(doc);
                if (view.InternalElement.ToString() == "Autodesk.Revit.DB.ViewSchedule")
                {
                    result = Autodesk.Revit.DB.ScheduleSheetInstance.Create(doc, sheetId, viewId, revitPoint);
                }
                else
                {
                    result = Autodesk.Revit.DB.Viewport.Create(doc, sheetId, viewId, revitPoint);
                }

                TransactionManager.Instance.TransactionTaskDone();

                return(result.ToDSType(true));
            }
            catch (Exception e)
            {
                if (!Autodesk.Revit.DB.Viewport.CanAddViewToSheet(doc, sheetId, viewId))
                {
                    return("Error: View " + view.Id + " cannot be added to the sheet because it is already on another sheet.");
                }
                if (result == null)
                {
                    return("Error: View " + view.Id + " cannot be added to the sheet because it is empty.");
                }

                return("Error: View " + view.Id + e.Message);
            }
        }
예제 #16
0
        public Base LocationToSpeckle(DB.Element revitElement)
        {
            if (revitElement is FamilyInstance familyInstance)
            {
                //vertical columns are point based, and the point does not reflect the actual vertical location
                if (Categories.columnCategories.Contains(familyInstance.Category) ||
                    familyInstance.StructuralType == StructuralType.Column)
                {
                    return(TryGetLocationAsCurve(familyInstance));
                }
            }

            var revitLocation = revitElement.Location;

            switch (revitLocation)
            {
            case LocationCurve locationCurve:
            {
                var curve = locationCurve.Curve;

                //apply revit offset as transfrom
                if (revitElement is DB.Wall)
                {
                    var       offset = revitElement.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).AsDouble();
                    XYZ       vector = new XYZ(0, 0, offset);
                    Transform tf     = Transform.CreateTranslation(vector);
                    curve = curve.CreateTransformed(tf);
                }

                return(CurveToSpeckle(curve) as Base);
            }

            case LocationPoint locationPoint:
            {
                return(PointToSpeckle(locationPoint.Point));
            }

            // TODO what is the correct way to handle this?
            case null:
                return(null);

            default:
                return(null);
            }
        }
예제 #17
0
//set specified parameter as element ID for the given element
        public static bool setParameterValueAsID(Autodesk.Revit.DB.Element curElem, string paramName, ElementId newValue)
        {
            bool functionReturnValue = false;

            Autodesk.Revit.DB.Parameter curParam = curElem.GetParameters(paramName).First();

            try {
                curParam.Set(newValue);
                return(true);
                //return functionReturnValue;
            } catch (Exception ex) {
                //error
                TaskDialog.Show("Error", "Could not change parameter value");
            }

            return(false);
            //return functionReturnValue;
        }
예제 #18
0
        void ReconstructDirectShapeByGeometry
        (
            Document doc,
            ref Autodesk.Revit.DB.Element element,

            [Optional] string name,
            Optional <Autodesk.Revit.DB.Category> category,
            IList <IGH_GeometricGoo> geometry,
            [Optional] IList <Autodesk.Revit.DB.Material> material
        )
        {
            var scaleFactor = 1.0 / Revit.ModelUnits;

            SolveOptionalCategory(ref category, doc, BuiltInCategory.OST_GenericModel, nameof(geometry));

            if (element is DirectShape ds && ds.Category.Id == category.Value.Id)
            {
            }
예제 #19
0
        internal void AssertValidSpeckleElement(DB.Element elem, Base spkElem)
        {
            Assert.NotNull(elem);
            Assert.NotNull(spkElem);
            Assert.NotNull(spkElem["parameters"]);
            Assert.NotNull(spkElem["elementId"]);

            // HACK: This is not reliable or acceptable as a testing strategy.
            if (!(elem is DB.Architecture.Room || elem is DB.Mechanical.Duct || AdaptiveComponentInstanceUtils.IsAdaptiveComponentInstance(elem as FamilyInstance)))
            {
                Assert.Equal(elem.Name, spkElem["type"]);
            }

            //Assert.NotNull(spkElem.baseGeometry);

            //Assert.NotNull(spkElem.level);
            //Assert.NotNull(spkRevit.displayMesh);
        }
예제 #20
0
파일: Command.cs 프로젝트: alexberd/igraph
 static void setParameterOfElement(Autodesk.Revit.DB.Element i, String p, String f)
 {
     foreach (Autodesk.Revit.DB.Parameter para in i.Parameters)
     {
         if (para.Definition.Name == p)
         {
             //return para.AsString();
             //using (Transaction t = new Transaction(doc, "Set Parameter"))
             {
                 //t.Start();
                 para.Set(f);
                 //return;
                 ///t.Commit();
             }
         }
     }
     //return null;
 }
예제 #21
0
        internal void AssertValidSpeckleElement(DB.Element elem, Base spkElem)
        {
            Assert.NotNull(elem);
            Assert.NotNull(spkElem);
            Assert.NotNull(spkElem["parameters"]);
            Assert.NotNull(spkElem["elementId"]);


            if (!(elem is DB.Architecture.Room || elem is DB.Mechanical.Duct))
            {
                Assert.Equal(elem.Name, spkElem["type"]);
            }

            //Assert.NotNull(spkElem.baseGeometry);

            //Assert.NotNull(spkElem.level);
            //Assert.NotNull(spkRevit.displayMesh);
        }
예제 #22
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Autodesk.Revit.DB.Element element = null;
            if (!DA.GetData(ObjectType.Name, ref element))
            {
                return;
            }

            var options = new Options {
                ComputeReferences = true
            };

            using (var geometry = element.get_Geometry(options))
            {
                var list = geometry.ToRhino().Where(x => x != null).ToList();
                DA.SetDataList("Geometry", list);
            }
        }
예제 #23
0
        /// <summary>
        /// store the selected element and its corresponding BCs
        /// </summary>
        /// <param name="element"> use selected element in Revit UI(the host element)</param>
        private void SetBCHostMap(Autodesk.Revit.DB.Element element)
        {
            // set the Host element with current selected element
            m_hostElement = element;
            // retrieve the Document in which the Element resides.
            Document doc = element.Document;

            IEnumerable <Autodesk.Revit.DB.BoundaryConditions> boundaryConditions = from elem in
                                                                                    new FilteredElementCollector(doc).OfClass(typeof(Autodesk.Revit.DB.BoundaryConditions)).ToElements()
                                                                                    let bC = elem as Autodesk.Revit.DB.BoundaryConditions
                                                                                             where bC != null && m_hostElement.Id.IntegerValue == bC.HostElement.Id.IntegerValue
                                                                                             select bC;

            foreach (Autodesk.Revit.DB.BoundaryConditions bC in boundaryConditions)
            {
                m_bCsDictionary.Add(bC.Id.IntegerValue, bC);
            }
        }
예제 #24
0
        public static Dictionary <string, object> getRebarCenterLineCurve(
            List <Revit.Elements.Element> rebar,
            bool adjustForSelfIntersection = false,
            bool suppressHooks             = true,
            bool suppressBendRadius        = true,
            bool multiplanarOption         = true
            )
        {
            string        message = "";
            Document      doc     = DocumentManager.Instance.CurrentDBDocument;
            DynaFunctions f       = new DynaFunctions();
            //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
            //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument;
            List <Autodesk.DesignScript.Geometry.PolyCurve> curves = new List <Autodesk.DesignScript.Geometry.PolyCurve>();
            MultiplanarOption mp = MultiplanarOption.IncludeOnlyPlanarCurves;

            foreach (Revit.Elements.Element r in rebar)
            {
                switch (multiplanarOption)
                {
                case true: mp = MultiplanarOption.IncludeOnlyPlanarCurves; break;

                case false: mp = MultiplanarOption.IncludeAllMultiplanarCurves; break;
                }
                Autodesk.Revit.DB.Element el = doc.GetElement(r.UniqueId.ToString());
                Rebar         reb            = el as Rebar;
                IList <Curve> sketch         = reb.GetCenterlineCurves(adjustForSelfIntersection, suppressHooks, suppressBendRadius, mp, 0);
                List <Autodesk.DesignScript.Geometry.Curve> crv = new List <Autodesk.DesignScript.Geometry.Curve>();
                foreach (Curve s in sketch)
                {
                    Autodesk.DesignScript.Geometry.Curve c = Revit.GeometryConversion.RevitToProtoCurve.ToProtoType(s, true);
                    crv.Add(c);
                }
                Autodesk.DesignScript.Geometry.PolyCurve pc = Autodesk.DesignScript.Geometry.PolyCurve.ByJoinedCurves(crv);
                curves.Add(pc);
            }

            return(new Dictionary <string, object>
            {
                { "polyCurves", curves },
                //{ "Message", message },
            });
        }
예제 #25
0
        public static Dictionary <string, object> getTrueCoordinates(Revit.Elements.Element elements)
        {
            string message = "";


            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;

            Units         units  = doc.GetUnits();
            FormatOptions fo     = units.GetFormatOptions(UnitType.UT_Length);
            List <double> output = new List <double>();

            //Document openedDoc = null;
            //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
            //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument;
            ProjectLocation pr = doc.ActiveProjectLocation;
            Transform       tr = pr.GetTotalTransform().Inverse;

            try
            {
                Autodesk.Revit.DB.Element        e  = doc.GetElement(elements.UniqueId.ToString());
                Autodesk.Revit.DB.FamilyInstance fi = e as Autodesk.Revit.DB.FamilyInstance;

                LocationPoint loc = fi.Location as LocationPoint;

                XYZ p = tr.OfPoint(loc.Point);

                double x = UnitUtils.ConvertFromInternalUnits(p.X, fo.DisplayUnits);
                double y = UnitUtils.ConvertFromInternalUnits(p.Y, fo.DisplayUnits);
                double z = UnitUtils.ConvertFromInternalUnits(p.Z, fo.DisplayUnits);

                output.AddRange(new List <Double> {
                    x, y, z
                });
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return(new Dictionary <string, object>
            {
                { "ENZ", output },
            });
        }
예제 #26
0
        /// <summary>
        /// Overwrites the parameters of an element with the parameters of an element from a different document.  Associated elements such as materials may be duplicated in the document.
        /// </summary>
        /// <param name="Element"></param>
        /// <param name="SourceElement"></param>
        /// <returns></returns>
        public static RevitElem TransferElements(
            RevitElem Element,
            RevitElem SourceElement)
        {
            RevitDoc destinationDoc = Element.Document;
            RevitDoc sourceDoc      = SourceElement.Document;

            string transactionName = "Element overwritten from " + sourceDoc.Title;

            RevitElem returnElem;

            Func <RevitElem, RevitDoc, RevitElem, RevitDoc, RevitElem> transfer = (dElem, dDoc, sElem, sDoc) =>
            {
                List <RevitElemId> revitElemIds = new List <RevitElemId>();
                revitElemIds.Add(sElem.Id);

                Autodesk.Revit.DB.CopyPasteOptions cpo = new Autodesk.Revit.DB.CopyPasteOptions();
                List <RevitElemId> ids = (List <RevitElemId>)Autodesk.Revit.DB.ElementTransformUtils.CopyElements(sDoc, revitElemIds, dDoc, null, cpo);

                RevitElem tempElem = dDoc.GetElement(ids[0]);
                _transferParameters(tempElem, dElem);
                destinationDoc.Delete(tempElem.Id);

                return(dElem);
            };

            if (destinationDoc.IsModifiable)
            {
                TransactionManager.Instance.EnsureInTransaction(destinationDoc);
                returnElem = transfer(Element, destinationDoc, SourceElement, sourceDoc);
                TransactionManager.Instance.TransactionTaskDone();
            }
            else
            {
                using (Autodesk.Revit.DB.Transaction trans = new Autodesk.Revit.DB.Transaction(destinationDoc))
                {
                    trans.Start(transactionName);
                    returnElem = transfer(Element, destinationDoc, SourceElement, sourceDoc);
                    trans.Commit();
                }
            }

            return(returnElem);
        }
예제 #27
0
        protected void PipeHostParameter(IGH_DataAccess DA, DB.Element srcElement, DB.BuiltInParameter srcParam, string paramName)
        {
            if (srcElement is null)
            {
                DA.SetData(paramName, null);
                return;
            }

            var param = srcElement.get_Parameter(srcParam);

            if (param != null)
            {
                switch (param.StorageType)
                {
                case DB.StorageType.None: break;

                case DB.StorageType.String:
                    DA.SetData(paramName, param.AsString());
                    break;

                case DB.StorageType.Integer:
                    if (param.Definition.ParameterType == DB.ParameterType.YesNo)
                    {
                        DA.SetData(paramName, param.AsInteger() != 0);
                    }
                    else
                    {
                        DA.SetData(paramName, param.AsInteger());
                    }
                    break;

                case DB.StorageType.Double:
                    DA.SetData(paramName, param.AsDoubleInRhinoUnits());
                    break;

                case DB.StorageType.ElementId:
                    DA.SetData(
                        paramName,
                        Types.Element.FromElementId(srcElement.Document, param.AsElementId())
                        );
                    break;
                }
            }
        }
예제 #28
0
        /// <summary>
        /// Generate appropriate graphics data object from exact analytical model type.
        /// </summary>
        /// <param name="element">The selected element maybe has analytical model lines</param>
        /// <returns>A graphics data object appropriate for GDI.</returns>
        public ModelData(Element element)
        {
            try
            {
                AnalyticalModel analyticalMode = GetAnalyticalModel(element);
                View            currentView    = Command.CommandData.Application.ActiveUIDocument.Document.ActiveView;
                m_bbox = element.get_BoundingBox(currentView);

                if (null == analyticalMode)
                {
                    return;
                }

                GetModelData(analyticalMode);
            }
            catch (Exception)
            {
            }
        }
예제 #29
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            DB.Element element = null;
            if (!DA.GetData("Element", ref element))
            {
                return;
            }

            IGH_Goo key = null;

            if (!DA.GetData("ParameterKey", ref key))
            {
                return;
            }

            var parameter = ParameterUtils.GetParameter(this, element, key);

            if (parameter is null)
            {
                return;
            }

            using (var transaction = NewTransaction(element.Document))
            {
                transaction.Start();

                if (parameter.ResetValue())
                {
                    if (CommitTransaction(element.Document, transaction) == DB.TransactionStatus.Committed)
                    {
                        DA.SetData("Element", element);
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Failed to reset '{parameter.Definition.Name}'");
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Unable to reset '{parameter.Definition.Name}'");
                }
            }
        }
예제 #30
0
        //Component가 Element로 부터 정보를 얻는다!
        public Component(PCFData data, Autodesk.Revit.DB.Element element)
        {
            this.Data = data;

            //초기화
            this.Misc_Spec = new List <string>(5);
            this.KeyPoints = new List <DataType.KeyPoint>();

            //파라미터 값을 추가하는 과정
            this.Component_Type       = RevitParam.GetParameter(element, RevitParam.ParameterName.Type).AsString();
            this.Component_Identifier = ++elementIdentificationNumber;

            //Material 처리
            this.Material_Identifier = this.Data.GetMaterialData(RevitParam.GetParameter(element, RevitParam.ParameterName.Item_Code).AsString()).Material_Identifier;

            this.Category    = DataType.EnumString.CATEGORY.GetBySecond(RevitParam.GetParameter(element, RevitParam.ParameterName.Category).AsString());
            this.Piping_Spec = RevitParam.GetParameter(element, RevitParam.ParameterName.Piping_Spec).AsString();
            this.Unique_Component_Identifier = element.UniqueId;
        }
예제 #31
0
        /// <summary>
        /// Private constructor
        /// </summary>
        private PerspectiveView(XYZ eye, XYZ target, Autodesk.Revit.DB.Element element, string name, bool isolate)
        {
            //Phase 1 - Check to see if the object exists and should be rebound
            var oldEle =
                ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.View3D>(Document);

            // Rebind to Element
            if (oldEle != null)
            {
                InternalSetView3D(oldEle);
                InternalSetOrientation(BuildOrientation3D(eye, target));
                if (isolate)
                {
                    InternalIsolateInView(element);
                }
                else
                {
                    InternalRemoveIsolation();
                }
                InternalSetName(name);
                return;
            }

            //Phase 2 - There was no existing Element, create new one
            TransactionManager.Instance.EnsureInTransaction(Document);

            var vd = Create3DView(BuildOrientation3D(eye, target), name, true);

            InternalSetView3D(vd);
            if (isolate)
            {
                InternalIsolateInView(element);
            }
            else
            {
                InternalRemoveIsolation();
            }
            InternalSetName(name);

            TransactionManager.Instance.TransactionTaskDone();

            ElementBinder.SetElementForTrace(this.InternalElement);
        }
예제 #32
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            DB.Element element = null;
            if (!DA.GetData("Element", ref element))
            {
                return;
            }

            IGH_Goo parameterKey = null;

            if (!DA.GetData("ParameterKey", ref parameterKey))
            {
                return;
            }

            var parameter = ParameterUtils.GetParameter(this, element, parameterKey);

            DA.SetData("ParameterValue", parameter);
        }
예제 #33
0
        /// <summary>
        /// Depending on SerialElementId properties, method attempts to find the Element referenced by the ElementId by first trying UniqueId, then Id, then Name, then Aliases of the name.  If an element is found, then set the parameter to the Element's Id.
        /// </summary>
        /// <param name="param">Parameter to modify</param>
        /// <param name="serialElementId">A SerialElementId that references an element in the Document.</param>
        /// <param name="document">A revit document</param>
        /// <returns name="status">Returns true if parameter was successfully set and false if not.  Parameter retains it previous value if Set was unsucessful.</returns>
        private static bool _ModifyElementIdParameter(RevitParam param, SerialElementId serialElementId, RevitDoc document)
        {
            //  Initialize variables.
            // Status of parameter change.
            bool status = false;

            //  Element to set the ElementId parameter.
            //  Will return null if element is not found.
            RevitElem elem = serialElementId.GetElem(document);

            //  If elem was selected, then set the parameter to that element.
            if (elem != null)
            {
                status = param.Set(elem.Id);
            }

            // Return if parameter change was successful.
            return(status);
        }
예제 #34
0
파일: ModelData.cs 프로젝트: AMEE/revit
        /// <summary>
        /// Generate appropriate graphics data object from exact analytical model type.
        /// </summary>
        /// <param name="element">The selected element maybe has analytical model lines</param>
        /// <returns>A graphics data object appropriate for GDI.</returns>
        public ModelData(Element element)
        {
            try
            {
                AnalyticalModel analyticalMode = GetAnalyticalModel(element);
                View currentView = Command.CommandData.Application.ActiveUIDocument.Document.ActiveView;
                m_bbox = element.get_BoundingBox(currentView);

                if (null == analyticalMode)
                {
                    return;
                }

                GetModelData(analyticalMode);

            }
            catch (Exception)
            {
            }
        }
예제 #35
0
파일: GeomUtil.cs 프로젝트: AMEE/revit
        const double PRECISION = 0.00001; //precision when judge whether two doubles are equal

        #endregion Fields

        #region Methods

        /// <summary>
        /// get all faces that compose the geometry solid of given element
        /// </summary>
        /// <param name="elem">element to be calculated</param>
        /// <returns>all faces</returns>
        public static FaceArray GetFaces(Element elem)
        {
            List<Face> faces = new List<Face>();

            Autodesk.Revit.DB.Options geoOptions = Command.CommandData.Application.Application.Create.NewGeometryOptions();
            geoOptions.ComputeReferences = true;

            GeoElement geoElem = elem.get_Geometry(geoOptions);
            GeometryObjectArray geoElems = geoElem.Objects;

            foreach (object o in geoElems)
            {
                GeoSolid geoSolid = o as GeoSolid;
                if (null == geoSolid)
                {
                    continue;
                }

                return geoSolid.Faces;
            }

            return null;
        }
예제 #36
0
파일: ObjectViewer.cs 프로젝트: AMEE/revit
        private Element m_selected; // selected element to display

        #endregion Fields

        #region Constructors

        /// <summary>
        /// constructor
        /// </summary>
        public ObjectViewer()
        {
            UIDocument doc = Command.CommandData.Application.ActiveUIDocument;
            ElementSet selection = doc.Selection.Elements;
            // only one element should be selected
            if (0 == selection.Size)
            {
                throw new ErrorMessageException("Please select an element.");
            }

            if (1 < selection.Size)
            {
                throw new ErrorMessageException("Please select only one element.");
            }
            // get selected element
            foreach (Element e in selection)
            {
                m_selected = e;
            }
            // get current view and all views
            m_currentView = doc.Document.ActiveView;
            FilteredElementIterator itor = (new FilteredElementCollector(doc.Document)).OfClass(typeof(View)).GetElementIterator();
            itor.Reset();
            while (itor.MoveNext())
            {
                View view = itor.Current as View;
                // Skip view templates because they're invisible in project browser, invalid for geometry elements
                if (null != view && !view.IsTemplate)
                {
                    m_allViews.Add(view);
                }
            }

            // create a instance of Sketch3D
            GeometryData geomFactory = new GeometryData(m_selected, m_currentView);
            m_currentSketch3D = new Sketch3D(geomFactory.Data3D, Graphics2DData.Empty);

            //get a instance of ParametersFactory and then use it to create Parameters
            ParasFactory parasFactory = new ParasFactory(m_selected);
            m_paras = parasFactory.CreateParas();
        }
예제 #37
0
        /// <summary>
        /// Inquire an geometry element to get all face instances
        /// </summary>
        /// <param name="geoElement">the geometry element</param>
        /// <param name="elem">the element, it provides the prefix of face name</param>
        /// <returns></returns>
        private bool InquireGeometry(GeoElement geoElement, RevitElement elem)
        {
            if(null == geoElement || null == elem)
            {
                return false;
            }

            GeometryObjectArray geoArray = null;

            if (null != geoElement && null != geoElement.Objects)
            {
                geoArray = geoElement.Objects;
            }
            else
            {
                return false;
            }

            foreach (GeometryObject obj in geoArray)
            {
                if (obj is GeoInstance)
                {
                    GeoInstance instance = (GeoInstance)obj;
                    InquireGeometry(instance.SymbolGeometry, elem);
                }
                else if (!(obj is Solid))
                {
                    // is not Solid instance
                    continue;
                }

                // continue when obj is Solid instance
                Solid solid = obj as Solid;
                if (null == solid)
                {
                    continue;
                }
                FaceArray faces = solid.Faces;
                if (faces.IsEmpty)
                {
                    continue;
                }

                // get the face name list
                String category = String.Empty;
                if (null != elem.Category && null != elem.Name)
                {
                    category = elem.Category.Name;
                }

                int ii = 0;
                foreach (Face tempFace in faces)
                {
                    if (tempFace is PlanarFace)
                    {
                        m_faceNameList.Add(
                            String.Format("{0} : {1} ({2})", category, elem.Name, ii));
                        m_faceList.Add(tempFace);
                        ii++;
                    }
                }
            }
            return true;
        }
예제 #38
0
 public PanelTreeNodeHelper( Element e, System.Windows.Forms.TreeNode tn )
 {
     _element = e;
       _tn = tn;
 }
예제 #39
0
 public PanelTreeNodeHelper( Element e )
 {
     _element = e;
 }
예제 #40
0
파일: ModelData.cs 프로젝트: AMEE/revit
 /// <summary>
 /// Get the analytical model object from an element.
 /// </summary>
 /// <param name="element">The selected element maybe has analytical model lines</param>
 /// <returns>Return analytical model object, or else return null.</returns>
 private AnalyticalModel GetAnalyticalModel(Element element)
 {
     return element.GetAnalyticalModel();
 }
예제 #41
0
 /// <summary>
 /// Private constructor
 /// </summary>
 /// <param name="element"></param>
 private UnknownElement(Autodesk.Revit.DB.Element element)
 {
     this._element = element;
 }
예제 #42
0
        /// <summary>
        /// Create reference plane for a wall.
        /// </summary>
        /// <param name="host">A wall element.</param>
        private void OperateWall(Element host)
        {
            Wall wall = host as Wall;
            Autodesk.Revit.DB.XYZ bubbleEnd = new Autodesk.Revit.DB.XYZ ();
            Autodesk.Revit.DB.XYZ freeEnd = new Autodesk.Revit.DB.XYZ ();
            Autodesk.Revit.DB.XYZ cutVec = new Autodesk.Revit.DB.XYZ ();

            LocateWall(wall, ref bubbleEnd, ref freeEnd, ref cutVec);
            m_document.Document.Create.NewReferencePlane(bubbleEnd, freeEnd, cutVec, m_document.Document.ActiveView);
        }
예제 #43
0
 /// <summary>
 /// Create reference plane for a slab.
 /// </summary>
 /// <param name="host">A floor element.</param>
 private void OperateSlab(Element host)
 {
     Floor floor = host as Floor;
     Autodesk.Revit.DB.XYZ bubbleEnd = new Autodesk.Revit.DB.XYZ ();
     Autodesk.Revit.DB.XYZ freeEnd = new Autodesk.Revit.DB.XYZ ();
     Autodesk.Revit.DB.XYZ thirdPnt = new Autodesk.Revit.DB.XYZ ();
     LocateSlab(floor, ref bubbleEnd, ref freeEnd, ref thirdPnt);
     m_document.Document.Create.NewReferencePlane2(bubbleEnd, freeEnd, thirdPnt, m_document.Document.ActiveView);
 }
예제 #44
0
        /// <summary>
        /// store the selected element and its corresponding BCs
        /// </summary>
        /// <param name="element"> use selected element in Revit UI(the host element)</param>
        private void SetBCHostMap(Autodesk.Revit.DB.Element element)
        {
            // set the Host element with current selected element
            m_hostElement = element;
            // retrieve the Document in which the Element resides.
            Document doc = element.Document;

            IEnumerable<Autodesk.Revit.DB.BoundaryConditions> boundaryConditions = from elem in
                                                                                       new FilteredElementCollector(doc).OfClass(typeof(Autodesk.Revit.DB.BoundaryConditions)).ToElements()
                                                                                   let bC = elem as Autodesk.Revit.DB.BoundaryConditions
                                                                                   where bC != null && m_hostElement.Id.IntegerValue == bC.HostElement.Id.IntegerValue
                                                                                   select bC;
            foreach (Autodesk.Revit.DB.BoundaryConditions bC in boundaryConditions)
            {
                m_bCsDictionary.Add(bC.Id.IntegerValue, bC);
            }
        }
예제 #45
0
파일: Command.cs 프로젝트: AMEE/revit
        /// <summary>
        /// Get the mechanical or piping system from selected element
        /// </summary>
        /// <param name="selectedElement">Selected element</param>
        /// <returns>The extracted mechanical or piping system. Null if no expected system is found.</returns>
        private MEPSystem ExtractMechanicalOrPipingSystem(Element selectedElement)
        {
            MEPSystem system = null;

            if (selectedElement is MEPSystem)
            {
                if (selectedElement is MechanicalSystem || selectedElement is PipingSystem)
                {
                    system = selectedElement as MEPSystem;
                    return system;
                }
            }
            else // Selected element is not a system
            {
                FamilyInstance fi = selectedElement as FamilyInstance;
                //
                // If selected element is a family instance, iterate its connectors and get the expected system
                if (fi != null)
                {
                    MEPModel mepModel = fi.MEPModel;
                    ConnectorSet connectors = null;
                    try
                    {
                        connectors = mepModel.ConnectorManager.Connectors;
                    }
                    catch (System.Exception)
                    {
                        system = null;
                    }

                    system = ExtractSystemFromConnectors(connectors);
                }
                else
                {
                    //
                    // If selected element is a MEPCurve (e.g. pipe or duct),
                    // iterate its connectors and get the expected system
                    MEPCurve mepCurve = selectedElement as MEPCurve;
                    if (mepCurve != null)
                    {
                        ConnectorSet connectors = null;
                        connectors = mepCurve.ConnectorManager.Connectors;
                        system = ExtractSystemFromConnectors(connectors);
                    }
                }
            }

            return system;
        }
예제 #46
0
파일: FrameBuilder.cs 프로젝트: AMEE/revit
 /// <summary>
 /// set parameter whose storage type is double
 /// </summary>
 /// <param name="elem">Element has parameter</param>
 /// <param name="builtInPara">BuiltInParameter to find parameter</param>
 /// <param name="value">value to set</param>
 /// <returns>is successful</returns>
 private bool SetParameter(ModelElement elem, 
     BuiltInParameter builtInPara, double value)
 {
     Parameter para = elem.get_Parameter(builtInPara);
     if (null != para && para.StorageType == StorageType.Double && !para.IsReadOnly)
     {
        var result = para.Set(value);
        return result;
     }
     return false;
 }
예제 #47
0
        /// <summary>
        /// Judge whether an element has face geometry
        /// </summary>
        /// <param name="elem">the element to be checked</param>
        /// <returns>true is having face geometry, false is having no face geometry</returns>
        private bool CheckSelectedElement(RevitElement elem)
        {
            if(null == elem)
            {
                return false;
            }
            Autodesk.Revit.DB.Options opts = new Autodesk.Revit.DB.Options();
            opts.View = m_revitDoc.Document.ActiveView;
            opts.ComputeReferences = true;
            // Get geometry of the element
            GeoElement geoElement = elem.get_Geometry(opts);
            InquireGeometry(geoElement, elem);

            return true;
        }
예제 #48
0
파일: EdgeFetchForm.cs 프로젝트: AMEE/revit
        /// <summary>
        /// Switch geometry displayed in the preview according to the tree node.
        /// </summary>
        /// <param name="node">Tree node to active</param>
        private void ActiveNode(TreeNode node)
        {
            if (node.Tag == null) return;

            if (node.Tag is Autodesk.Revit.DB.Element)
                m_activeElem = node.Tag as Autodesk.Revit.DB.Element;
            else if (node.Tag is Edge)
            {
                m_activeElem = node.Parent.Tag as Autodesk.Revit.DB.Element;
            }
        }
예제 #49
0
파일: EdgeFetchForm.cs 프로젝트: AMEE/revit
        /// <summary>
        /// Initialize something related to the geometry preview.
        /// </summary>
        private void InitializePreview()
        {
            m_centerMatrix = new Matrix(1, 0, 0, -1,
               (float)pictureBoxPreview.Width / 2.0f, (float)pictureBoxPreview.Height / 2.0f);
            this.KeyPreview = true;

            foreach (Autodesk.Revit.DB.Element elem in m_creationData.Creator.ElemGeomDic.Keys)
            {
                m_activeElem = elem;
                break;
            }
        }
예제 #50
-1
파일: Command.cs 프로젝트: AMEE/revit
        /// <summary>
        /// Get the selected element, and check whether it is a wall, a floor or a beam.
        /// </summary>
        /// <returns>true if the process succeed; otherwise, false.</returns>
        Boolean GetSelectedElement()
        {
            // First get the selection, and make sure only one element in it.
            ElementSet collection = m_project.Selection.Elements;
            if (1 != collection.Size)
            {
                m_errorInformation =
                    "Please select only one element, such as a wall, a beam or a floor.";
                return false;
            }

            // Get the selected element.
            foreach (Autodesk.Revit.DB.Element e in collection)
            {
                m_currentComponent = e;
            }

            // Make sure the element to be a wall, beam or a floor.
            if (m_currentComponent is Wall)
            {
                // Check whether the wall is a linear wall
                LocationCurve location = m_currentComponent.Location as LocationCurve;
                if (null == location)
                {
                    m_errorInformation = "The selected wall should be linear.";
                    return false;
                }
                if (location.Curve is Line)
                {
                    m_type = SelectType.WALL;   // when the element is a linear wall
                    return true;
                }
                else
                {
                    m_errorInformation = "The selected wall should be linear.";
                    return false;
                }
            }

            FamilyInstance beam = m_currentComponent as FamilyInstance;
            if (null != beam && StructuralType.Beam == beam.StructuralType)
            {
                m_type = SelectType.BEAM;       // when the element is a beam
                return true;
            }

            if (m_currentComponent is Floor)
            {
                m_type = SelectType.FLOOR;      // when the element is a floor.
                return true;
            }

            // If it is not a wall, a beam or a floor, give error information.
            m_errorInformation = "Please select an element, such as a wall, a beam or a floor.";
            return false;
        }
예제 #51
-2
파일: GeometryData.cs 프로젝트: AMEE/revit
        /// <summary>
        /// create 3D and 2D data of given GeometryElement
        /// </summary>
        /// <param name="elem">of which geometry data be gotten</param>
        /// <param name="currentView">current view of Revit</param>
        public GeometryData(Element elem, View currentView)
        {
            Options opt = Command.CommandData.Application.Application.Create.NewGeometryOptions();
            opt.View = currentView;
            opt.ComputeReferences = false;
            GeometryElement geoElement = elem.get_Geometry(opt);

            Autodesk.Revit.DB.XYZ xyz = new Autodesk.Revit.DB.XYZ (0, 0, 0);
            Transform transform = Transform.get_Translation(xyz);
            AddGeoElement(geoElement, transform);

            m_bbox = elem.get_BoundingBox(currentView);
        }