Exemplo n.º 1
0
        /// <summary>
        /// Update the selected grid extents to match the grid extents is the source view
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            //StringBuilder sb = new StringBuilder();

            //Select the grid to update
            //Reference re = uidoc.Selection.PickObject(ObjectType.Element, "Select Grid");

            GenericSelectionFilter gridFilter = new GenericSelectionFilter("Grids");

            IList <Reference> selectedGrids = uidoc.Selection.PickObjects(ObjectType.Element, gridFilter, "Select Grids");

            //Grid extent to copy from
            View source = null;

            using (var form = new FormAddActiveView("Enter Source View Name"))
            {
                form.ShowDialog();
                //if the user hits cancel just drop out of macro
                if (form.DialogResult == forms.DialogResult.Cancel)
                {
                    return(Result.Cancelled);
                }

                string viewName = form.TextString.ToString();

                source = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements()
                         .Where(x => x.Name == viewName).First() as View;
            }


            using (Transaction t = new Transaction(doc, "set grid"))
            {
                t.Start();

                foreach (Reference re in selectedGrids)
                {
                    try
                    {
                        CopyGridExtent(doc, source, re);
                    }
                    catch (Exception ex)
                    {
                        Grid grid = doc.GetElement(re) as Grid;
                        TaskDialog.Show("Error", $"Error with {grid.Name} \n{ex.Message}");
                    }
                }

                t.Commit();
            }



            return(Result.Succeeded);
        }
Exemplo n.º 2
0
        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          activeView = doc.ActiveView;

            using (var form = new FormAddActiveView("Enter parameter"))
            {
                using (Transaction t = new Transaction(doc))
                {
                    string interrupt = "False";

                    while (interrupt == "False")
                    {
                        //use ShowDialog to show the form as a modal dialog box.
                        form.ShowDialog();

                        //if the user hits cancel just drop out of macro
                        if (form.DialogResult == forms.DialogResult.Cancel)
                        {
                            return(Result.Cancelled);
                        }

                        t.Start("Select By Parameter");

                        string userMessage = form.TextString.ToString();

                        Helpers.SelectAllElementsInView(uidoc, userMessage);


                        t.Commit();
                    }//close while
                }
            }

            return(Result.Succeeded);
        }
Exemplo n.º 3
0
        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;


            try
            {
                using (var form = new FormAddActiveView("Enter database table name"))
                {
                    form.ShowDialog();

                    if (form.DialogResult == winForm.DialogResult.Cancel)
                    {
                        return(Result.Cancelled);
                    }

                    string tableName = form.TextString;

                    string filePath = doc.PathName;

                    var fileInfo = new FileInfo(filePath);

                    long fileSize = fileInfo.Length;

                    FilteredElementCollector fecElements = new FilteredElementCollector(doc).WhereElementIsNotElementType();
                    FilteredElementCollector fecTypes    = new FilteredElementCollector(doc).WhereElementIsElementType();

                    FilteredElementCollector fecSheets    = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WhereElementIsNotElementType();
                    FilteredElementCollector fecViews     = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).WhereElementIsNotElementType();
                    FilteredElementCollector fecViewPorts = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Viewports).WhereElementIsNotElementType();


#if REVIT2017
                    int countWarnings = 0;
#else
                    int countWarnings = doc.GetWarnings().Count;
#endif
                    int countElements = fecElements.Count();
                    int countTypes    = fecTypes.Count();

                    int countSheets    = fecSheets.Count();
                    int countViews     = fecViews.Count();
                    int countViewPorts = fecViewPorts.Count();

                    int viewsNotOnSheet = Helpers.CountViewsNotOnSheet(fecViews).Count;

                    DateTime dateo = DateTime.Now;
                    string   time  = $"{dateo.Hour}h{dateo.Minute}m{dateo.Second}s";

                    string formatDate = $"{dateo.Year}{dateo.Month}{dateo.Day.ToString().PadLeft(2, '0')}_{time}";


                    string        outputFile = $"{doc.ProjectInformation.BuildingName}\\{Environment.UserName}_{formatDate}.csv";
                    StringBuilder sb         = new StringBuilder();

                    if (Helpers.InsertData(tableName, DateTime.Now, Environment.UserName,
                                           fileSize, countElements, countTypes, countSheets,
                                           countViews, countViewPorts, countWarnings, Helpers.CountPurgeableElements(doc), viewsNotOnSheet))
                    {
                        //File.WriteAllText(outputFile, "Date," +
                        //        "Username," +
                        //        "Total Warnings, " +
                        //        "File Size, " +
                        //        "Purgeable Elements, " +
                        //        "Total Elements\n");

                        //sb.AppendLine($"{DateTime.Now},{Environment.UserName},{countWarnings},{fileSize},{Helpers.CountPurgeableElements(doc)},{countElements}");

                        //File.AppendAllText(outputFile, sb.ToString());

                        TaskDialog.Show("result", $"File size: {(fileSize/1000000).ToString("#.##")}Mb\nWarnings: {countWarnings}");
                    }

                    return(Result.Succeeded);
                }
            }



            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }
Exemplo n.º 4
0
        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;

            IList <Reference> refe = uidoc.Selection.PickObjects(ObjectType.Element, "Select Viewports");

            IList <ElementId> viewportViewIds = new List <ElementId>();

            foreach (Reference r in refe)
            {
                Viewport vp = doc.GetElement(r) as Viewport;
                viewportViewIds.Add(vp.ViewId);
            }

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

            string errorMessage = "";

            int           counterTagged = 0;
            StringBuilder errorlog      = new StringBuilder();

            double xOffset = 0;

            using (var form = new FormAddActiveView("Tag X-offset [mm] from column centre"))
            {
                form.ShowDialog();

                //if the user hits cancel just drop out of macro
                if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    return(Result.Cancelled);
                }

                try
                {
                    xOffset = Int16.Parse(form.TextString) / 304.8;
                }
                catch
                {
                    xOffset = 0;
                }
            }

            using (Transaction t = new Transaction(doc, "Tag Elements in View"))
            {
                t.Start();

                foreach (ElementId viewId in viewportViewIds)
                {
                    FilteredElementCollector fec = new FilteredElementCollector(doc, viewId).WhereElementIsNotElementType();
                    foreach (Element ele in fec)
                    {
                        try
                        {
                            if (ele.Category.Name == "Structural Columns")
                            {
                                FamilyInstance fa = ele as FamilyInstance;

#if REVIT2017
                                CreateIndependentTagColumn(doc, fa, viewId, xOffset);
#elif REVIT2019
                                CreateIndependentTagColumn(doc, fa, viewId, xOffset);
#endif
                                counterTagged++;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ele.Category != null && ele.Category.Name == "Structural Columns")
                            {
                                errorMessage = ex.Message;
                                //TaskDialog.Show("Error", ex.Message);
                                errorlog.AppendLine($"{ele.Id}");
                            }
                        }
                    }
                }
                t.Commit();
            }


            TaskDialog.Show("result", $"{counterTagged} elements tagged. \nElement Id errors: \n{errorlog.ToString()}");

            return(Result.Succeeded);
        }
Exemplo n.º 5
0
        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          activeView = doc.ActiveView;

            using (var form = new FormAddActiveView("Enter Sheet Number"))
            {
                using (Transaction t = new Transaction(doc))
                {
                    string interrupt = "False";

                    while (interrupt == "False")
                    {
                        //use ShowDialog to show the form as a modal dialog box.



                        form.ShowDialog();

                        //if the user hits cancel just drop out of macro
                        if (form.DialogResult == forms.DialogResult.Cancel)
                        {
                            return(Result.Cancelled);
                        }



                        string sheetNumber = form.TextString.ToString();

                        ViewSheet viewSh = null;

                        FilteredElementCollector sheets = new FilteredElementCollector(doc).OfClass(typeof(ViewSheet));

                        foreach (ViewSheet sht in sheets)
                        {
                            if (sht.SheetNumber == sheetNumber)
                            {
                                viewSh = sht;
                            }
                        }

                        t.Start("Add view to sheet");

                        try
                        {
                            Viewport newvp = Viewport.Create(doc, viewSh.Id, activeView.Id, new XYZ(1.38, .974, 0));
                            interrupt = "True";
                            t.Commit();
                            if (null != viewSh)
                            {
                                uidoc.ActiveView = viewSh;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (sheetNumber == "")
                            {
                                TaskDialog.Show("Warning", "Please enter a sheet number");
                                t.RollBack();
                                //                                form.ShowDialog();
                            }

                            else if (viewSh == null)
                            {
                                TaskDialog.Show("Warning", "The sheet number does not exist");
                                t.RollBack();
                                //                          form.ShowDialog();
                            }

                            else
                            {
                                //TaskDialog.Show("Warning", "The view is already placed on another sheet");
                                TaskDialog.Show("Warning", ex.Message);
                                t.RollBack();
                                //                      form.ShowDialog();
                            }
                        } //close catch
                    }     //close while
                }
            }

            return(Result.Succeeded);
        }
Exemplo n.º 6
0
        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          activeView = doc.ActiveView;

            try
            {
                using (var form = new FormAddActiveView("Enter Sheet Number"))
                {
                    using (Transaction t = new Transaction(doc))
                    {
                        Reference legendRef = uidoc.Selection.PickObject(ObjectType.Element, "Select a Legend");

                        form.ShowDialog();

                        //if the user hits cancel just drop out of macro
                        if (form.DialogResult == forms.DialogResult.Cancel)
                        {
                            return(Result.Cancelled);
                        }

                        string sheetNumber = form.TextString.ToString();

                        List <ElementId> sheetIds = new List <ElementId>();

                        IEnumerable <ViewSheet> sheetItr = new FilteredElementCollector(doc).OfClass(typeof(ViewSheet)).ToElements().Cast <ViewSheet>();

                        foreach (ViewSheet e in sheetItr)
                        {
                            if (sheetNumber.Contains(e.SheetNumber))
                            {
                                sheetIds.Add(e.Id);
                            }
                        }



                        Viewport legendVp = doc.GetElement(legendRef) as Viewport;

                        ElementId legendId = legendVp.ViewId;

                        XYZ center = legendVp.GetBoxCenter();


                        // start the transaction
                        t.Start("Add Legend");

                        // loop through the list of sheet ids
                        foreach (ElementId sheetid in sheetIds)
                        {
                            Viewport.Create(doc, sheetid, legendId, center);
                        }

                        // commit the changes
                        t.Commit();
                    }
                }

                return(Result.Succeeded);
            }//close try

            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }
Exemplo n.º 7
0
        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          activeView = doc.ActiveView;

            using (var form = new FormAddActiveView("Enter Beam Identity Type Mark"))
            {
                using (Transaction t = new Transaction(doc))
                {
                    Reference selectedBeam = uidoc.Selection.PickObject(ObjectType.Element, "Select a beam");

                    FamilyInstance beam = doc.GetElement(selectedBeam) as FamilyInstance;

                    string interrupt = "False";

                    while (interrupt == "False")
                    {
                        //use ShowDialog to show the form as a modal dialog box.



                        form.ShowDialog();

                        //if the user hits cancel just drop out of macro
                        if (form.DialogResult == forms.DialogResult.Cancel)
                        {
                            return(Result.Cancelled);
                        }

                        string identityTypeMark = form.TextString.ToUpper().ToString();

                        FilteredElementCollector beamTypesCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming).WhereElementIsElementType();



                        var wte = beamTypesCollector.FirstOrDefault((e) =>
                        {
                            if (string.Equals(e.LookupParameter("Identity_Type Mark").AsString(), identityTypeMark))
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        });


                        ElementType et = wte as ElementType;


                        t.Start("Add view to sheet");

                        try
                        {
                            beam.ChangeTypeId(et.Id);
                            interrupt = "True";
                            t.Commit();
                        }
                        catch (Exception ex)
                        {
                            if (identityTypeMark == "")
                            {
                                TaskDialog.Show("Warning", "Please enter an identity type mark");
                                t.RollBack();
                                //                                form.ShowDialog();
                            }

                            else if (identityTypeMark == null)
                            {
                                TaskDialog.Show("Warning", "This identity type mark not exist");
                                t.RollBack();
                                //                          form.ShowDialog();
                            }

                            else
                            {
                                TaskDialog.Show("Warning", ex.Message);
                                t.RollBack();
                                //                      form.ShowDialog();
                            }
                        } //close catch
                    }     //close while
                }
            }

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


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

            Options geometryOptions = new Options();

            geometryOptions.ComputeReferences = false;

            GeometryElement geomElem = doc.GetElement(r).get_Geometry(geometryOptions);

            List <NurbSpline> cadSplines = new List <NurbSpline>();

            IList <XYZ>   controlPoints = new List <XYZ>();
            List <double> weights       = new List <double>();
            List <double> knots         = new List <double>();

            if (null != geomElem)
            {
                foreach (var o in geomElem)
                {
                    GeometryInstance gi = o as GeometryInstance;
                    GeometryElement  instanceGeometryElement = gi.GetInstanceGeometry();

                    foreach (GeometryObject instanceObj in instanceGeometryElement)
                    {
                        if (instanceObj.GetType().ToString().Contains("NurbSpline"))
                        {
                            //TaskDialog.Show("r", instanceObj.GetType().ToString());
                            NurbSpline nurb = instanceObj as NurbSpline;
                            cadSplines.Add(nurb);
                            controlPoints = nurb.CtrlPoints;
                            //weights = nurb.Weights;
                            weights = nurb.Weights.Cast <double>().ToList();
                            //knots = nurb.Knots;
                            knots = nurb.Knots.Cast <double>().ToList();
                        }
                        break;
                    }
                }
            }

            double scale = 0.3048;

            #region Test
            //List<XYZ> controlPoints = new List<XYZ>();
            //controlPoints.Add(new XYZ(0 / scale, 0 / scale, 0 / scale));
            //controlPoints.Add(new XYZ(5 / scale, 5 / scale, 2 / scale));
            //controlPoints.Add(new XYZ(10 / scale, 10 / scale, 5 / scale));
            //controlPoints.Add(new XYZ(15 / scale, 10 / scale, 5 / scale));
            //controlPoints.Add(new XYZ(20 / scale, 5 / scale, 4 / scale));
            //controlPoints.Add(new XYZ(25 / scale, 5 / scale, 3 / scale));

            //List<double> weights = new List<double>();
            //weights.Add(1.0);
            //weights.Add(1.0);
            //weights.Add(1.0);
            //weights.Add(1.0);
            //weights.Add(1.0);
            //weights.Add(1.0);

            //List<double> knots = new List<double>();
            //knots.Add(0); //1revit
            //knots.Add(0); //2
            //knots.Add(0); //3
            //knots.Add(0); //4
            //knots.Add(10.76); //5
            //knots.Add(21.51); //6
            //knots.Add(32.27); //7
            //knots.Add(32.27);
            //knots.Add(32.27); //9
            //knots.Add(32.27);//revit
            #endregion

            HermiteSpline hermspline = HermiteSpline.Create(controlPoints, false);

            //Curve nurbSpline = NurbSpline.Create(hermspline);
            Curve nurbSpline = NurbSpline.CreateCurve(3, knots, controlPoints, weights);

            //XYZ startPoint = nurbSpline.GetEndPoint(0);

            Transform nurbsTr = nurbSpline.ComputeDerivatives(0, true);

            XYZ startPoint = nurbsTr.Origin;
            //PrintPoint("a", nurbsTr.Origin);

            #region Test Plane
            //Plane geomPlane = Autodesk.Revit.DB.Plane.CreateByOriginAndBasis(nurbsTr.Origin, nurbsTr.BasisY.Normalize(), nurbsTr.BasisZ.Normalize());
            //Plane geomPlane = Autodesk.Revit.DB.Plane.CreateByOriginAndBasis(nurbSpline.GetEndPoint(0), nurbsTr.BasisY.Normalize(), nurbsTr.BasisZ.Normalize());
            //Frame f = new Frame(nurbSpline.GetEndPoint(0), nurbsTr.BasisY.Normalize(), nurbsTr.BasisZ.Normalize(), nurbsTr.BasisX.Normalize());
            //Plane geomPlane = Autodesk.Revit.DB.Plane.CreateByThreePoints(XYZ.Zero, XYZ.BasisX, XYZ.BasisZ);
            //Plane geomPlane = Plane.CreateByNormalAndOrigin(nurbsTr.BasisX.Normalize(), nurbSpline.GetEndPoint(1)); funziona
            //Plane geomPlane = Plane.CreateByThreePoints(startPoint, startPoint + nurbsTr.BasisX.Normalize(), startPoint + XYZ.BasisZ);
            #endregion
            //XYZ curveDir = controlPoints[1] - controlPoints[0];
            XYZ   curveDir  = nurbsTr.BasisX;
            XYZ   perpDir   = curveDir.CrossProduct(startPoint + XYZ.BasisZ).Normalize();
            Plane perpPlane = Plane.CreateByNormalAndOrigin(curveDir, startPoint);
            //Plane vertPlane = Plane.CreateByThreePoints(startPoint, perpPlane.XVec, XYZ.BasisZ);
            Plane vertPlane = perpPlane;

            //PrintPoint("per", perpDir);

            List <PtCoord> pointsCoordinates = new List <PtCoord>();

            using (var form = new FormAddActiveView("Enter coordinates in clockwise order"))
            {
                form.ShowDialog();

                //if the user hits cancel just drop out of macro
                if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    return(Result.Cancelled);
                }

                string[] inputs = form.TextString.Split(';');

                foreach (string coord in inputs)
                {
                    string[] xy = coord.Split(',');
                    pointsCoordinates.Add(new PtCoord(Double.Parse(xy[0]) / (scale * 1000), Double.Parse(xy[1]) / (scale * 1000)));
                }
            }

//			List<PtCoord> pointsCoordinates = new List<PtCoord>(){new PtCoord(5,0), new PtCoord(2,2), new PtCoord(-14,0), new PtCoord(2,-2)};

            List <XYZ> pts = VertexPoints(nurbsTr.Origin, pointsCoordinates, vertPlane);

            XYZ pt1 = nurbsTr.Origin;
            XYZ pt2 = pt1 + vertPlane.XVec * 5;
            XYZ pt3 = pt2 + vertPlane.YVec * 2 + vertPlane.XVec * 2;
            XYZ pt4 = pt3 - vertPlane.XVec * 12;
            XYZ pt5 = pt4 - vertPlane.YVec * 2 + vertPlane.XVec * 2;



            Line l1 = Line.CreateBound(pt1, pt2);
            Line l2 = Line.CreateBound(pt2, pt3);
            Line l3 = Line.CreateBound(pt3, pt4);
            Line l4 = Line.CreateBound(pt4, pt5);
            Line l5 = Line.CreateBound(pt5, pt1);
            //
            //			var profileLoop = CurveLoop.Create(new List<Curve>{l1, l2, l3, l4, l5});

            var profileLoop = LoopPoints(pts);

            //double rotAngle = -2.543 * Math.PI / 180;
            double rotAngle  = -15 * Math.PI / 180;
            var    transform = Transform.CreateRotationAtPoint(nurbsTr.BasisX, rotAngle, nurbsTr.Origin);

            profileLoop.Transform(transform);

            var loops = new List <CurveLoop> {
                profileLoop
            };

            var path = CurveLoop.Create(new List <Curve> {
                nurbSpline
            });

            WireframeBuilder builder = new WireframeBuilder();

            builder.AddCurve(nurbSpline);


            //Solid solid = GeometryCreationUtilities.CreateSweptGeometry(path,0,nurbSpline.GetEndParameter(0),loops);
            Solid solid = GeometryCreationUtilities.CreateFixedReferenceSweptGeometry(path, 0, nurbSpline.GetEndParameter(0), loops, XYZ.BasisZ);


            using (Transaction t = new Transaction(doc, "create spline"))
            {
                t.Start();

                ElementId categoryId = new ElementId(BuiltInCategory.OST_Floors);

                DirectShape ds = DirectShape.CreateElement(doc, categoryId);

                ds.SetShape(builder);

                ds.Name = "RhinoSpline";

                SketchPlane sp = SketchPlane.Create(doc, vertPlane);
                uidoc.ActiveView.SketchPlane = sp;

                //uidoc.ActiveView.ShowActiveWorkPlane();

                ModelLine line1 = doc.Create.NewModelCurve(l1, sp) as ModelLine;
                ModelLine line2 = doc.Create.NewModelCurve(l2, sp) as ModelLine;
                ModelLine line3 = doc.Create.NewModelCurve(l3, sp) as ModelLine;
                ModelLine line4 = doc.Create.NewModelCurve(l4, sp) as ModelLine;
                ModelLine line5 = doc.Create.NewModelCurve(l5, sp) as ModelLine;

                List <GeometryObject> gs = new List <GeometryObject>();
                gs.Add(solid);

                //DirectShape directShape = DirectShape.CreateElement(doc, categoryId);
                ds.AppendShape(gs);

                t.Commit();
            }

            return(Result.Succeeded);
        }