Example #1
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            try
            {
                m_project = commandData.Application.ActiveUIDocument;

                // Get the selected element and store it to data member.
                if (!GetSelectedElement())
                {
                    message = m_errorInformation;
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // Create a BoundingBoxXYZ instance which used in NewViewSection() method
                if (!GenerateBoundingBoxXYZ())
                {
                    message = m_errorInformation;
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // Create a section view.
                Transaction transaction = new Transaction(m_project.Document, "CreateSectionView");
                transaction.Start();
                //ViewSection section = m_project.Document.Create.NewViewSection(m_box);
                ElementId       DetailViewId = new ElementId(-1);
                IList <Element> elems        = new FilteredElementCollector(m_project.Document).OfClass(typeof(ViewFamilyType)).ToElements();
                foreach (Element e in elems)
                {
                    ViewFamilyType v = e as ViewFamilyType;

                    if (v != null && v.ViewFamily == ViewFamily.Detail)
                    {
                        DetailViewId = e.Id;
                        break;
                    }
                }
                ViewSection section = ViewSection.CreateDetail(m_project.Document, DetailViewId, m_box);
                if (null == section)
                {
                    message = "Can't create the ViewSection.";
                    return(Autodesk.Revit.UI.Result.Failed);
                }

                // Modify some parameters to make it look better.
                section.get_Parameter(BuiltInParameter.VIEW_DETAIL_LEVEL).Set(2);
                transaction.Commit();

                // If everything goes right, give successful information and return succeeded.
                TaskDialog.Show("Revit", "Create view section succeeded.");
                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Example #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;

            // get view types
            FilteredElementCollector viewCol
                = new FilteredElementCollector(doc)
                  .WhereElementIsElementType()
                  .OfClass(typeof(ViewFamilyType));

            ViewFamilyType viewFamilyTypeFP = null;
            ViewFamilyType viewFamilyTypeS  = null;
            ViewFamilyType viewFamilyTypeD  = null;

            foreach (ViewFamilyType view in viewCol)
            {
                if (view.ViewFamily == ViewFamily.FloorPlan)
                {
                    viewFamilyTypeFP = view;
                }
                if (view.ViewFamily == ViewFamily.Section)
                {
                    viewFamilyTypeS = view;
                }
                if (view.ViewFamily == ViewFamily.Detail)
                {
                    viewFamilyTypeD = view;
                }
            }

            // collecting categories which must be visible (structural stiffener, structural column and text note
            List <ElementId> categoriesToShow = new List <ElementId>();

            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_StructuralStiffener)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_StructuralColumns)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_TextNotes)
                                 .ToElements()
                                 .First().Category.Id);
            categoriesToShow.Add(new FilteredElementCollector(doc)
                                 .OfCategory(BuiltInCategory.OST_Dimensions)
                                 .ToElements()
                                 .First().Category.Id);

            // declaring elementsCol and elementsToHide variables
            Categories categories = doc.Settings.Categories;
            TextNote   textNote;
            Leader     leader;
            ElementId  defaultTextNoteTypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);


            // retrieve elements from database
            FilteredElementCollector col
                = new FilteredElementCollector(doc)
                  .WhereElementIsNotElementType()
                  .OfCategory(BuiltInCategory.OST_StructuralStiffener);

            // create a list to save the types already handled
            List <string> typesHandled = new List <string>();

            // modify document within a transaction
            using (Transaction tx = new Transaction(doc))
            {
                bool warningKey = true;
                tx.Start("Criar detalhe das chapas");
                // get first element for tests
                foreach (Element e in col)
                {
                    // handling plate type with comment
                    Parameter commentParam = e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);

                    // checking comment param
                    if (commentParam.AsString() == null)
                    {
                        if (warningKey)
                        {
                            System.Windows.Forms.MessageBox.Show("Foi encontrada uma chapa sem indicação de tipo, " +
                                                                 "ela será ignorada pelo add-in.", "Aviso");
                            warningKey = false;
                        }
                        continue;
                    }

                    string[] splittedParam = (from str in commentParam.AsString().Split(_Separators)
                                              select str.ToLower())
                                             .ToArray();

                    int plateType = 0;
                    try
                    {
                        plateType = int.Parse(splittedParam.Last().Split(' ').Last());
                    }
                    catch (Exception)
                    {
                        System.Windows.Forms.MessageBox.Show("Problemas ao identificar o tipo da chapa. " +
                                                             splittedParam.Last(), "Erro");
                        tx.RollBack();
                        return(Result.Failed);
                    }

                    if (typesHandled.ToArray().Intersect(splittedParam).Any())
                    {
                        continue;
                    }

                    List <View> existingViews = new List <View>();
                    if (!CheckNameAvailability(doc, plateType, ref existingViews))
                    {
                        switch (AskOverwriteDetailView(plateType))
                        {
                        case System.Windows.Forms.DialogResult.Yes:
                            doc.Delete((from view in existingViews select view.Id).ToList());
                            break;

                        case System.Windows.Forms.DialogResult.No:
                            tx.RollBack();
                            return(Result.Cancelled);

                        case System.Windows.Forms.DialogResult.Cancel:
                            tx.RollBack();
                            return(Result.Cancelled);
                        }
                    }

                    // get boundingbox of element
                    BoundingBoxXYZ ebbox = e.get_BoundingBox(null);
                    double         w     = ebbox.Max.X - ebbox.Min.X;
                    double         d     = ebbox.Max.Y - ebbox.Min.Y;
                    double         h     = ebbox.Max.Z - ebbox.Min.Z;

                    // creating boundingbox for vertical view section
                    BoundingBoxXYZ vBbox = new BoundingBoxXYZ();
                    vBbox.Enabled = true;
                    vBbox.Max     = new XYZ(w + 0.2, h + 2, d + 0.2);
                    vBbox.Min     = new XYZ(-w - 0.2, -h - 0.2, -d - 0.2);

                    // creating boundingbox for horizontal view section
                    BoundingBoxXYZ hBbox = new BoundingBoxXYZ();
                    hBbox.Enabled = true;
                    hBbox.Max     = new XYZ(w + 0.2, d + 0.2, h + 0.2);
                    hBbox.Min     = new XYZ(-w - 0.2, -d - 0.2, -h - 0.2);

                    // set the transform
                    Transform vTrans = Transform.Identity;
                    Transform hTrans = Transform.Identity;

                    // find the element mid point
                    XYZ midPt = 0.5 * (ebbox.Max + ebbox.Min);

                    // set it as origin
                    vTrans.Origin = midPt;
                    hTrans.Origin = midPt;

                    // determine view direction for vView
                    vTrans.BasisX = XYZ.BasisX;
                    vTrans.BasisY = XYZ.BasisZ;
                    vTrans.BasisZ = -XYZ.BasisY;

                    // determine view direction for hView
                    hTrans.BasisX = -XYZ.BasisX;
                    hTrans.BasisY = XYZ.BasisY;
                    hTrans.BasisZ = -XYZ.BasisZ;

                    // transforming
                    vBbox.Transform = vTrans;
                    hBbox.Transform = hTrans;

                    // creating vertical view section
                    ViewSection vView = ViewSection.CreateDetail(doc, viewFamilyTypeD.Id, vBbox);

                    // hidding categories in vertical view section
                    foreach (Category category in categories)
                    {
                        if (!categoriesToShow.Contains(category.Id) &&
                            vView.CanCategoryBeHidden(category.Id))
                        {
                            vView.SetCategoryHidden(category.Id, true);
                        }
                    }

                    // scale
                    int scaleValue = 20;

                    // configuring vertical view properties
                    vView.Name           = MakeViewNames(plateType)[0];
                    vView.DetailLevel    = ViewDetailLevel.Fine;
                    vView.DisplayStyle   = DisplayStyle.FlatColors;
                    vView.CropBoxVisible = false;
                    vView.Scale          = scaleValue;

                    // creating textNotes
                    String text0 = "LIGAÇÃO COLUNA X CHAPA \nFEITA ATRAVÉS DE SOLDA";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text0, defaultTextNoteTypeId);
                    //leader = textNote.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_R);
                    //leader.End = vBbox.Transform.Origin + new XYZ(0, -5, 0);

                    String text1 = "CHUMBAR CHAPA COM ADESIVO \nEPOXI SIKADUR 32 OU SIMILAR" +
                                   "\nVERIFICAR MODO DE UTILIZAÇÃO \nJUNTO AO FORNECEDOR";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text1, defaultTextNoteTypeId);
                    //leader = textNote.AddLeader(TextNoteLeaderTypes.TNLT_STRAIGHT_L);
                    //leader.End = vBbox.Transform.Origin + new XYZ(0, -50, 0);

                    String text2 = "PREENCHER COM EPS";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text2, defaultTextNoteTypeId);

                    String text3 = "CHUMBAR CHAPA \nCOM ADESIVO EPOXI";
                    textNote = TextNote.Create(doc, vView.Id, vBbox.Transform.Origin + new XYZ(0, 12, 3), text3, defaultTextNoteTypeId);

                    // creating horizontal view section
                    ViewSection hView = ViewSection.CreateDetail(doc, viewFamilyTypeD.Id, hBbox);

                    // hidding categories in horizontal view section
                    foreach (Category category in categories)
                    {
                        if (!categoriesToShow.Contains(category.Id) &&
                            hView.CanCategoryBeHidden(category.Id))
                        {
                            hView.SetCategoryHidden(category.Id, true);
                        }
                    }

                    // configuring hView properties
                    hView.Name           = MakeViewNames(plateType)[1];
                    hView.DetailLevel    = ViewDetailLevel.Fine;
                    hView.DisplayStyle   = DisplayStyle.HLR;
                    hView.CropBoxVisible = false;
                    hView.Scale          = scaleValue;

                    // adding type handled to list
                    typesHandled.Add(String.Format("tipo {0}", (plateType).ToString()));
                }
                tx.Commit();
            }

            return(Result.Succeeded);
        }
        private void sectionViewBeamY(Element myElemt, double atX)
        {
            UIDocument UiDoc = this.ActiveUIDocument;
            Document   doc   = UiDoc.Document;

            Element elem = myElemt;

            ElementId elemTypeId = elem.GetTypeId();
            Element   elemType   = doc.GetElement(elemTypeId);


            LocationCurve lc = elem.Location as LocationCurve;

            Line line = lc.Curve as Line;

            // tao BoundingBox (tham so thu 3)

            XYZ p = line.GetEndPoint(0);
            XYZ q = line.GetEndPoint(1);
            XYZ v = q - p;         // Vector equation of line

            v = v.Normalize();

            //Set boundingBox
            BoundingBoxXYZ bb   = elem.get_BoundingBox(null);
            double         minZ = bb.Min.Z;
            double         maxZ = bb.Max.Z;

            double minY = bb.Min.Y;
            double maxY = bb.Max.Y;

            //lay cac thong so kich thuoc dam, get parameter of beam

            double l = v.GetLength();           // length of beam (endpoint - start Point)
            double h = maxZ - minZ;             // h of beam
            double b = maxY - minY;             // b of beam

            //Distance from point to vector
            XYZ point = bb.Max;

            // Tính toán dien tich tam giac

            double b2 = 4 * Math.Abs((q.X - p.X) * (point.Y - p.Y) - (point.X - p.X) * (q.Y - p.Y)) /
                        Math.Sqrt(Math.Pow(q.X - p.X, 2) + Math.Pow(q.Y - p.Y, 2));

            double wv = Math.Min(b2 / 2, h / 2); //width of view

            double offset = 1;                   // khoang cach offset


            XYZ max = new XYZ(wv + offset, offset, 1);
            XYZ min = new XYZ(-wv - offset, -offset - h, 0);


            // Type view Family
            ViewFamilyType vft = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType))
                                 .Cast <ViewFamilyType>()
                                 .FirstOrDefault <ViewFamilyType>(x =>
                                                                  ViewFamily.Detail == x.ViewFamily);

            // origin at the center of the location curve
            Transform curveTransform = lc.Curve.ComputeDerivatives(0.5, true);

            // The transform contains the location curve

            XYZ origin  = curveTransform.Origin - v * (0.5 - atX); // Set tam cua section View la origin cua curve Transform
            XYZ viewdir = curveTransform.BasisX.Normalize();       // view dir da bi xoay di 90 do
            XYZ up      = XYZ.BasisZ;                              // Huong len trung voi truc z
            XYZ right   = up.CrossProduct(viewdir);                // right theo tam dien thuan

            // Create a transform from vectors above.

            Transform transform = Transform.Identity;

            transform.Origin = origin;
            transform.BasisX = right;
            transform.BasisY = up;
            transform.BasisZ = viewdir;


            BoundingBoxXYZ sectionBoxY = new BoundingBoxXYZ();

            sectionBoxY.Transform = transform;
            sectionBoxY.Min       = min;
            sectionBoxY.Max       = max;


            using (Transaction myTrans = new Transaction(doc, "Create view section of Beam")) {
                myTrans.Start();
//				ViewSection.CreateSection(doc, vft.Id, sectionBoxY);
                ViewSection.CreateDetail(doc, vft.Id, sectionBoxY);
                myTrans.Commit();
            }
        }