Ejemplo n.º 1
2
 /// <summary>
 /// Constructor with display unit type
 /// </summary>
 /// <param name="application">Revit application</param>
 /// <param name="labels">All existing labels in Revit's document</param>
 /// <param name="dut">Current length display unit type</param>
 public CreateGridsData(UIApplication application, ArrayList labels, DisplayUnitType dut)
 {
     m_revitDoc = application.ActiveUIDocument.Document;
     m_appCreator = application.Application.Create;
     m_docCreator = application.ActiveUIDocument.Document.Create;
     m_labelsList = labels;
     m_dut = dut;
 }
Ejemplo n.º 2
0
        Autodesk.Revit.Creation.Application m_appCreator; // buffer of API object

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="data">data necessary to initialize object</param>
        public FrameBuilder(FrameData data)
        {
            // initialize members
            if (null == data)
            {
                throw new ArgumentNullException("data",
                                                "constructor FrameBuilder(FrameData data)'s parameter shouldn't be null ");
            }
            m_data = data;

            m_appCreator = data.CommandData.Application.Application.Create;
            m_docCreator = data.CommandData.Application.ActiveUIDocument.Document.Create;
        }
Ejemplo n.º 3
0
        Autodesk.Revit.Creation.Document m_docCreator; // buffer of API object

        #endregion Fields

        #region Constructors

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="data">data necessary to initialize object</param>
        public FrameBuilder(FrameData data)
        {
            // initialize members
            if (null == data)
            {
                throw new ArgumentNullException("data",
                    "constructor FrameBuilder(FrameData data)'s parameter shouldn't be null ");
            }
            m_data = data;

            m_appCreator = data.CommandData.Application.Application.Create;
            m_docCreator = data.CommandData.Application.ActiveUIDocument.Document.Create;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Create model lines representing a closed
        /// planar loop in the given sketch plane.
        /// </summary>
        static void DrawModelLineLoop(
            SketchPlane sketchPlane,
            XYZ[] corners)
        {
            Autodesk.Revit.Creation.Document factory
                = sketchPlane.Document.Create;

            int n = corners.GetLength(0);

            for (int i = 0; i < n; ++i)
            {
                int j = 0 == i ? n - 1 : i - 1;

                factory.NewModelCurve(Line.CreateBound(
                                          corners[j], corners[i]), sketchPlane);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// create beam system according to given profile and property
        /// </summary>
        public void CreateBeamSystem()
        {
            Autodesk.Revit.Creation.Document docCreation = m_data.CommandData.Application.ActiveUIDocument.Document.Create;
            // create CurveArray and insert Lines in order
            CurveArray curves = new CurveArray();

            foreach (Line line in m_data.Lines)
            {
                curves.Append(line);
            }
            // create beam system takes closed profile consist of lines
            BeamSystem aBeamSystem = docCreation.NewBeamSystem(curves, m_data.CommandData.Application.ActiveUIDocument.Document.ActiveView.SketchPlane);

            // set created beam system's layout rule and beam type property
            aBeamSystem.LayoutRule = m_data.Param.Layout;
            aBeamSystem.BeamType   = m_data.Param.BeamType;
        }
Ejemplo n.º 6
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            IWin32Window revit_window
                = new JtWindowHandle(
                      ComponentManager.ApplicationWindow);

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            PlaceInstancesForm f
                = new PlaceInstancesForm(doc);

            if ((DialogResult.OK == f.ShowDialog(revit_window)) &&
                (null != f.Points))
            {
                using (Transaction t = new Transaction(
                           doc))
                {
                    t.Start("Place Instances");

                    Autodesk.Revit.Creation.Document
                        creation_doc = doc.Create;

                    StructuralType st
                        = StructuralType.NonStructural;

                    foreach (XYZ p in f.Points)
                    {
                        creation_doc.NewFamilyInstance(
                            p, f.Type, st);
                    }

                    t.Commit();
                }
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// create truss in Revit
        /// </summary>
        /// <returns>new created truss</returns>
        public Autodesk.Revit.DB.Structure.Truss CreateTruss()
        {
            Autodesk.Revit.DB.Document          document  = m_commandData.Application.ActiveUIDocument.Document;
            Autodesk.Revit.Creation.Document    createDoc = document.Create;
            Autodesk.Revit.Creation.Application createApp = m_commandData.Application.Application.Create;
            //sketchPlane
            Autodesk.Revit.DB.XYZ origin     = new Autodesk.Revit.DB.XYZ(0, 0, 0);
            Autodesk.Revit.DB.XYZ xDirection = new Autodesk.Revit.DB.XYZ(1, 0, 0);
            Autodesk.Revit.DB.XYZ yDirection = new Autodesk.Revit.DB.XYZ(0, 1, 0);
            Plane       plane       = Plane.CreateByOriginAndBasis(xDirection, yDirection, origin);
            SketchPlane sketchPlane = SketchPlane.Create(document, plane);
            //new base Line
            Curve frame1Curve = null;
            Curve frame2Curve = null;

            if (column1.Location is LocationCurve)
            {
                frame1Curve = (column1.Location as LocationCurve).Curve;
            }
            if (column2.Location is LocationCurve)
            {
                frame2Curve = (column2.Location as LocationCurve).Curve;
            }

            Autodesk.Revit.DB.XYZ centerPoint1 = (frame1Curve as Line).GetEndPoint(0);


            Autodesk.Revit.DB.XYZ  centerPoint2 = (frame2Curve as Line).GetEndPoint(0);
            Autodesk.Revit.DB.XYZ  startPoint   = new Autodesk.Revit.DB.XYZ(centerPoint1.X, centerPoint1.Y, 0);
            Autodesk.Revit.DB.XYZ  endPoint     = new Autodesk.Revit.DB.XYZ(centerPoint2.X, centerPoint2.Y, 0);
            Autodesk.Revit.DB.Line baseLine     = null;

            try
            { baseLine = Line.CreateBound(startPoint, endPoint); }
            catch (System.ArgumentException)
            {
                TaskDialog.Show("Argument Exception", "Two column you selected are too close to create truss.");
            }

            return(Autodesk.Revit.DB.Structure.Truss.Create(document, m_selectedTrussType.Id, sketchPlane.Id, baseLine));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// The default constructor
        /// </summary>
        /// <param name="revit">The reference of the application in revit</param>
        public ModelLines(Autodesk.Revit.UI.UIApplication revit)
        {
            // Store the reference of the application for further use.
            m_revit = revit;
            // Get the create references
            m_createApp = m_revit.Application.Create;               // Creation.Application
            m_createDoc = m_revit.ActiveUIDocument.Document.Create; // Creation.Document

            // Construct all the ModelCurveArray instances for model lines
            m_lineArray    = new ModelCurveArray();
            m_arcArray     = new ModelCurveArray();
            m_ellipseArray = new ModelCurveArray();
            m_hermiteArray = new ModelCurveArray();
            m_nurbArray    = new ModelCurveArray();

            // Construct the sketch plane list data
            m_sketchArray = new List <SketchPlane>();

            // Construct the information list data
            m_informationMap = new List <ModelCurveCounter>();
        }
Ejemplo n.º 9
0
        List<SketchPlane> m_sketchArray; // Store the SketchPlane references

        #endregion Fields

        #region Constructors

        /// <summary>
        /// The default constructor
        /// </summary>
        /// <param name="revit">The reference of the application in revit</param>
        public ModelLines(Autodesk.Revit.UI.UIApplication revit)
        {
            // Store the reference of the application for further use.
            m_revit = revit;
            // Get the create references
            m_createApp = m_revit.Application.Create;       // Creation.Application
            m_createDoc = m_revit.ActiveUIDocument.Document.Create;// Creation.Document

            // Construct all the ModelCurveArray instances for model lines
            m_lineArray = new ModelCurveArray();
            m_arcArray = new ModelCurveArray();
            m_ellipseArray = new ModelCurveArray();
            m_hermiteArray = new ModelCurveArray();
            m_nurbArray = new ModelCurveArray();

            // Construct the sketch plane list data
            m_sketchArray = new List<SketchPlane>();

            // Construct the information list data
            m_informationMap = new List<ModelCurveCounter>();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// add more levels so that level number can meet floor number
        /// </summary>
        public void UpdateLevels()
        {
            double baseElevation = m_levels.Values[m_levels.Count - 1].Elevation;

            Autodesk.Revit.Creation.Document createDoc = m_commandData.Application.ActiveUIDocument.Document.Create;
            Autodesk.Revit.DB.Document       m_Doc     = m_commandData.Application.ActiveUIDocument.Document;

            FilteredElementCollector collector       = new FilteredElementCollector(m_Doc);
            IList <Element>          viewFamilyTypes = collector.OfClass(typeof(ViewFamilyType)).ToElements();
            ElementId floorPlanId = new ElementId(-1);

            foreach (Element e in viewFamilyTypes)
            {
                ViewFamilyType v = e as ViewFamilyType;

                if (v != null && v.ViewFamily == ViewFamily.FloorPlan)
                {
                    floorPlanId = e.Id;
                    break;
                }
            }

            int newLevelSize = (m_floorNumber + 1) - m_levels.Count;

            if (newLevelSize == 0)
            {
                return;
            }

            for (int ii = 0; ii < newLevelSize; ii++)
            {
                double elevation = baseElevation + m_levelHeight * (ii + 1);
                Level  newLevel  = Level.Create(m_commandData.Application.ActiveUIDocument.Document, elevation);
                //createDoc.NewViewPlan(newLevel.Name, newLevel, Autodesk.Revit.DB.ViewPlanType.FloorPlan);
                ViewPlan viewPlan = ViewPlan.Create(m_Doc, floorPlanId, newLevel.Id);
                viewPlan.Name = newLevel.Name;
                m_levels.Add(elevation, newLevel);
            }
            m_originalLevelSize = m_levels.Count;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// add more levels so that level number can meet floor number
        /// </summary>
        public void UpdateLevels()
        {
            double baseElevation = m_levels.Values[m_levels.Count - 1].Elevation;

            Autodesk.Revit.Creation.Document createDoc = m_commandData.Application.ActiveUIDocument.Document.Create;

            int newLevelSize = (m_floorNumber + 1) - m_levels.Count;

            if (newLevelSize == 0)
            {
                return;
            }

            for (int ii = 0; ii < newLevelSize; ii++)
            {
                double elevation = baseElevation + m_levelHeight * (ii + 1);
                Level  newLevel  = createDoc.NewLevel(elevation);
                createDoc.NewViewPlan(newLevel.Name, newLevel, Autodesk.Revit.DB.ViewPlanType.FloorPlan);
                m_levels.Add(elevation, newLevel);
            }
            m_originalLevelSize = m_levels.Count;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// create the curtain wall to the active document of Revit
        /// </summary>
        /// <returns>
        /// the created curtain wall
        /// </returns>
        public Wall CreateCurtainWall()
        {
            if (null == m_selectedWallType || null == m_selectedView)
            {
                return(null);
            }

            Autodesk.Revit.Creation.Document    createDoc = m_myDocument.Document.Create;
            Autodesk.Revit.Creation.Application createApp = m_myDocument.CommandData.Application.Application.Create;
            //baseline
            System.Drawing.Point point0 = m_drawing.WallLine2D.StartPoint;
            System.Drawing.Point point1 = m_drawing.WallLine2D.EndPoint;
            //new baseline and transform coordinate on windows UI to Revit UI
            m_startXYZ = new Autodesk.Revit.DB.XYZ(m_startPointD.X, m_startPointD.Y, 0);
            m_endXYZ   = new Autodesk.Revit.DB.XYZ(m_endPointD.X, m_endPointD.Y, 0);
            Autodesk.Revit.DB.Line baseline = null;
            try
            {
                baseline = Line.CreateBound(m_startXYZ, m_endXYZ);
            }
            catch (System.ArgumentException)
            {
                TaskDialog.Show("Revit", "The start point and the end point of the line are too close, please re-draw it.");
            }
            Transaction act = new Transaction(m_myDocument.Document);

            act.Start(Guid.NewGuid().GetHashCode().ToString());
            Wall wall = Wall.Create(m_myDocument.Document, baseline, m_selectedWallType.Id,
                                    m_selectedView.GenLevel.Id, 20, 0, false, false);

            act.Commit();
            Transaction act2 = new Transaction(m_myDocument.Document);

            act2.Start(Guid.NewGuid().GetHashCode().ToString());
            m_myDocument.UIDocument.ShowElements(wall);
            act2.Commit();
            return(wall);
        }
Ejemplo n.º 13
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            if (!doc.IsFamilyDocument)
            {
                message = "Please run this command in afamily document.";
                return(Result.Failed);
            }

            Autodesk.Revit.Creation.Application creApp = app.Application.Create;
            Autodesk.Revit.Creation.Document    creDoc = doc.Create;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("New Dimension Label");


                SketchPlane skplane = findSketchPlane(doc, XYZ.BasisZ);

                if (null == skplane)
                {
                    //Plane geometryPlane = creApp.NewPlane( XYZ.BasisZ, XYZ.Zero ); // 2016
                    Plane geometryPlane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero); // 2017

                    //skplane = doc.FamilyCreate.NewSketchPlane( geometryPlane ); // 2013

                    skplane = SketchPlane.Create(doc, geometryPlane); // 2014
                }

                double length = 1.23;

                XYZ start = XYZ.Zero;
                XYZ end   = creApp.NewXYZ(0, length, 0);

                //Line line = creApp.NewLine( start, end, true ); // 2013

                Line line = Line.CreateBound(start, end); // 2014

                ModelCurve modelCurve
                    = doc.FamilyCreate.NewModelCurve(
                          line, skplane);

                ReferenceArray ra = new ReferenceArray();

                ra.Append(modelCurve.GeometryCurve.Reference);

                start = creApp.NewXYZ(length, 0, 0);
                end   = creApp.NewXYZ(length, length, 0);

                line = Line.CreateBound(start, end);

                modelCurve = doc.FamilyCreate.NewModelCurve(
                    line, skplane);

                ra.Append(modelCurve.GeometryCurve.Reference);

                start = creApp.NewXYZ(0, 0.2 * length, 0);
                end   = creApp.NewXYZ(length, 0.2 * length, 0);

                line = Line.CreateBound(start, end);

                Dimension dim
                    = doc.FamilyCreate.NewLinearDimension(
                          doc.ActiveView, line, ra);

                FamilyParameter familyParam
                    = doc.FamilyManager.AddParameter(
                          "length",
                          BuiltInParameterGroup.PG_IDENTITY_DATA,
                          ParameterType.Length, false);

                //dim.Label = familyParam; // 2013
                dim.FamilyLabel = familyParam; // 2014

                t.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = commandData.Application.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;

            View   acview   = uidoc.ActiveView;
            UIView acuiview = uidoc.ActiveUiview();


            Transaction ts = new Transaction(doc, "******");

            try
            {
                ts.Start();

                //获取revit文档的创建句柄
                Autodesk.Revit.Creation.Document creater = doc.Create;

                //创建一根柱子: 使用给点的位置(坐标原点),柱子的类型和标高(高度为0)
                XYZ origin = new XYZ(0, 0, 0);

                //获得level
                Level level = null;
                if (acview.ViewType == ViewType.FloorPlan)
                {
                    level = acview.GenLevel;
                }

                if (level == null)
                {
                    MessageBox.Show("未找到楼层");
                    return(Result.Cancelled);
                }

                //获取symbol
                var symbol = doc.TCollector <FamilySymbol>()
                             .Where(m => m.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns).First();

                if (symbol == null)
                {
                    MessageBox.Show("未找到柱子的族符号");
                    return(Result.Cancelled);
                }

                //创建柱子
                FamilyInstance colum = creater.NewFamilyInstance(origin, symbol, level,
                                                                 Autodesk.Revit.DB.Structure.StructuralType.Column);


                // 把柱子移动到新的位置
                XYZ newPlace = new XYZ(100, 100, 100);
                ElementTransformUtils.MoveElement(doc, colum.Id, newPlace);


                ts.Commit();
            }

            catch (Exception)
            {
                if (ts.GetStatus() == TransactionStatus.Started)
                {
                    ts.RollBack();
                }
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 15
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // Retrieve selected floors, or all floors, if nothing is selected:

            List <Element> floors = new List <Element>();

            if (!Util.GetSelectedElementsOrAll(
                    floors, uidoc, typeof(Floor)))
            {
                Selection sel = uidoc.Selection;
                message = (0 < sel.GetElementIds().Count)
          ? "Please select some floor elements."
          : "No floor elements found.";
                return(Result.Failed);
            }

            // Determine top face of each selected floor:

            int         nNullFaces = 0;
            List <Face> topFaces   = new List <Face>();
            Options     opt        = app.Application.Create.NewGeometryOptions();

            foreach (Floor floor in floors)
            {
                GeometryElement geo = floor.get_Geometry(opt);

                //GeometryObjectArray objects = geo.Objects; // 2012

                foreach (GeometryObject obj in geo)
                {
                    Solid solid = obj as Solid;
                    if (solid != null)
                    {
                        PlanarFace f = GetTopFace(solid);
                        if (null == f)
                        {
                            Debug.WriteLine(
                                Util.ElementDescription(floor)
                                + " has no top face.");
                            ++nNullFaces;
                        }
                        topFaces.Add(f);
                    }
                }
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Model Lines and Floor");

                // Create new floors from the top faces found.
                // Before creating the new floor, we would obviously
                // apply whatever modifications are required to the
                // new floor profile:

                Autodesk.Revit.Creation.Application creApp = app.Application.Create;
                Autodesk.Revit.Creation.Document    creDoc = doc.Create;

                int i = 0;
                int n = topFaces.Count - nNullFaces;

                Debug.Print(
                    "{0} top face{1} found.",
                    n, Util.PluralSuffix(n));

                foreach (Face f in topFaces)
                {
                    Floor floor = floors[i++] as Floor;

                    if (null != f)
                    {
                        EdgeArrayArray eaa = f.EdgeLoops;
                        CurveArray     profile;

                        #region Attempt to include inner loops
#if ATTEMPT_TO_INCLUDE_INNER_LOOPS
                        bool use_original_loops = true;
                        if (use_original_loops)
                        {
                            profile = Convert(eaa);
                        }
                        else
#endif // ATTEMPT_TO_INCLUDE_INNER_LOOPS
                        #endregion // Attempt to include inner loops

                        {
                            profile = new CurveArray();

                            // Only use first edge array,
                            // the outer boundary loop,
                            // skip the further items
                            // representing holes:

                            EdgeArray ea = eaa.get_Item(0);
                            foreach (Edge e in ea)
                            {
                                IList <XYZ> pts  = e.Tessellate();
                                int         m    = pts.Count;
                                XYZ         p    = pts[0];
                                XYZ         q    = pts[m - 1];
                                Line        line = Line.CreateBound(p, q);
                                profile.Append(line);
                            }
                        }
                        //Level level = floor.Level; // 2013

                        Level level = doc.GetElement(floor.LevelId)
                                      as Level; // 2014

                        // In this case we have a valid floor type given.
                        // In general, not that NewFloor will only accept
                        // floor types whose IsFoundationSlab predicate
                        // is false.

                        floor = creDoc.NewFloor(profile,
                                                floor.FloorType, level, true);

                        XYZ v = new XYZ(5, 5, 0);

                        //doc.Move( floor, v ); // 2011
                        ElementTransformUtils.MoveElement(doc, floor.Id, v); // 2012
                    }
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app  = commandData.Application;
            Document      doc  = app.ActiveUIDocument.Document;
            View          view = doc.ActiveView;

            Autodesk.Revit.Creation.Application creApp = app.Application.Create;
            Autodesk.Revit.Creation.Document    creDoc = doc.Create;

            // Create a geometry line

            XYZ startPoint = new XYZ(0, 0, 0);
            XYZ endPoint   = new XYZ(10, 10, 0);

            //Line geomLine = creApp.NewLine( startPoint, endPoint, true ); // 2013

            Line geomLine = Line.CreateBound(startPoint, endPoint); // 2014

            // Create a geometry arc

            XYZ end0         = new XYZ(0, 0, 0);
            XYZ end1         = new XYZ(10, 0, 0);
            XYZ pointOnCurve = new XYZ(5, 5, 0);

            //Arc geomArc = creApp.NewArc( end0, end1, pointOnCurve ); // 2013

            Arc geomArc = Arc.Create(end0, end1, pointOnCurve); // 2014

#if NEED_PLANE
            // Create a geometry plane

            XYZ origin = new XYZ(0, 0, 0);
            XYZ normal = new XYZ(1, 1, 0);

            Plane geomPlane = creApp.NewPlane(
                normal, origin);

            // Create a sketch plane in current document

            SketchPlane sketch = creDoc.NewSketchPlane(
                geomPlane);
#endif // NEED_PLANE

            // Create a DetailLine element using the
            // newly created geometry line and sketch plane

            DetailLine line = creDoc.NewDetailCurve(
                view, geomLine) as DetailLine;

            // Create a DetailArc element using the
            // newly created geometry arc and sketch plane

            DetailArc arc = creDoc.NewDetailCurve(
                view, geomArc) as DetailArc;

            // Change detail curve colour.
            // Initially, this only affects the newly
            // created curves. However, when the view
            // is refreshed, all detail curves will
            // be updated.

            GraphicsStyle gs = arc.LineStyle as GraphicsStyle;

            gs.GraphicsStyleCategory.LineColor
                = new Color(250, 10, 10);

            return(Result.Succeeded);
        }
Ejemplo n.º 17
0
 public Creator( Document doc )
 {
     _doc = doc;
       _credoc = doc.Create;
       _creapp = doc.Application.Create;
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Initializes a new instance of TagBeamData.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command</param>
        public TagBeamData(ExternalCommandData commandData)
        {
            //Get beams selected
            m_revitDoc   = commandData.Application.ActiveUIDocument;
            m_docCreator = m_revitDoc.Document.Create;
            m_view       = m_revitDoc.Document.ActiveView;

            ElementSet elementSet = new ElementSet();

            foreach (ElementId elementId in m_revitDoc.Selection.GetElementIds())
            {
                elementSet.Insert(m_revitDoc.Document.GetElement(elementId));
            }
            ElementSetIterator itor = elementSet.ForwardIterator();

            while (itor.MoveNext())
            {
                FamilyInstance familyInstance = itor.Current as FamilyInstance;
                if ((familyInstance != null) && (familyInstance.StructuralType == Autodesk.Revit.DB.Structure.StructuralType.Beam))
                {
                    m_beamList.Add(familyInstance);
                }
            }
            if (m_beamList.Count < 1)
            {
                throw new ApplicationException("there is no beam selected");
            }

            //Get the family symbols of tag in this document.
            FilteredElementCollector collector = new FilteredElementCollector(commandData.Application.ActiveUIDocument.Document);
            IList <Element>          elements  = collector.OfClass(typeof(Family)).ToElements();

            foreach (Family family in elements)
            {
                if (family != null && family.GetFamilySymbolIds() != null)
                {
                    List <FamilySymbol> ffs = new List <FamilySymbol>();
                    foreach (ElementId elementId in family.GetFamilySymbolIds())
                    {
                        ffs.Add((FamilySymbol)(commandData.Application.ActiveUIDocument.Document.GetElement(elementId)));
                    }
                    foreach (FamilySymbol tagSymbol in ffs)
                    {
                        try
                        {
                            if (tagSymbol != null)
                            {
                                switch (tagSymbol.Category.Name)
                                {
                                case "Structural Framing Tags":
                                    m_categoryTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                    continue;

                                case "Material Tags":
                                    m_materialTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                    continue;

                                case "Multi-Category Tags":
                                    m_multiCategoryTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                    continue;

                                default:
                                    continue;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private Autodesk.Revit.DB.View m_view; // current view

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of TagBeamData. 
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command</param>
        public TagBeamData(ExternalCommandData commandData)
        {
            //Get beams selected
               m_revitDoc = commandData.Application.ActiveUIDocument;
               m_docCreator = m_revitDoc.Document.Create;
               m_view = m_revitDoc.Document.ActiveView;

               SelElementSet elementSet = m_revitDoc.Selection.Elements;
            ElementSetIterator itor = elementSet.ForwardIterator();
            while (itor.MoveNext())
            {
                FamilyInstance familyInstance = itor.Current as FamilyInstance;
                if ((familyInstance != null) && (familyInstance.StructuralType == Autodesk.Revit.DB.Structure.StructuralType.Beam))
                {
                    m_beamList.Add(familyInstance);
                }
            }
            if (m_beamList.Count < 1)
            {
                throw new ApplicationException("there is no beam selected");
            }

            //Get the family symbols of tag in this document.
            FilteredElementCollector collector = new FilteredElementCollector(commandData.Application.ActiveUIDocument.Document);
            IList<Element> elements = collector.OfClass(typeof(Family)).ToElements();

            foreach (Family family in elements)
            {
               if (family != null && family.Symbols != null)
               {
                  FamilySymbolSetIterator it = family.Symbols.ForwardIterator();
                  while (it.MoveNext())
                  {
                     try
                     {
                        FamilySymbol tagSymbol = it.Current as FamilySymbol;
                        if (tagSymbol != null)
                        {
                           switch (tagSymbol.Category.Name)
                           {
                              case "Structural Framing Tags":
                                 m_categoryTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                 continue;
                              case "Material Tags":
                                 m_materialTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                 continue;
                              case "Multi-Category Tags":
                                 m_multiCategoryTagTypes.Add(new FamilySymbolWrapper(tagSymbol));
                                 continue;
                              default:
                                 continue;
                           }
                        }
                     }
                     catch (Exception)
                     {
                        continue;
                     }
                  }
               }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Create wall system, floor, and allocate rooms
        /// </summary>

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            Autodesk.Revit.Creation.Application appCreation = app.Create;
            Autodesk.Revit.Creation.Document    docCreation = doc.Create;

            // Access current selection
            Selection sel = uidoc.Selection;

            // Extraction of CurveElements by LineStyle WALL
            CurveElementFilter       filter       = new CurveElementFilter(CurveElementType.ModelCurve);
            FilteredElementCollector collector    = new FilteredElementCollector(doc);
            ICollection <Element>    founds       = collector.WherePasses(filter).ToElements();
            List <CurveElement>      importCurves = new List <CurveElement>();

            foreach (CurveElement ce in founds)
            {
                importCurves.Add(ce);
            }
            var          strayCurves = importCurves.Where(x => x.LineStyle.Name == "WALL").ToList();
            List <Curve> strayLines  = new List <Curve>();

            foreach (CurveElement ce in strayCurves)
            {
                strayLines.Add(ce.GeometryCurve as Line);
            }


            // Grab the current building level
            FilteredElementCollector colLevels = new FilteredElementCollector(doc)
                                                 .WhereElementIsNotElementType()
                                                 .OfCategory(BuiltInCategory.INVALID)
                                                 .OfClass(typeof(Level));
            Level firstLevel = colLevels.FirstElement() as Level;


            // Grab the building view
            // This may be useful when handling room allocation on separate levels
            //FilteredElementCollector colViews = new FilteredElementCollector(doc)
            //    .OfClass(typeof(View));
            //View firstView = colViews.FirstElement() as View;


            // Grab the building floortype
            FloorType floorType = new FilteredElementCollector(doc)
                                  .OfClass(typeof(FloorType))
                                  .First <Element>(e => e.Name.Equals("Generic 150mm")) as FloorType;


            // Modify document within a transaction
            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Generate Walls");

                List <CurveArray> curveGroup = RegionCluster(strayLines);
                //var (mesh, perimeter) = FlattenLines(curveGroup);

                Plane       Geomplane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero);
                SketchPlane sketch    = SketchPlane.Create(doc, Geomplane);

                foreach (CurveArray group in curveGroup)
                {
                    foreach (Curve edge in group)
                    {
                        DetailLine    axis = doc.Create.NewDetailCurve(view, edge) as DetailLine;
                        GraphicsStyle gs   = axis.LineStyle as GraphicsStyle;
                        gs.GraphicsStyleCategory.LineColor = new Color(202, 51, 82);
                        gs.GraphicsStyleCategory.SetLineWeight(7, gs.GraphicsStyleType);
                    }
                }


                /*
                 * Region detect and boolean union all have bugs to fix
                 * DO NOT TEST THIS ONE
                 *
                 *
                 *
                 * // Wall generation
                 * foreach (Curve wallAxis in mesh)
                 * {
                 *  Wall.Create(doc, wallAxis, firstLevel.Id, true);
                 * }
                 *
                 * // Create.NewRoom will automatically detect the topology according to the wall system
                 * // Don't bother sketching boundary lines unless you're handling a virtual room
                 * //docCreation.NewSpaceBoundaryLines(doc.ActiveView.SketchPlane, mesh, doc.ActiveView);
                 * doc.Regenerate();
                 *
                 * PlanTopology planTopology = doc.get_PlanTopology(firstLevel);
                 * if (doc.ActiveView.ViewType == ViewType.FloorPlan)
                 * {
                 *  foreach (PlanCircuit circuit in planTopology.Circuits)
                 *  {
                 *      if (null != circuit && !circuit.IsRoomLocated)
                 *      {
                 *          var room = doc.Create.NewRoom(null, circuit);
                 *          //Debug.Print("New room created!");
                 *      }
                 *  }
                 * }
                 * /* // add error handling here
                 * else
                 * {
                 *  System.Windows.Forms.MessageBox.Show("You can not create spaces in this plan view");
                 * }
                 */
                /*
                 * Floor newFloor = doc.Create.NewFloor(AlignCrv(perimeter), floorType, firstLevel, false, XYZ.BasisZ);
                 * newFloor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set(0);
                 */

                tx.Commit();
            }


            return(Result.Succeeded);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="commandData">object which contains reference to Revit Application</param>
 protected Profile(ExternalCommandData commandData)
 {
     m_commandData = commandData;
     m_appCreator  = m_commandData.Application.Application.Create;
     m_docCreator  = m_commandData.Application.ActiveUIDocument.Document.Create;
 }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Debug.Assert(false, "This has not been tested since Revit 2010!");

            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            Autodesk.Revit.Creation.Application ca
                = app.Application.Create;

            Autodesk.Revit.Creation.Document cd
                = doc.Create;

            // determine line load symbol to use:

            FilteredElementCollector symbols
                = new FilteredElementCollector(doc);

            symbols.OfClass(typeof(LineLoadType));

            LineLoadType loadSymbol
                = symbols.FirstElement() as LineLoadType;

            // sketch plane and arrays of forces and moments:

            //Plane plane = ca.NewPlane( XYZ.BasisZ, XYZ.Zero ); // 2016
            Plane plane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero); // 2017

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create New Line Load");

                //SketchPlane skplane = cd.NewSketchPlane( plane ); // 2013

                SketchPlane skplane = SketchPlane.Create(doc, plane); // 2014

                XYZ        forceA = new XYZ(0, 0, 5);
                XYZ        forceB = new XYZ(0, 0, 10);
                List <XYZ> forces = new List <XYZ>();
                forces.Add(forceA);
                forces.Add(forceB);

                XYZ        momentA = new XYZ(0, 0, 0);
                XYZ        momentB = new XYZ(0, 0, 0);
                List <XYZ> moments = new List <XYZ>();
                moments.Add(momentA);
                moments.Add(momentB);

                BuiltInCategory bic
                    = BuiltInCategory.OST_StructuralFraming;

                FilteredElementCollector beams = Util.GetElementsOfType(
                    doc, typeof(FamilyInstance), bic);

                XYZ p1 = new XYZ(0, 0, 0);
                XYZ p2 = new XYZ(3, 0, 0);
                //List<XYZ> points = new List<XYZ>();
                //points.Add( p1 );
                //points.Add( p2 );

                // create a new unhosted line load on points:

                //LineLoad lineLoadNoHost = cd.NewLineLoad(
                //  points, forces, moments,
                //  false, false, false,
                //  loadSymbol, skplane ); // 2015

                LineLoad lineLoadNoHost = LineLoad.Create(doc,
                                                          p1, p2, forces[0], moments[0],
                                                          loadSymbol, skplane); // 2016

                Debug.Print("Unhosted line load works.");

                // create new line loads on beam:

                foreach (Element e in beams)
                {
                    try
                    {
                        //LineLoad lineLoad = cd.NewLineLoad(
                        //  e, forces, moments,
                        //  false, false, false,
                        //  loadSymbol, skplane ); // 2015

                        AnalyticalModelSurface amsurf = e.GetAnalyticalModel()
                                                        as AnalyticalModelSurface;

                        LineLoad lineLoad = LineLoad.Create(doc,
                                                            amsurf, 0, forces[0], moments[0], loadSymbol); // 2016

                        Debug.Print("Hosted line load on beam works.");
                    }
                    catch (Exception ex)
                    {
                        Debug.Print("Hosted line load on beam fails: "
                                    + ex.Message);
                    }

                    FamilyInstance i = e as FamilyInstance;

                    AnalyticalModel am = i.GetAnalyticalModel();

                    foreach (Curve curve in
                             am.GetCurves(AnalyticalCurveType.ActiveCurves))
                    {
                        try
                        {
                            //LineLoad lineLoad = cd.NewLineLoad(
                            //  curve.Reference, forces, moments,
                            //  false, false, false,
                            //  loadSymbol, skplane ); // 2015

                            AnalyticalModelStick amstick = e.GetAnalyticalModel()
                                                           as AnalyticalModelStick;

                            LineLoad lineLoad = LineLoad.Create(doc,
                                                                amstick, forces[0], moments[0], loadSymbol); // 2016

                            Debug.Print("Hosted line load on "
                                        + "AnalyticalModelFrame curve works.");
                        }
                        catch (Exception ex)
                        {
                            Debug.Print("Hosted line load on "
                                        + "AnalyticalModelFrame curve fails: "
                                        + ex.Message);
                        }
                    }
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="commandData">object which contains reference to Revit Application</param>
 protected Profile(ExternalCommandData commandData)
 {
     m_commandData = commandData;
     m_appCreator = m_commandData.Application.Application.Create;
     m_docCreator = m_commandData.Application.ActiveUIDocument.Document.Create;
 }
Ejemplo n.º 24
0
 /// <summary>
 /// The construct of ExtrusionRoofManager class.
 /// </summary>
 /// <param name="commandData">A reference to the commandData.</param>
 public ExtrusionRoofManager(ExternalCommandData commandData)
 {
     m_commandData = commandData;
     m_creationDoc = m_commandData.Application.ActiveUIDocument.Document.Create;
     m_creationApp = m_commandData.Application.Application.Create;
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Constructor without display unit type
 /// </summary>
 /// <param name="application">Revit application</param>
 /// <param name="labels">All existing labels in Revit's document</param>
 public CreateGridsData(UIApplication application, ArrayList labels)
 {
     m_revitDoc = application.ActiveUIDocument.Document;
     m_appCreator = application.Application.Create;
     m_docCreator = application.ActiveUIDocument.Document.Create;
     m_labelsList = labels;
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Alternative implementation published January 23, 2015:
        /// http://thebuildingcoder.typepad.com/blog/2015/01/getting-the-wall-elevation-profile.html
        /// </summary>
        public Result Execute2(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            Autodesk.Revit.Creation.Application creapp
                = app.Create;

            Autodesk.Revit.Creation.Document credoc
                = doc.Create;

            Reference r = uidoc.Selection.PickObject(
                ObjectType.Element, "Select a wall");

            Element e = uidoc.Document.GetElement(r);

            Wall wall = e as Wall;

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Wall Profile");

                // Get the external wall face for the profile

                IList <Reference> sideFaces
                    = HostObjectUtils.GetSideFaces(wall,
                                                   ShellLayerType.Exterior);

                Element e2 = doc.GetElement(sideFaces[0]);

                Face face = e2.GetGeometryObjectFromReference(
                    sideFaces[0]) as Face;

                // The normal of the wall external face.

                XYZ normal = face.ComputeNormal(new UV(0, 0));

                // Offset curve copies for visibility.

                Transform offset = Transform.CreateTranslation(
                    5 * normal);

                // If the curve loop direction is counter-
                // clockwise, change its color to RED.

                Color colorRed = new Color(255, 0, 0);

                // Get edge loops as curve loops.

                IList <CurveLoop> curveLoops
                    = face.GetEdgesAsCurveLoops();

                // ExporterIFCUtils class can also be used for
                // non-IFC purposes. The SortCurveLoops method
                // sorts curve loops (edge loops) so that the
                // outer loops come first.

                IList <IList <CurveLoop> > curveLoopLoop
                    = ExporterIFCUtils.SortCurveLoops(
                          curveLoops);

                foreach (IList <CurveLoop> curveLoops2
                         in curveLoopLoop)
                {
                    foreach (CurveLoop curveLoop2 in curveLoops2)
                    {
                        // Check if curve loop is counter-clockwise.

                        bool isCCW = curveLoop2.IsCounterclockwise(
                            normal);

                        CurveArray curves = creapp.NewCurveArray();

                        foreach (Curve curve in curveLoop2)
                        {
                            curves.Append(curve.CreateTransformed(offset));
                        }

                        // Create model lines for an curve loop.

                        //Plane plane = creapp.NewPlane( curves ); // 2016

                        Plane plane = curveLoop2.GetPlane(); // 2017

                        SketchPlane sketchPlane
                            = SketchPlane.Create(doc, plane);

                        ModelCurveArray curveElements
                            = credoc.NewModelCurveArray(curves,
                                                        sketchPlane);

                        if (isCCW)
                        {
                            foreach (ModelCurve mcurve in curveElements)
                            {
                                OverrideGraphicSettings overrides
                                    = view.GetElementOverrides(
                                          mcurve.Id);

                                overrides.SetProjectionLineColor(
                                    colorRed);

                                view.SetElementOverrides(
                                    mcurve.Id, overrides);
                            }
                        }
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 27
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            try
            {
                WaitCursor    waitCursor = new WaitCursor();
                UIApplication app        = commandData.Application;
                Document      doc        = app.ActiveUIDocument.Document;
                Autodesk.Revit.Creation.Application createApp = app.Application.Create;
                Autodesk.Revit.Creation.Document    createDoc = doc.Create;

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Create Little House");

                    // Determine the four corners of the rectangular house:

                    double width = 7 * LabConstants.MeterToFeet;
                    double depth = 4 * LabConstants.MeterToFeet;

                    List <XYZ> corners = new List <XYZ>(4);

                    corners.Add(XYZ.Zero);
                    corners.Add(new XYZ(width, 0, 0));
                    corners.Add(new XYZ(width, depth, 0));
                    corners.Add(new XYZ(0, depth, 0));

                    #region Test creating two levels
#if CREATE_TWO_LEVELS
                    Level          levelBottom = null;
                    Level          levelMiddle = null;
                    Level          levelTop    = null;
                    List <Element> levels      = new List <Element>();

                    Filter filterType
                        = createApp.Filter.NewTypeFilter(
                              typeof(Level));

                    doc.get_Elements(filterType, levels);
                    foreach (Element e in levels)
                    {
                        if (null == levelBottom)
                        {
                            levelBottom = e as Level;
                        }
                        else if (null == levelMiddle)
                        {
                            levelMiddle = e as Level;
                        }
                        else if (null == levelTop)
                        {
                            levelTop = e as Level;
                        }
                        else
                        {
                            break;
                        }
                    }

                    BuiltInParameter topLevelParam
                        = BuiltInParameter.WALL_HEIGHT_TYPE;

                    Line      line;
                    Wall      wall;
                    Parameter param;

                    ElementId   topId = levelMiddle.Id;
                    List <Wall> walls = new List <Wall>(8);
                    for (int i = 0; i < 4; ++i)
                    {
                        line = createApp.NewLineBound(
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        wall = createDoc.NewWall(
                            line, levelBottom, false);

                        param = wall.get_Parameter(topLevelParam);
                        param.Set(ref topId);
                        walls.Add(wall);
                    }

                    topId = levelTop.Id;
                    for (int i = 0; i < 4; ++i)
                    {
                        line = createApp.NewLineBound(
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        wall = createDoc.NewWall(
                            line, levelMiddle, false);

                        param = wall.get_Parameter(topLevelParam);
                        param.Set(ref topId);
                        walls.Add(wall);
                    }

                    List <Element> doorSymbols
                        = LabUtils.GetAllFamilySymbols(
                              app, BuiltInCategory.OST_Doors);

                    Debug.Assert(
                        0 < doorSymbols.Count,
                        "expected at least one door symbol"
                        + " to be loaded into project");

                    FamilySymbol door
                        = doorSymbols[0] as FamilySymbol;

                    XYZ midpoint = LabUtils.Midpoint(
                        corners[0], corners[1]);

                    FamilyInstance inst0
                        = createDoc.NewFamilyInstance(
                              midpoint, door, walls[0], levelBottom,
                              StructuralType.NonStructural);

                    midpoint.Z = levelMiddle.Elevation;

                    FamilyInstance inst1
                        = createDoc.NewFamilyInstance(
                              midpoint, door, walls[4], levelMiddle,
                              StructuralType.NonStructural);
#endif // CREATE_TWO_LEVELS
                    #endregion // Test creating two levels

                    // Determine the levels where the walls will be located:

                    Level levelBottom = null;
                    Level levelTop    = null;

                    if (!LabUtils.GetBottomAndTopLevels(doc, ref levelBottom, ref levelTop))
                    {
                        message = "Unable to determine wall bottom and top levels";
                        return(Result.Failed);
                    }
                    Debug.Print(string.Format("Drawing walls on '{0}' up to '{1}'",
                                              levelBottom.Name, levelTop.Name));

                    // Create the walls:

                    BuiltInParameter topLevelParam = BuiltInParameter.WALL_HEIGHT_TYPE;
                    ElementId        levelBottomId = levelBottom.Id;
                    ElementId        topLevelId    = levelTop.Id;
                    List <Wall>      walls         = new List <Wall>(4);

                    for (int i = 0; i < 4; ++i)
                    {
                        Line line = Line.CreateBound(corners[i], corners[3 == i ? 0 : i + 1]);
                        //Wall wall = createDoc.NewWall( line, levelBottom, false ); // 2012
                        Wall      wall  = Wall.Create(doc, line, levelBottomId, false); // 2013
                        Parameter param = wall.get_Parameter(topLevelParam);
                        param.Set(topLevelId);
                        walls.Add(wall);
                    }

                    // Determine wall thickness for tag offset and profile growth:

                    //double wallThickness = walls[0].WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011
                    //double wallThickness = walls[0].WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012
                    double wallThickness = walls[0].WallType.Width; // simpler and more direct property available in 2012

                    // Add door and windows to the first wall;
                    // note that the NewFamilyInstance() api method does not automatically add door
                    // and window tags, like the ui command does. we add tags here by making additional calls
                    // to NewTag():

                    FamilySymbol door = LabUtils.GetFirstFamilySymbol(doc, BuiltInCategory.OST_Doors);
                    if (null == door)
                    {
                        LabUtils.InfoMsg("No door symbol found.");
                        return(Result.Failed);
                    }
                    FamilySymbol window = LabUtils.GetFirstFamilySymbol(
                        doc, BuiltInCategory.OST_Windows);

                    if (null == window)
                    {
                        LabUtils.InfoMsg("No window symbol found.");
                        return(Result.Failed);
                    }

                    XYZ    midpoint  = LabUtils.Midpoint(corners[0], corners[1]);
                    XYZ    p         = LabUtils.Midpoint(corners[0], midpoint);
                    XYZ    q         = LabUtils.Midpoint(midpoint, corners[1]);
                    double tagOffset = 3 * wallThickness;

                    //double windowHeight = 1 * LabConstants.MeterToFeet;
                    double windowHeight = levelBottom.Elevation + 0.3 * (
                        levelTop.Elevation - levelBottom.Elevation);

                    p = new XYZ(p.X, p.Y, windowHeight);
                    q = new XYZ(q.X, q.Y, windowHeight);
                    View view = doc.ActiveView;

                    door.Activate(); // 2016

                    FamilyInstance inst = createDoc.NewFamilyInstance(
                        midpoint, door, walls[0], levelBottom, StructuralType.NonStructural);

                    midpoint += tagOffset * XYZ.BasisY;

                    //IndependentTag tag = createDoc.NewTag(
                    //  view, inst, false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, midpoint ); // 2017

                    IndependentTag tag = IndependentTag.Create(
                        doc, view.Id, new Reference(inst),
                        false, TagMode.TM_ADDBY_CATEGORY,
                        TagOrientation.Horizontal, midpoint); // 2018

                    IList <FamilyPointPlacementReference> fpprefs = inst.GetFamilyPointPlacementReferences();
                    IList <Reference> refs = inst.GetReferences(FamilyInstanceReferenceType.CenterLeftRight);

                    //IndependentTag tag = IndependentTag.Create( doc,
                    //  view.Id, refs[0], false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, midpoint ); // 2018

                    window.Activate(); // 2016

                    inst = createDoc.NewFamilyInstance(p, window,
                                                       walls[0], levelBottom, StructuralType.NonStructural);

                    p += tagOffset * XYZ.BasisY;

                    //tag = createDoc.NewTag( view, inst,
                    //  false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, p ); // 2017

                    tag = IndependentTag.Create(
                        doc, view.Id, new Reference(inst),
                        false, TagMode.TM_ADDBY_CATEGORY,
                        TagOrientation.Horizontal, p); // 2018

                    inst = createDoc.NewFamilyInstance(q, window, walls[0],
                                                       levelBottom, StructuralType.NonStructural);

                    q += tagOffset * XYZ.BasisY;

                    //tag = createDoc.NewTag( view, inst,
                    //  false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.TAG_HORIZONTAL, q ); // 2011

                    //tag = createDoc.NewTag( view, inst,
                    //  false, TagMode.TM_ADDBY_CATEGORY,
                    //  TagOrientation.Horizontal, q ); // 2012

                    tag = IndependentTag.Create(
                        doc, view.Id, new Reference(inst),
                        false, TagMode.TM_ADDBY_CATEGORY,
                        TagOrientation.Horizontal, p); // 2018

                    // Grow the profile out by half the wall thickness,
                    // so the floor and roof do not stop halfway through the wall:

                    double w = 0.5 * wallThickness;
                    corners[0] -= w * (XYZ.BasisX + XYZ.BasisY);
                    corners[1] += w * (XYZ.BasisX - XYZ.BasisY);
                    corners[2] += w * (XYZ.BasisX + XYZ.BasisY);
                    corners[3] -= w * (XYZ.BasisX - XYZ.BasisY);
                    CurveArray profile = new CurveArray();
                    for (int i = 0; i < 4; ++i)
                    {
                        //Line line = createApp.NewLineBound( // 2013

                        Line line = Line.CreateBound( // 2014
                            corners[i], corners[3 == i ? 0 : i + 1]);

                        profile.Append(line);
                    }

                    // Add a floor, a roof and the roof slope:

                    bool  structural = false;
                    Floor floor      = createDoc.NewFloor(
                        profile, structural);

                    List <Element> roofTypes
                        = new List <Element>(
                              LabUtils.GetElementsOfType(
                                  doc, typeof(RoofType),
                                  BuiltInCategory.OST_Roofs));

                    Debug.Assert(0 < roofTypes.Count,
                                 "expected at least one roof type"
                                 + " to be loaded into project");

                    // Ensure that we get a valid roof type.
                    // In Revit 2013, the first one encountered
                    // is sloped glazing with zero entries in
                    // its compound layers; actually, the entire
                    // compound structure is null:

                    //RoofType roofType = null;
                    //foreach( RoofType rt in roofTypes )
                    //{
                    //  CompoundStructure cs = rt.GetCompoundStructure();
                    //  if( null != cs
                    //    && 0 < cs.GetLayers().Count )
                    //  {
                    //    roofType = rt;
                    //    break;
                    //  }
                    //}

                    RoofType roofType = roofTypes
                                        .Cast <RoofType>()
                                        .FirstOrDefault <RoofType>(typ
                                                                   => null != typ.GetCompoundStructure());

                    ModelCurveArray modelCurves
                        = new ModelCurveArray();

                    FootPrintRoof roof
                        = createDoc.NewFootPrintRoof(profile,
                                                     levelTop, roofType, out modelCurves);

                    // Regenerate the model after roof creation,
                    // otherwise the calls to set_DefinesSlope and
                    // set_SlopeAngle throw the exception "Unable
                    // to access curves from the roof sketch."

                    doc.Regenerate();

                    // The argument to set_SlopeAngle is NOT an
                    // angle, it is really a slope, i.e. relation
                    // of height to distance, e.g. 0.5 = 6" / 12",
                    // 0.75  = 9" / 12", etc.

                    double slope = 0.3;

                    foreach (ModelCurve curve in modelCurves)
                    {
                        roof.set_DefinesSlope(curve, true);
                        roof.set_SlopeAngle(curve, slope);
                    }

                    // Add a room and a room tag:

                    Room room = createDoc.NewRoom(levelBottom,
                                                  new UV(0.5 * width, 0.5 * depth));

                    //RoomTag roomTag = createDoc.NewRoomTag(
                    //  room, new UV( 0.5 * width, 0.7 * depth ),
                    //  null ); // 2014

                    RoomTag roomTag = createDoc.NewRoomTag(
                        new LinkElementId(room.Id),
                        new UV(0.5 * width, 0.7 * depth),
                        null); // 2015

                    //doc.AutoJoinElements(); // todo: remove this, the transaction should perform this automatically

                    //LabUtils.InfoMsg( "Little house was created successfully." );

                    //#region Test setting BaseOffset and LimitOffset
                    //// 11334196 [Failed to set Room.BaseOffset and Room.LimitOffset properties]
                    //double h = 0.123;
                    //room.BaseOffset = -h;
                    //room.LimitOffset = h + h;
                    //#endregion // Test setting BaseOffset and LimitOffset

                    t.Commit();

                    return(Result.Succeeded);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Improved implementation by Alexander Ignatovich
        /// supporting curved wall with curved window,
        /// second attempt, published April 10, 2015:
        /// </summary>
        public Result Execute3(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            Autodesk.Revit.Creation.Application creapp
                = app.Create;

            Autodesk.Revit.Creation.Document credoc
                = doc.Create;

            Reference r = uidoc.Selection.PickObject(
                ObjectType.Element, "Select a wall");

            Element e = uidoc.Document.GetElement(r);

            Creator creator = new Creator(doc);

            Wall wall = e as Wall;

            if (wall == null)
            {
                return(Result.Cancelled);
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Wall Profile");

                // Get the external wall face for the profile
                // a little bit simpler than in the last realization

                Reference sideFaceReference
                    = HostObjectUtils.GetSideFaces(
                          wall, ShellLayerType.Exterior)
                      .First();

                Face face = wall.GetGeometryObjectFromReference(
                    sideFaceReference) as Face;

                // The normal of the wall external face.

                XYZ normal = wall.Orientation;

                // Offset curve copies for visibility.

                Transform offset = Transform.CreateTranslation(
                    5 * normal);

                // If the curve loop direction is counter-
                // clockwise, change its color to RED.

                Color colorRed = new Color(255, 0, 0);

                // Get edge loops as curve loops.

                IList <CurveLoop> curveLoops
                    = face.GetEdgesAsCurveLoops();

                foreach (var curveLoop in curveLoops)
                {
                    CurveArray curves = creapp.NewCurveArray();

                    foreach (Curve curve in curveLoop)
                    {
                        curves.Append(curve.CreateTransformed(
                                          offset));
                    }

                    var isCounterClockwize = curveLoop
                                             .IsCounterclockwise(normal);

                    // Create model lines for an curve loop if it is made

                    if (((LocationCurve)wall.Location).Curve
                        is Line)
                    {
                        //Plane plane = creapp.NewPlane( curves ); // 2016
                        Plane plane = CurveLoop.CreateViaOffset(
                            curveLoop, 5 * normal.GetLength(),
                            normal.Normalize()).GetPlane(); // 2017

                        SketchPlane sketchPlane
                            = SketchPlane.Create(doc, plane);

                        ModelCurveArray curveElements = credoc
                                                        .NewModelCurveArray(curves, sketchPlane);

                        if (isCounterClockwize)
                        {
                            SetModelCurvesColor(curveElements,
                                                view, colorRed);
                        }
                    }
                    else
                    {
                        foreach (var curve in curves.Cast <Curve>())
                        {
                            var curveElements = creator.CreateModelCurves(curve);
                            if (isCounterClockwize)
                            {
                                SetModelCurvesColor(curveElements, view, colorRed);
                            }
                        }
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
        /// <summary>
        /// Improved implementation by Alexander Ignatovich
        /// supporting curved wall with curved window,
        /// second attempt, published April 10, 2015:
        /// </summary>
        public Result Execute3(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            Autodesk.Revit.Creation.Application creapp
                = app.Create;

            Autodesk.Revit.Creation.Document credoc
                = doc.Create;

            Reference r = uidoc.Selection.PickObject(
                ObjectType.Element, "Select a wall");

            Element e = uidoc.Document.GetElement(r);

            Creator creator = new Creator(doc);

            Wall wall = e as Wall;

            if (wall == null)
            {
                return(Result.Cancelled);
            }

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Wall Profile");

                // Get the external wall face for the profile
                // a little bit simpler than in the last
                // implementation in Execute2.

                Reference sideFaceReference
                    = HostObjectUtils.GetSideFaces(
                          wall, ShellLayerType.Exterior)
                      .First();

                Face face = wall.GetGeometryObjectFromReference(
                    sideFaceReference) as Face;

                // The plane and normal of the wall external face.

                XYZ       normal  = wall.Orientation.Normalize();
                Transform ftx     = face.ComputeDerivatives(UV.Zero);
                XYZ       forigin = ftx.Origin;
                XYZ       fnormal = ftx.BasisZ;

                Debug.Print(
                    "wall orientation {0}, face origin {1}, face normal {2}",
                    Util.PointString(normal),
                    Util.PointString(forigin),
                    Util.PointString(fnormal));

                // Offset distance.

                double d = 5;

                // Offset curve copies for visibility.

                XYZ       voffset = d * normal;
                Transform offset  = Transform.CreateTranslation(
                    voffset);

                // If the curve loop direction is counter-
                // clockwise, change its color to RED.

                Color colorRed = new Color(255, 0, 0);

                // Get edge loops as curve loops.

                IList <CurveLoop> curveLoops
                    = face.GetEdgesAsCurveLoops();

                foreach (var curveLoop in curveLoops)
                {
                    //CurveLoop curveLoopOffset = CurveLoop.CreateViaOffset(
                    //  curveLoop, d, normal );

                    CurveArray curves = creapp.NewCurveArray();

                    foreach (Curve curve in curveLoop)
                    {
                        curves.Append(curve.CreateTransformed(
                                          offset));
                    }

                    var isCounterClockwize = curveLoop
                                             .IsCounterclockwise(normal);

                    // Create model lines for an curve loop if it is made

                    Curve wallCurve = ((LocationCurve)wall.Location).Curve;

                    if (wallCurve is Line)
                    {
                        //Plane plane = creapp.NewPlane( curves ); // 2016

                        //Plane plane = curveLoopOffset.GetPlane(); // 2017

                        Plane plane = Plane.CreateByNormalAndOrigin( // 2019
                            normal, forigin + voffset);

                        Debug.Print(
                            "plane origin {0}, plane normal {1}",
                            Util.PointString(plane.Origin),
                            Util.PointString(plane.Normal));

                        SketchPlane sketchPlane
                            = SketchPlane.Create(doc, plane);

                        ModelCurveArray curveElements = credoc
                                                        .NewModelCurveArray(curves, sketchPlane);

                        if (isCounterClockwize)
                        {
                            SetModelCurvesColor(curveElements,
                                                view, colorRed);
                        }
                    }
                    else
                    {
                        foreach (var curve in curves.Cast <Curve>())
                        {
                            var curveElements = creator.CreateModelCurves(curve);
                            if (isCounterClockwize)
                            {
                                SetModelCurvesColor(curveElements, view, colorRed);
                            }
                        }
                    }
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Result        rc  = Result.Failed;
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            // Check whether the family we are interested in is loaded:

#if _2010
            List <Element> symbols      = new List <Element>();
            Filter         filterFamily = creApp.Filter.NewFamilyFilter(_family_name);
            doc.get_Elements(filterFamily, symbols);

            // the family filter returns both the symbols and the family itself:

            Family f = null;
            foreach (Element e in symbols)
            {
                if (e is Family)
                {
                    f = e as Family;
                }
                else if (e is FamilySymbol)
                {
                    FamilySymbol s = e as FamilySymbol;
                    Debug.Print("Family name={0}, symbol name={1}", s.Family.Name, s.Name);
                }
            }
#endif // _2010

            Family f = Util.GetFirstElementOfTypeNamed(
                doc, typeof(Family), _family_name) as Family;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Beam Type and Instance");
                // If the family was not already loaded, then do so:

                if (null == f)
                {
                    if (!doc.LoadFamily(_path, out f))
                    {
                        message = "Unable to load '" + _path + "'.";
                    }
                }

                if (null != f)
                {
                    Debug.Print("Family name={0}", f.Name);

                    // Pick a symbol for duplication, any one will do,
                    // we select the first:

                    FamilySymbol s = null;

                    //foreach( FamilySymbol s2 in f.Symbols ) // 2014

                    foreach (ElementId id in f.GetFamilySymbolIds()) // 2015
                    {
                        s = doc.GetElement(id) as FamilySymbol;
                        break;
                    }

                    Debug.Assert(null != s, "expected at least one symbol to be defined in family");

                    // Duplicate the existing symbol:

                    ElementType s1 = s.Duplicate("Nuovo simbolo");
                    s = s1 as FamilySymbol;

                    // Analyse the symbol parameters:

                    foreach (Parameter param in s.Parameters)
                    {
                        Debug.Print("Parameter name={0}, value={1}", param.Definition.Name, param.AsValueString());
                    }

                    // Define new dimensions for our new type;
                    // the specified parameter name is case sensitive:

                    //s.get_Parameter( "b" ).Set( Util.MmToFoot( 500 ) ); // 2014
                    //s.get_Parameter( "h" ).Set( Util.MmToFoot( 1000 ) ); // 2014

                    s.LookupParameter("b").Set(Util.MmToFoot(500));  // 2015
                    s.LookupParameter("h").Set(Util.MmToFoot(1000)); // 2015

                    // we can change the symbol name at any time:

                    s.Name = "Nuovo simbolo due";

                    // insert an instance of our new symbol:

                    Autodesk.Revit.Creation.Application creApp = app.Application.Create;
                    Autodesk.Revit.Creation.Document    creDoc = doc.Create;

                    // It is possible to insert a beam,
                    // which normally uses a location line,
                    // by specifying only a location point:

                    //XYZ p = XYZ.Zero;
                    //doc.Create.NewFamilyInstance( p, s, nonStructural );

                    XYZ  p    = XYZ.Zero;
                    XYZ  q    = creApp.NewXYZ(30, 20, 20); // feet
                    Line line = Line.CreateBound(p, q);

                    // Specifying a non-structural type here means no beam
                    // is created, and results in a null family instance:

                    FamilyInstance fi = creDoc.NewFamilyInstance(
                        line, s, null, stBeam);

                    // This creates a visible family instance,
                    // but the resulting beam has no location line
                    // and behaves strangely, e.g. cannot be selected:
                    //FamilyInstance fi = doc.Create.NewFamilyInstance(
                    //  p, s, q, null, nonStructural );

                    //List<Element> levels = new List<Element>();
                    //doc.get_Elements( typeof( Level ), levels );
                    //Debug.Assert( 0 < levels.Count,
                    //  "expected at least one level in model" );
                    //Level level = levels[0] as Level;
                    //fi = doc.Create.NewFamilyInstance(
                    //  line, s, level, nonStructural );

                    rc = Result.Succeeded;
                }
                t.Commit();
            }
            return(rc);
        }
Ejemplo n.º 31
0
        RoomArea()
        {
            Revit.Creation.Document doc         = m_revitApp.ActiveUIDocument.Document.Create;
            SketchPlane             sketchPlane = Utils.Geometry.GetWorldPlane(m_revitApp);

            RevitLookup.Test.Forms.Levels lev = new RevitLookup.Test.Forms.Levels(m_revitApp);
            if (lev.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            Level curLevel = lev.LevelSelected;

            if (curLevel == null)
            {
                MessageBox.Show("No Level was selected.");
                return;
            }

            // Get the plan topology of the active doc first
            PlanTopology            planTopo = m_revitApp.ActiveUIDocument.Document.get_PlanTopology(curLevel);
            ICollection <ElementId> roomIds  = planTopo.GetRoomIds();

            if (roomIds.Count > 0)
            {
                IEnumerator <ElementId> setIter = roomIds.GetEnumerator();
                while (setIter.MoveNext())
                {
                    Room room = m_revitApp.ActiveUIDocument.Document.GetElement(setIter.Current) as Room;
                    if (null != room)
                    {
                        Autodesk.Revit.DB.View view          = m_revitApp.ActiveUIDocument.Document.ActiveView;
                        LocationPoint          locationPoint = room.Location as LocationPoint;

                        Double area = room.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble();

                        Double roundedArea = Math.Round(area, 2);

                        // providing an offset so that the Room Tag and the Area Tag dont overlap. Overlapping leads to an
                        // alignment related assert.

                        XYZ offset = new XYZ(5.0, 0, 0);

                        /// align text middle and center
                        TextAlignFlags align   = TextAlignFlags.TEF_ALIGN_MIDDLE ^ TextAlignFlags.TEF_ALIGN_CENTER;
                        TextNote       txtNote = m_revitApp.ActiveUIDocument.Document.Create.NewTextNote(view, offset + locationPoint.Point, GeomUtils.kXAxis,
                                                                                                         view.ViewDirection, .25,
                                                                                                         align, roundedArea.ToString());
                    }
                }
            }
            else
            {
                MessageBox.Show("No rooms found in the Active Document", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


            // TBD: Tried to play around with PlanCircuits and there seems to be a problem with the IsRoomLocated property.
            // arj 1/23/07

            //Revit.PlanCircuitSet circSet = planTopo.Circuits;
            //Revit.PlanCircuitSetIterator setIters = circSet.ForwardIterator();

            //while (setIters.MoveNext())
            //{
            //    Revit.PlanCircuit planCircuit = setIters.Current as Revit.PlanCircuit;

            //    if (null != planCircuit)
            //    {
            //
            //        if (planCircuit.IsRoomLocated) // throws an exception always "Attempted to read or write protected memory.
            // This is often an indication that other memory is corrupt."
            //        {
            //        }
            //    }
            //}
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            Autodesk.Revit.Creation.Application createApp
                = app.Application.Create;

            Autodesk.Revit.Creation.Document createDoc
                = doc.Create;

            // Determine the wall endpoints:

            double length = 5 * MeterToFeet;

            XYZ [] pts = new XYZ[2];

            pts[0] = XYZ.Zero;
            pts[1] = new XYZ(length, 0, 0);

            // Determine the levels where
            // the wall will be located:

            Level levelBottom = null;
            Level levelTop    = null;

            if (!GetBottomAndTopLevels(doc,
                                       ref levelBottom, ref levelTop))
            {
                message = "Unable to determine "
                          + "wall bottom and top levels";

                return(Result.Failed);
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create Wall, Door and Tag");

                // Create a wall:

                BuiltInParameter topLevelParam
                    = BuiltInParameter.WALL_HEIGHT_TYPE;

                ElementId topLevelId = levelTop.Id;

                //Line line = createApp.NewLineBound( pts[0], pts[1] ); // 2013
                Line line = Line.CreateBound(pts[0], pts[1]); // 2014

                //Wall wall = createDoc.NewWall( // 2012
                //  line, levelBottom, false );

                Wall wall = Wall.Create( // 2013
                    doc, line, levelBottom.Id, false);

                Parameter param = wall.get_Parameter(
                    topLevelParam);

                param.Set(topLevelId);

                // Determine wall thickness for tag
                // offset and profile growth:

                //double wallThickness = wall.WallType.CompoundStructure.Layers.get_Item( 0 ).Thickness; // 2011

                double wallThickness = wall.WallType.GetCompoundStructure().GetLayers()[0].Width; // 2012

                // Add door to wall;
                // note that the NewFamilyInstance method
                // does not automatically add a door tag,
                // like the UI command does:

                FamilySymbol doorSymbol = GetFirstFamilySymbol(
                    doc, BuiltInCategory.OST_Doors);

                if (null == doorSymbol)
                {
                    message = "No door symbol found.";
                    return(Result.Failed);
                }

                XYZ midpoint = Util.Midpoint(pts[0], pts[1]);

                FamilyInstance door = createDoc
                                      .NewFamilyInstance(
                    midpoint, doorSymbol, wall, levelBottom,
                    StructuralType.NonStructural);

                // Create door tag:

                View view = doc.ActiveView;

                double tagOffset = 3 * wallThickness;

                midpoint += tagOffset * XYZ.BasisY;

                // 2011: TagOrientation.TAG_HORIZONTAL

                IndependentTag tag = createDoc.NewTag(
                    view, door, false, TagMode.TM_ADDBY_CATEGORY,
                    TagOrientation.Horizontal, midpoint); // 2012

                // Create and assign new door tag type:

                FamilySymbol doorTagType
                    = GetFirstFamilySymbol(
                          doc, BuiltInCategory.OST_DoorTags);

                doorTagType = doorTagType.Duplicate(
                    "New door tag type") as FamilySymbol;

                tag.ChangeTypeId(doorTagType.Id);

                // Demonstrate changing name of
                // family instance and family symbol:

                door.Name        = door.Name + " modified";
                door.Symbol.Name = door.Symbol.Name + " modified";

                t.Commit();
            }

            return(Result.Succeeded);
        }
Ejemplo n.º 33
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            Autodesk.Revit.Creation.Document creDoc
                = doc.Create;

            #region Check for pre-selected wall element
            Selection sel = uidoc.Selection;
            ICollection <ElementId> ids = sel.GetElementIds();

            if (1 == ids.Count)
            {
                Element e = doc.GetElement(ids.First <ElementId>());
                if (e is Wall)
                {
                    LocationCurve lc    = e.Location as LocationCurve;
                    Curve         curve = lc.Curve;

                    using (Transaction tx = new Transaction(doc))
                    {
                        tx.Start("Create Detail Line in Wall Centre");
                        creDoc.NewDetailCurve(view, curve);
                        tx.Commit();
                    }
                    return(Result.Succeeded);
                }
            }
            #endregion // Check for pre-selected wall element

            // Create a geometry line

            XYZ startPoint = new XYZ(0, 0, 0);
            XYZ endPoint   = new XYZ(10, 10, 0);

            //Line geomLine = creApp.NewLine( startPoint, endPoint, true ); // 2013

            Line geomLine = Line.CreateBound(startPoint, endPoint); // 2014

            // Create a geometry arc

            XYZ end0         = new XYZ(0, 0, 0);
            XYZ end1         = new XYZ(10, 0, 0);
            XYZ pointOnCurve = new XYZ(5, 5, 0);

            //Arc geomArc = creApp.NewArc( end0, end1, pointOnCurve ); // 2013

            Arc geomArc = Arc.Create(end0, end1, pointOnCurve); // 2014

#if NEED_PLANE
            // Create a geometry plane

            XYZ origin = new XYZ(0, 0, 0);
            XYZ normal = new XYZ(1, 1, 0);

            Plane geomPlane = creApp.NewPlane(
                normal, origin);

            // Create a sketch plane in current document

            SketchPlane sketch = creDoc.NewSketchPlane(
                geomPlane);
#endif // NEED_PLANE

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create Detail Line and Arc");

                // Create a DetailLine element using the
                // newly created geometry line and sketch plane

                DetailLine line = creDoc.NewDetailCurve(
                    view, geomLine) as DetailLine;

                // Create a DetailArc element using the
                // newly created geometry arc and sketch plane

                DetailArc arc = creDoc.NewDetailCurve(
                    view, geomArc) as DetailArc;

                // Change detail curve colour.
                // Initially, this only affects the newly
                // created curves. However, when the view
                // is refreshed, all detail curves will
                // be updated.

                GraphicsStyle gs = arc.LineStyle as GraphicsStyle;

                gs.GraphicsStyleCategory.LineColor
                    = new Color(250, 10, 10);

                tx.Commit();
            }
            return(Result.Succeeded);
        }
Ejemplo n.º 34
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Hello World
            //TaskDialog.Show("VL title", "VL says Hello Revit");

            var uiApp = commandData.Application;
            var app   = commandData.Application.Application;
            var uiDoc = commandData.Application.ActiveUIDocument;
            var doc   = commandData.Application.ActiveUIDocument.Document;


            #region 放置类型为"0762*2032 mm"的门
            //首先通过类型过滤出 类型为门的族类型,找到名称相同的
            string       doorTypeName = "0762*2032 mm";
            FamilySymbol doorType     = null;
            var          filter       = new LogicalAndFilter(
                new ElementCategoryFilter(BuiltInCategory.OST_Doors),
                new ElementClassFilter(typeof(FamilySymbol))
                );
            var  collector   = new FilteredElementCollector(doc).WherePasses(filter);
            bool symbolFound = collector.FirstOrDefault(c => c.Name == doorTypeName) != null;
            //如果没有则通过文件加载族
            if (symbolFound)
            {
                doorType = collector.FirstOrDefault(c => c.Name == doorTypeName) as FamilySymbol;
            }
            else
            {
                string file = @"familyFilePath";
                Family family;
                if (doc.LoadFamily(file, out family))
                {
                    var validType = family.GetValidTypes().FirstOrDefault(c =>
                    {
                        var symbol = (doc.GetElement(c) as FamilySymbol);
                        if (symbol != null && symbol.Name == doorTypeName)
                        {
                            return(true);
                        }
                        return(false);
                    });
                    if (validType != null)
                    {
                        doorType    = doc.GetElement(validType) as FamilySymbol;
                        symbolFound = true;
                    }
                }
            }
            //使用族类型创建门 线性的门是有着LocationCurve的且LocationCurve.Curve为Line的元素
            Wall wall = null;
            if (doorType != null)
            {
                Element element = new FilteredElementCollector(doc)
                                  .WherePasses(new ElementClassFilter(typeof(Wall)))
                                  .FirstOrDefault(c =>
                {
                    var locationCurve = c.Location as LocationCurve;
                    if (locationCurve != null)
                    {
                        var line = locationCurve.Curve as Line;
                        if (line != null)
                        {
                            return(true);
                        }
                        return(false);
                    }
                    return(false);
                });
                if (element != null)
                {
                    wall = element as Wall;
                }
            }
            //在墙的中心创建一个门
            if (wall != null)
            {
                var            line          = (wall.Location as LocationCurve).Curve as Line;
                var            wallLevel     = doc.GetElement(wall.LevelId) as Level;
                XYZ            midPoint      = (line.GetEndPoint(0) + line.GetEndPoint(1)) / 2;
                var            structureType = Autodesk.Revit.DB.Structure.StructuralType.NonStructural;
                FamilyInstance door          = doc.Create.NewFamilyInstance(midPoint, doorType, wall, wallLevel, structureType);
            }
            #endregion

            #region  制墙类型
            var wallElementId = 1111;
            wall = doc.GetElement(new ElementId(wallElementId)) as Wall;
            if (wall != null)
            {
                var         wallType       = wall.WallType;
                ElementType duplicatedType = wallType.Duplicate(wall.Name + "duplicated");
            }
            #endregion

            #region 元素移动
            VLTransactionHelper.DelegateTransaction(doc, "创建一根柱子", () =>
            {
                //Revit文档的创建句柄
                Autodesk.Revit.Creation.Document creator = doc.Create;
                XYZ origin              = new XYZ(0, 0, 0);
                Level level             = doc.GetElement(new ElementId(12122)) as Level;
                FamilySymbol columnType = doc.GetElement(new ElementId(12123)) as FamilySymbol;
                var structureType       = Autodesk.Revit.DB.Structure.StructuralType.Column;
                FamilyInstance column   = creator.NewFamilyInstance(origin, columnType, level, structureType);
                XYZ newPlace            = new XYZ(10, 20, 30);
                ElementTransformUtils.MoveElement(doc, column.Id, newPlace);
                return(true);
            });
            #endregion

            #region ElementTransformUtils
            //ElementTransformUtils.CopyElement();
            //ElementTransformUtils.CopyElements();
            //ElementTransformUtils.MirrorElement();
            //ElementTransformUtils.MirrorElements();
            //ElementTransformUtils.MoveElement();
            //ElementTransformUtils.MoveElements();
            //ElementTransformUtils.RotateElement();
            //ElementTransformUtils.RotateElements();
            #endregion

            #region 元素旋转
            VLTransactionHelper.DelegateTransaction(doc, "ElementTransformUtils旋转方法", () =>
            {
                LocationCurve wallLine = wall.Location as LocationCurve;
                XYZ p1    = wallLine.Curve.GetEndPoint(0);
                XYZ p2    = new XYZ(p1.X, p1.Y, 30);
                Line axis = Line.CreateBound(p1, p2);
                ElementTransformUtils.RotateElement(doc, wall.Id, axis, Math.PI / 3);//逆时针60°
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "LocationCurve,LocationPoint,自带的旋转方法", () =>
            {
                LocationCurve locationCurve = wall.Location as LocationCurve;//线性坐标自带线
                if (locationCurve != null)
                {
                    Curve curve = locationCurve.Curve;
                    var start   = curve.GetEndPoint(0);
                    Line axis   = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationCurve.Rotate(axis, Math.PI);//PI=180°
                }
                LocationPoint locationPoint = wall.Location as LocationPoint;
                if (locationPoint != null)
                {
                    var start = locationPoint.Point;
                    Line axis = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationPoint.Rotate(axis, Math.PI);
                }
                return(true);
            });
            #endregion

            #region 元素镜像
            VLTransactionHelper.DelegateTransaction(doc, "元素镜像", () =>
            {
                Plane plane = new Plane(XYZ.BasisX, XYZ.Zero);
                if (ElementTransformUtils.CanMirrorElement(doc, wall.Id))
                {
                    ElementTransformUtils.MirrorElement(doc, wall.Id, plane);
                }
                return(true);
            });
            #endregion

            #region 元素删除
            //var deleteElements = Document.Delete(@ElementIds);
            #endregion

            #region 元素组合
            VLTransactionHelper.DelegateTransaction(doc, "元素组合", () =>
            {
                List <ElementId> elementIds = new List <ElementId>()
                {
                    new ElementId(1000),
                    new ElementId(1001),
                    new ElementId(1002),
                };
                Group group = doc.Create.NewGroup(elementIds);
                return(true);
            });
            #endregion

            #region 元素编辑
            VLTransactionHelper.DelegateTransaction(doc, "创建参照平面", () =>
            {
                XYZ bubbleEnd = new XYZ(0, 5, 5);
                XYZ freeEnd   = new XYZ(5, 5, 5);
                XYZ cutVector = XYZ.BasisY;
                View view     = doc.ActiveView;
                ReferencePlane referencePlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVector, view);
                referencePlane.Name           = "MyReferencePlane";
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "创建参照线,由模型线-转>参照线", () =>
            {
                ModelCurve modelCurve = doc.GetElement(new ElementId(1000)) as ModelCurve;//ModelCurve模型线
                modelCurve.ChangeToReferenceLine();
                //modelCurve.IsReferenceLine;
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "通过标高创建草图平面,然后在草图平面创建模型线", () =>
            {
                Level level             = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).FirstOrDefault() as Level;
                Line line               = Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 0));
                SketchPlane sketchPlane = SketchPlane.Create(doc, level.Id);
                ModelCurve modelLine    = doc.FamilyCreate.NewModelCurve(line, sketchPlane);
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "使用拉身体获取相应的草图平面", () =>
            {
                Extrusion extrusion         = doc.GetElement(new ElementId(11212)) as Extrusion;
                SketchPlane sketchPlane     = extrusion.Sketch.SketchPlane;
                CurveArrArray sketchProfile = extrusion.Sketch.Profile;
                return(true);
            });
            #endregion

            #region 族
            string       tagName   = "梁平法_集中标_左对齐";
            FamilySymbol tagSymbol = null;
            //查找族类型
            var symbols = new FilteredElementCollector(doc)
                          .WherePasses(new ElementClassFilter(typeof(FamilySymbol)))
                          .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_StructuralFramingTags));
            var targetSymbol = symbols.FirstOrDefault(c => c.Name == tagName);
            if (targetSymbol != null)
            {
                tagSymbol = targetSymbol as FamilySymbol;
            }
            //空时加载族类型
            if (tagSymbol == null)
            {
                var    symbolFile = @"E:\WorkingSpace\Tasks\0526标注\梁平法_集中标_左对齐.rfa";
                Family family;
                if (doc.LoadFamily(symbolFile, out family))
                {
                    foreach (ElementId typeId in family.GetValidTypes())
                    {
                        var validType = doc.GetElement(typeId) as FamilySymbol;
                        if (validType != null && validType.Name == tagName)
                        {
                            tagSymbol = validType;
                            break;
                        }
                    }
                }
                else
                {
                    TaskDialogShow("加载族文件失败");
                }
            }
            //如果上述两者获取到了对应的族
            if (tagSymbol != null)
            {
                //doc.Create.NewFamilyInstance(, tagSymbol);
            }
            #endregion

            #region 建筑建模

            VLTransactionHelper.DelegateTransaction(doc, "修改标高的基面", () =>
            {
                var levelId         = 111;
                Level level         = doc.GetElement(new ElementId(levelId)) as Level;
                LevelType levelType = doc.GetElement(level.GetTypeId()) as LevelType;


                return(true);
            });


            #endregion

            return(Result.Succeeded);
        }
Ejemplo n.º 35
0
        /// <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);
        }
Ejemplo n.º 36
0
 public Creator(Document doc)
 {
     _doc    = doc;
     _credoc = doc.Create;
     _creapp = doc.Application.Create;
 }
Ejemplo n.º 37
0
 /// <summary>
 /// The construct of ExtrusionRoofManager class.
 /// </summary>
 /// <param name="commandData">A reference to the commandData.</param>
 public FootPrintRoofManager(ExternalCommandData commandData)
 {
     m_commandData = commandData;
     m_creationDoc = m_commandData.Application.ActiveUIDocument.Document.Create;
     m_creationApp = m_commandData.Application.Application.Create;
 }